repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/modules/freebsdpkg.py
|
list_pkgs
|
python
|
def list_pkgs(versions_as_list=False, with_origin=False, **kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
with_origin : False
Return a nested dictionary containing both the origin name and version
for each installed package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
ret = {}
origins = {}
out = __salt__['cmd.run_stdout'](['pkg_info', '-ao'],
output_loglevel='trace',
python_shell=False)
pkgs_re = re.compile(r'Information for ([^:]+):\s*Origin:\n([^\n]+)')
for pkg, origin in pkgs_re.findall(out):
if not pkg:
continue
try:
pkgname, pkgver = pkg.rsplit('-', 1)
except ValueError:
continue
__salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver)
origins[pkgname] = origin
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
__context__['pkg.origin'] = origins
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
|
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
with_origin : False
Return a nested dictionary containing both the origin name and version
for each installed package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdpkg.py#L257-L319
|
[
"def iteritems(d, **kw):\n return d.iteritems(**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"
] |
# -*- coding: utf-8 -*-
'''
Remote package support using ``pkg_add(1)``
.. 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>`.
.. warning::
This module has been completely rewritten. Up to and including version
0.17.0, it supported ``pkg_add(1)``, but checked for the existence of a
pkgng local database and, if found, would provide some of pkgng's
functionality. The rewrite of this module has removed all pkgng support,
and moved it to the :mod:`pkgng <salt.modules.pkgng>` execution module. For
versions <= 0.17.0, the documentation here should not be considered
accurate. If your Minion is running one of these versions, then the
documentation for this module can be viewed using the :mod:`sys.doc
<salt.modules.sys.doc>` function:
.. code-block:: bash
salt bsdminion sys.doc pkg
This module acts as the default package provider for FreeBSD 9 and older. If
you need to use pkgng on a FreeBSD 9 system, you will need to override the
``pkg`` provider by setting the :conf_minion:`providers` parameter in your
Minion config file, in order to use pkgng.
.. code-block:: yaml
providers:
pkg: pkgng
More information on pkgng support can be found in the documentation for the
:mod:`pkgng <salt.modules.pkgng>` module.
This module will respect the ``PACKAGEROOT`` and ``PACKAGESITE`` environment
variables, if set, but these values can also be overridden in several ways:
1. :strong:`Salt configuration parameters.` The configuration parameters
``freebsdpkg.PACKAGEROOT`` and ``freebsdpkg.PACKAGESITE`` are recognized.
These config parameters are looked up using :mod:`config.get
<salt.modules.config.get>` and can thus be specified in the Master config
file, Grains, Pillar, or in the Minion config file. Example:
.. code-block:: yaml
freebsdpkg.PACKAGEROOT: ftp://ftp.freebsd.org/
freebsdpkg.PACKAGESITE: ftp://ftp.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
2. :strong:`CLI arguments.` Both the ``packageroot`` (used interchangeably with
``fromrepo`` for API compatibility) and ``packagesite`` CLI arguments are
recognized, and override their config counterparts from section 1 above.
.. code-block:: bash
salt -G 'os:FreeBSD' pkg.install zsh fromrepo=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packageroot=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packagesite=ftp://ftp2.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
.. note::
These arguments can also be passed through in states:
.. code-block:: yaml
zsh:
pkg.installed:
- fromrepo: ftp://ftp2.freebsd.org/
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import logging
import re
# Import salt libs
import salt.utils.data
import salt.utils.functools
import salt.utils.pkg
from salt.exceptions import CommandExecutionError, MinionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Load as 'pkg' on FreeBSD versions less than 10.
Don't load on FreeBSD 9 when the config option
``providers:pkg`` is set to 'pkgng'.
'''
if __grains__['os'] == 'FreeBSD' and float(__grains__['osrelease']) < 10:
providers = {}
if 'providers' in __opts__:
providers = __opts__['providers']
if providers and 'pkg' in providers and providers['pkg'] == 'pkgng':
log.debug('Configuration option \'providers:pkg\' is set to '
'\'pkgng\', won\'t load old provider \'freebsdpkg\'.')
return (False, 'The freebsdpkg execution module cannot be loaded: the configuration option \'providers:pkg\' is set to \'pkgng\'')
return __virtualname__
return (False, 'The freebsdpkg execution module cannot be loaded: either the os is not FreeBSD or the version of FreeBSD is >= 10.')
def _get_repo_options(fromrepo=None, packagesite=None):
'''
Return a list of tuples to seed the "env" list, which is used to set
environment variables for any pkg_add commands that are spawned.
If ``fromrepo`` or ``packagesite`` are None, then their corresponding
config parameter will be looked up with config.get.
If both ``fromrepo`` and ``packagesite`` are None, and neither
freebsdpkg.PACKAGEROOT nor freebsdpkg.PACKAGESITE are specified, then an
empty list is returned, and it is assumed that the system defaults (or
environment variables) will be used.
'''
root = fromrepo if fromrepo is not None \
else __salt__['config.get']('freebsdpkg.PACKAGEROOT', None)
site = packagesite if packagesite is not None \
else __salt__['config.get']('freebsdpkg.PACKAGESITE', None)
ret = {}
if root is not None:
ret['PACKAGEROOT'] = root
if site is not None:
ret['PACKAGESITE'] = site
return ret
def _match(names):
'''
Since pkg_delete requires the full "pkgname-version" string, this function
will attempt to match the package name with its version. Returns a list of
partial matches and package names that match the "pkgname-version" string
required by pkg_delete, and a list of errors encountered.
'''
pkgs = list_pkgs(versions_as_list=True)
errors = []
# Look for full matches
full_pkg_strings = []
out = __salt__['cmd.run_stdout'](['pkg_info'],
output_loglevel='trace',
python_shell=False)
for line in out.splitlines():
try:
full_pkg_strings.append(line.split()[0])
except IndexError:
continue
full_matches = [x for x in names if x in full_pkg_strings]
# Look for pkgname-only matches
matches = []
ambiguous = []
for name in set(names) - set(full_matches):
cver = pkgs.get(name)
if cver is not None:
if len(cver) == 1:
matches.append('{0}-{1}'.format(name, cver[0]))
else:
ambiguous.append(name)
errors.append(
'Ambiguous package \'{0}\'. Full name/version required. '
'Possible matches: {1}'.format(
name,
', '.join(['{0}-{1}'.format(name, x) for x in cver])
)
)
# Find packages that did not match anything
not_matched = \
set(names) - set(matches) - set(full_matches) - set(ambiguous)
for name in not_matched:
errors.append('Package \'{0}\' not found'.format(name))
return matches + full_matches, errors
def latest_version(*names, **kwargs):
'''
``pkg_add(1)`` is not capable of querying for remote packages, so this
function will always return results as if there is no package available for
install or upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
return '' if len(names) == 1 else dict((x, '') for x in names)
# 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.
with_origin : False
Return a nested dictionary containing both the origin name and version
for each specified package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
with_origin = kwargs.pop('with_origin', False)
ret = __salt__['pkg_resource.version'](*names, **kwargs)
if not salt.utils.data.is_true(with_origin):
return ret
# Put the return value back into a dict since we're adding a subdict
if len(names) == 1:
ret = {names[0]: ret}
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
def refresh_db(**kwargs):
'''
``pkg_add(1)`` does not use a local database of available packages, so this
function simply returns ``True``. it exists merely for API compatibility.
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__)
return True
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
**kwargs):
'''
Install package(s) using ``pkg_add(1)``
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo or packageroot
Specify a package repository from which to install. Overrides the
system default, as well as the PACKAGEROOT environment variable.
packagesite
Specify the exact directory from which to install the remote package.
Overrides the PACKAGESITE environment variable, if present.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
sources
A list of 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.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"}, {"bar": "salt://bar.deb"}]'
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
'''
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
packageroot = kwargs.get('packageroot')
if not fromrepo and packageroot:
fromrepo = packageroot
env = _get_repo_options(fromrepo, kwargs.get('packagesite'))
args = []
if pkg_type == 'repository':
args.append('-r') # use remote repo
args.extend(pkg_params)
old = list_pkgs()
out = __salt__['cmd.run_all'](
['pkg_add'] + args,
env=env,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
_rehash()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def remove(name=None, pkgs=None, **kwargs):
'''
Remove packages using ``pkg_delete(1)``
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"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets, errors = _match([x for x in pkg_params])
for error in errors:
log.error(error)
if not targets:
return {}
out = __salt__['cmd.run_all'](
['pkg_delete'] + targets,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
# Support pkg.delete to remove packages to more closely match pkg_delete
delete = salt.utils.functools.alias_function(remove, 'delete')
# No equivalent to purge packages, use remove instead
purge = salt.utils.functools.alias_function(remove, 'purge')
def _rehash():
'''
Recomputes internal hash table for the PATH variable. Use whenever a new
command is created during the current session.
'''
shell = __salt__['environ.get']('SHELL')
if shell.split('/')[-1] in ('csh', 'tcsh'):
__salt__['cmd.shell']('rehash', output_loglevel='trace')
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
'''
ret = file_dict(*packages)
files = []
for pkg_files in six.itervalues(ret['files']):
files.extend(pkg_files)
ret['files'] = files
return ret
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the
system's package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
files = {}
if packages:
match_pattern = '\'{0}-[0-9]*\''
cmd = ['pkg_info', '-QL'] + [match_pattern.format(p) for p in packages]
else:
cmd = ['pkg_info', '-QLa']
ret = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in ret['stderr'].splitlines():
errors.append(line)
pkg = None
for line in ret['stdout'].splitlines():
if pkg is not None and line.startswith('/'):
files[pkg].append(line)
elif ':/' in line:
pkg, fn = line.split(':', 1)
pkg, ver = pkg.rsplit('-', 1)
files[pkg] = [fn]
else:
continue # unexpected string
return {'errors': errors, 'files': files}
|
saltstack/salt
|
salt/modules/freebsdpkg.py
|
install
|
python
|
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
**kwargs):
'''
Install package(s) using ``pkg_add(1)``
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo or packageroot
Specify a package repository from which to install. Overrides the
system default, as well as the PACKAGEROOT environment variable.
packagesite
Specify the exact directory from which to install the remote package.
Overrides the PACKAGESITE environment variable, if present.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
sources
A list of 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.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"}, {"bar": "salt://bar.deb"}]'
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
'''
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
packageroot = kwargs.get('packageroot')
if not fromrepo and packageroot:
fromrepo = packageroot
env = _get_repo_options(fromrepo, kwargs.get('packagesite'))
args = []
if pkg_type == 'repository':
args.append('-r') # use remote repo
args.extend(pkg_params)
old = list_pkgs()
out = __salt__['cmd.run_all'](
['pkg_add'] + args,
env=env,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
_rehash()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
|
Install package(s) using ``pkg_add(1)``
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo or packageroot
Specify a package repository from which to install. Overrides the
system default, as well as the PACKAGEROOT environment variable.
packagesite
Specify the exact directory from which to install the remote package.
Overrides the PACKAGESITE environment variable, if present.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
sources
A list of 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.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"}, {"bar": "salt://bar.deb"}]'
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdpkg.py#L322-L425
|
[
"def list_pkgs(versions_as_list=False, with_origin=False, **kwargs):\n '''\n List the packages currently installed as a dict::\n\n {'<package_name>': '<version>'}\n\n with_origin : False\n Return a nested dictionary containing both the origin name and version\n for each installed package.\n\n .. versionadded:: 2014.1.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n if 'pkg.list_pkgs' in __context__:\n ret = copy.deepcopy(__context__['pkg.list_pkgs'])\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n if salt.utils.data.is_true(with_origin):\n origins = __context__.get('pkg.origin', {})\n return dict([\n (x, {'origin': origins.get(x, ''), 'version': y})\n for x, y in six.iteritems(ret)\n ])\n return ret\n\n ret = {}\n origins = {}\n out = __salt__['cmd.run_stdout'](['pkg_info', '-ao'],\n output_loglevel='trace',\n python_shell=False)\n pkgs_re = re.compile(r'Information for ([^:]+):\\s*Origin:\\n([^\\n]+)')\n for pkg, origin in pkgs_re.findall(out):\n if not pkg:\n continue\n try:\n pkgname, pkgver = pkg.rsplit('-', 1)\n except ValueError:\n continue\n __salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver)\n origins[pkgname] = origin\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n __context__['pkg.origin'] = origins\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n if salt.utils.data.is_true(with_origin):\n return dict([\n (x, {'origin': origins.get(x, ''), 'version': y})\n for x, y in six.iteritems(ret)\n ])\n return ret\n",
"def _get_repo_options(fromrepo=None, packagesite=None):\n '''\n Return a list of tuples to seed the \"env\" list, which is used to set\n environment variables for any pkg_add commands that are spawned.\n\n If ``fromrepo`` or ``packagesite`` are None, then their corresponding\n config parameter will be looked up with config.get.\n\n If both ``fromrepo`` and ``packagesite`` are None, and neither\n freebsdpkg.PACKAGEROOT nor freebsdpkg.PACKAGESITE are specified, then an\n empty list is returned, and it is assumed that the system defaults (or\n environment variables) will be used.\n '''\n root = fromrepo if fromrepo is not None \\\n else __salt__['config.get']('freebsdpkg.PACKAGEROOT', None)\n site = packagesite if packagesite is not None \\\n else __salt__['config.get']('freebsdpkg.PACKAGESITE', None)\n ret = {}\n if root is not None:\n ret['PACKAGEROOT'] = root\n if site is not None:\n ret['PACKAGESITE'] = site\n return ret\n",
"def _rehash():\n '''\n Recomputes internal hash table for the PATH variable. Use whenever a new\n command is created during the current session.\n '''\n shell = __salt__['environ.get']('SHELL')\n if shell.split('/')[-1] in ('csh', 'tcsh'):\n __salt__['cmd.shell']('rehash', output_loglevel='trace')\n"
] |
# -*- coding: utf-8 -*-
'''
Remote package support using ``pkg_add(1)``
.. 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>`.
.. warning::
This module has been completely rewritten. Up to and including version
0.17.0, it supported ``pkg_add(1)``, but checked for the existence of a
pkgng local database and, if found, would provide some of pkgng's
functionality. The rewrite of this module has removed all pkgng support,
and moved it to the :mod:`pkgng <salt.modules.pkgng>` execution module. For
versions <= 0.17.0, the documentation here should not be considered
accurate. If your Minion is running one of these versions, then the
documentation for this module can be viewed using the :mod:`sys.doc
<salt.modules.sys.doc>` function:
.. code-block:: bash
salt bsdminion sys.doc pkg
This module acts as the default package provider for FreeBSD 9 and older. If
you need to use pkgng on a FreeBSD 9 system, you will need to override the
``pkg`` provider by setting the :conf_minion:`providers` parameter in your
Minion config file, in order to use pkgng.
.. code-block:: yaml
providers:
pkg: pkgng
More information on pkgng support can be found in the documentation for the
:mod:`pkgng <salt.modules.pkgng>` module.
This module will respect the ``PACKAGEROOT`` and ``PACKAGESITE`` environment
variables, if set, but these values can also be overridden in several ways:
1. :strong:`Salt configuration parameters.` The configuration parameters
``freebsdpkg.PACKAGEROOT`` and ``freebsdpkg.PACKAGESITE`` are recognized.
These config parameters are looked up using :mod:`config.get
<salt.modules.config.get>` and can thus be specified in the Master config
file, Grains, Pillar, or in the Minion config file. Example:
.. code-block:: yaml
freebsdpkg.PACKAGEROOT: ftp://ftp.freebsd.org/
freebsdpkg.PACKAGESITE: ftp://ftp.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
2. :strong:`CLI arguments.` Both the ``packageroot`` (used interchangeably with
``fromrepo`` for API compatibility) and ``packagesite`` CLI arguments are
recognized, and override their config counterparts from section 1 above.
.. code-block:: bash
salt -G 'os:FreeBSD' pkg.install zsh fromrepo=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packageroot=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packagesite=ftp://ftp2.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
.. note::
These arguments can also be passed through in states:
.. code-block:: yaml
zsh:
pkg.installed:
- fromrepo: ftp://ftp2.freebsd.org/
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import logging
import re
# Import salt libs
import salt.utils.data
import salt.utils.functools
import salt.utils.pkg
from salt.exceptions import CommandExecutionError, MinionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Load as 'pkg' on FreeBSD versions less than 10.
Don't load on FreeBSD 9 when the config option
``providers:pkg`` is set to 'pkgng'.
'''
if __grains__['os'] == 'FreeBSD' and float(__grains__['osrelease']) < 10:
providers = {}
if 'providers' in __opts__:
providers = __opts__['providers']
if providers and 'pkg' in providers and providers['pkg'] == 'pkgng':
log.debug('Configuration option \'providers:pkg\' is set to '
'\'pkgng\', won\'t load old provider \'freebsdpkg\'.')
return (False, 'The freebsdpkg execution module cannot be loaded: the configuration option \'providers:pkg\' is set to \'pkgng\'')
return __virtualname__
return (False, 'The freebsdpkg execution module cannot be loaded: either the os is not FreeBSD or the version of FreeBSD is >= 10.')
def _get_repo_options(fromrepo=None, packagesite=None):
'''
Return a list of tuples to seed the "env" list, which is used to set
environment variables for any pkg_add commands that are spawned.
If ``fromrepo`` or ``packagesite`` are None, then their corresponding
config parameter will be looked up with config.get.
If both ``fromrepo`` and ``packagesite`` are None, and neither
freebsdpkg.PACKAGEROOT nor freebsdpkg.PACKAGESITE are specified, then an
empty list is returned, and it is assumed that the system defaults (or
environment variables) will be used.
'''
root = fromrepo if fromrepo is not None \
else __salt__['config.get']('freebsdpkg.PACKAGEROOT', None)
site = packagesite if packagesite is not None \
else __salt__['config.get']('freebsdpkg.PACKAGESITE', None)
ret = {}
if root is not None:
ret['PACKAGEROOT'] = root
if site is not None:
ret['PACKAGESITE'] = site
return ret
def _match(names):
'''
Since pkg_delete requires the full "pkgname-version" string, this function
will attempt to match the package name with its version. Returns a list of
partial matches and package names that match the "pkgname-version" string
required by pkg_delete, and a list of errors encountered.
'''
pkgs = list_pkgs(versions_as_list=True)
errors = []
# Look for full matches
full_pkg_strings = []
out = __salt__['cmd.run_stdout'](['pkg_info'],
output_loglevel='trace',
python_shell=False)
for line in out.splitlines():
try:
full_pkg_strings.append(line.split()[0])
except IndexError:
continue
full_matches = [x for x in names if x in full_pkg_strings]
# Look for pkgname-only matches
matches = []
ambiguous = []
for name in set(names) - set(full_matches):
cver = pkgs.get(name)
if cver is not None:
if len(cver) == 1:
matches.append('{0}-{1}'.format(name, cver[0]))
else:
ambiguous.append(name)
errors.append(
'Ambiguous package \'{0}\'. Full name/version required. '
'Possible matches: {1}'.format(
name,
', '.join(['{0}-{1}'.format(name, x) for x in cver])
)
)
# Find packages that did not match anything
not_matched = \
set(names) - set(matches) - set(full_matches) - set(ambiguous)
for name in not_matched:
errors.append('Package \'{0}\' not found'.format(name))
return matches + full_matches, errors
def latest_version(*names, **kwargs):
'''
``pkg_add(1)`` is not capable of querying for remote packages, so this
function will always return results as if there is no package available for
install or upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
return '' if len(names) == 1 else dict((x, '') for x in names)
# 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.
with_origin : False
Return a nested dictionary containing both the origin name and version
for each specified package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
with_origin = kwargs.pop('with_origin', False)
ret = __salt__['pkg_resource.version'](*names, **kwargs)
if not salt.utils.data.is_true(with_origin):
return ret
# Put the return value back into a dict since we're adding a subdict
if len(names) == 1:
ret = {names[0]: ret}
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
def refresh_db(**kwargs):
'''
``pkg_add(1)`` does not use a local database of available packages, so this
function simply returns ``True``. it exists merely for API compatibility.
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__)
return True
def list_pkgs(versions_as_list=False, with_origin=False, **kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
with_origin : False
Return a nested dictionary containing both the origin name and version
for each installed package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
ret = {}
origins = {}
out = __salt__['cmd.run_stdout'](['pkg_info', '-ao'],
output_loglevel='trace',
python_shell=False)
pkgs_re = re.compile(r'Information for ([^:]+):\s*Origin:\n([^\n]+)')
for pkg, origin in pkgs_re.findall(out):
if not pkg:
continue
try:
pkgname, pkgver = pkg.rsplit('-', 1)
except ValueError:
continue
__salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver)
origins[pkgname] = origin
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
__context__['pkg.origin'] = origins
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
def remove(name=None, pkgs=None, **kwargs):
'''
Remove packages using ``pkg_delete(1)``
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"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets, errors = _match([x for x in pkg_params])
for error in errors:
log.error(error)
if not targets:
return {}
out = __salt__['cmd.run_all'](
['pkg_delete'] + targets,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
# Support pkg.delete to remove packages to more closely match pkg_delete
delete = salt.utils.functools.alias_function(remove, 'delete')
# No equivalent to purge packages, use remove instead
purge = salt.utils.functools.alias_function(remove, 'purge')
def _rehash():
'''
Recomputes internal hash table for the PATH variable. Use whenever a new
command is created during the current session.
'''
shell = __salt__['environ.get']('SHELL')
if shell.split('/')[-1] in ('csh', 'tcsh'):
__salt__['cmd.shell']('rehash', output_loglevel='trace')
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
'''
ret = file_dict(*packages)
files = []
for pkg_files in six.itervalues(ret['files']):
files.extend(pkg_files)
ret['files'] = files
return ret
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the
system's package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
files = {}
if packages:
match_pattern = '\'{0}-[0-9]*\''
cmd = ['pkg_info', '-QL'] + [match_pattern.format(p) for p in packages]
else:
cmd = ['pkg_info', '-QLa']
ret = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in ret['stderr'].splitlines():
errors.append(line)
pkg = None
for line in ret['stdout'].splitlines():
if pkg is not None and line.startswith('/'):
files[pkg].append(line)
elif ':/' in line:
pkg, fn = line.split(':', 1)
pkg, ver = pkg.rsplit('-', 1)
files[pkg] = [fn]
else:
continue # unexpected string
return {'errors': errors, 'files': files}
|
saltstack/salt
|
salt/modules/freebsdpkg.py
|
remove
|
python
|
def remove(name=None, pkgs=None, **kwargs):
'''
Remove packages using ``pkg_delete(1)``
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"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets, errors = _match([x for x in pkg_params])
for error in errors:
log.error(error)
if not targets:
return {}
out = __salt__['cmd.run_all'](
['pkg_delete'] + targets,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
|
Remove packages using ``pkg_delete(1)``
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/freebsdpkg.py#L428-L487
|
[
"def list_pkgs(versions_as_list=False, with_origin=False, **kwargs):\n '''\n List the packages currently installed as a dict::\n\n {'<package_name>': '<version>'}\n\n with_origin : False\n Return a nested dictionary containing both the origin name and version\n for each installed package.\n\n .. versionadded:: 2014.1.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n if 'pkg.list_pkgs' in __context__:\n ret = copy.deepcopy(__context__['pkg.list_pkgs'])\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n if salt.utils.data.is_true(with_origin):\n origins = __context__.get('pkg.origin', {})\n return dict([\n (x, {'origin': origins.get(x, ''), 'version': y})\n for x, y in six.iteritems(ret)\n ])\n return ret\n\n ret = {}\n origins = {}\n out = __salt__['cmd.run_stdout'](['pkg_info', '-ao'],\n output_loglevel='trace',\n python_shell=False)\n pkgs_re = re.compile(r'Information for ([^:]+):\\s*Origin:\\n([^\\n]+)')\n for pkg, origin in pkgs_re.findall(out):\n if not pkg:\n continue\n try:\n pkgname, pkgver = pkg.rsplit('-', 1)\n except ValueError:\n continue\n __salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver)\n origins[pkgname] = origin\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n __context__['pkg.origin'] = origins\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n if salt.utils.data.is_true(with_origin):\n return dict([\n (x, {'origin': origins.get(x, ''), 'version': y})\n for x, y in six.iteritems(ret)\n ])\n return ret\n",
"def _match(names):\n '''\n Since pkg_delete requires the full \"pkgname-version\" string, this function\n will attempt to match the package name with its version. Returns a list of\n partial matches and package names that match the \"pkgname-version\" string\n required by pkg_delete, and a list of errors encountered.\n '''\n pkgs = list_pkgs(versions_as_list=True)\n errors = []\n\n # Look for full matches\n full_pkg_strings = []\n out = __salt__['cmd.run_stdout'](['pkg_info'],\n output_loglevel='trace',\n python_shell=False)\n for line in out.splitlines():\n try:\n full_pkg_strings.append(line.split()[0])\n except IndexError:\n continue\n full_matches = [x for x in names if x in full_pkg_strings]\n\n # Look for pkgname-only matches\n matches = []\n ambiguous = []\n for name in set(names) - set(full_matches):\n cver = pkgs.get(name)\n if cver is not None:\n if len(cver) == 1:\n matches.append('{0}-{1}'.format(name, cver[0]))\n else:\n ambiguous.append(name)\n errors.append(\n 'Ambiguous package \\'{0}\\'. Full name/version required. '\n 'Possible matches: {1}'.format(\n name,\n ', '.join(['{0}-{1}'.format(name, x) for x in cver])\n )\n )\n\n # Find packages that did not match anything\n not_matched = \\\n set(names) - set(matches) - set(full_matches) - set(ambiguous)\n for name in not_matched:\n errors.append('Package \\'{0}\\' not found'.format(name))\n\n return matches + full_matches, errors\n"
] |
# -*- coding: utf-8 -*-
'''
Remote package support using ``pkg_add(1)``
.. 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>`.
.. warning::
This module has been completely rewritten. Up to and including version
0.17.0, it supported ``pkg_add(1)``, but checked for the existence of a
pkgng local database and, if found, would provide some of pkgng's
functionality. The rewrite of this module has removed all pkgng support,
and moved it to the :mod:`pkgng <salt.modules.pkgng>` execution module. For
versions <= 0.17.0, the documentation here should not be considered
accurate. If your Minion is running one of these versions, then the
documentation for this module can be viewed using the :mod:`sys.doc
<salt.modules.sys.doc>` function:
.. code-block:: bash
salt bsdminion sys.doc pkg
This module acts as the default package provider for FreeBSD 9 and older. If
you need to use pkgng on a FreeBSD 9 system, you will need to override the
``pkg`` provider by setting the :conf_minion:`providers` parameter in your
Minion config file, in order to use pkgng.
.. code-block:: yaml
providers:
pkg: pkgng
More information on pkgng support can be found in the documentation for the
:mod:`pkgng <salt.modules.pkgng>` module.
This module will respect the ``PACKAGEROOT`` and ``PACKAGESITE`` environment
variables, if set, but these values can also be overridden in several ways:
1. :strong:`Salt configuration parameters.` The configuration parameters
``freebsdpkg.PACKAGEROOT`` and ``freebsdpkg.PACKAGESITE`` are recognized.
These config parameters are looked up using :mod:`config.get
<salt.modules.config.get>` and can thus be specified in the Master config
file, Grains, Pillar, or in the Minion config file. Example:
.. code-block:: yaml
freebsdpkg.PACKAGEROOT: ftp://ftp.freebsd.org/
freebsdpkg.PACKAGESITE: ftp://ftp.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
2. :strong:`CLI arguments.` Both the ``packageroot`` (used interchangeably with
``fromrepo`` for API compatibility) and ``packagesite`` CLI arguments are
recognized, and override their config counterparts from section 1 above.
.. code-block:: bash
salt -G 'os:FreeBSD' pkg.install zsh fromrepo=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packageroot=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packagesite=ftp://ftp2.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
.. note::
These arguments can also be passed through in states:
.. code-block:: yaml
zsh:
pkg.installed:
- fromrepo: ftp://ftp2.freebsd.org/
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import logging
import re
# Import salt libs
import salt.utils.data
import salt.utils.functools
import salt.utils.pkg
from salt.exceptions import CommandExecutionError, MinionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Load as 'pkg' on FreeBSD versions less than 10.
Don't load on FreeBSD 9 when the config option
``providers:pkg`` is set to 'pkgng'.
'''
if __grains__['os'] == 'FreeBSD' and float(__grains__['osrelease']) < 10:
providers = {}
if 'providers' in __opts__:
providers = __opts__['providers']
if providers and 'pkg' in providers and providers['pkg'] == 'pkgng':
log.debug('Configuration option \'providers:pkg\' is set to '
'\'pkgng\', won\'t load old provider \'freebsdpkg\'.')
return (False, 'The freebsdpkg execution module cannot be loaded: the configuration option \'providers:pkg\' is set to \'pkgng\'')
return __virtualname__
return (False, 'The freebsdpkg execution module cannot be loaded: either the os is not FreeBSD or the version of FreeBSD is >= 10.')
def _get_repo_options(fromrepo=None, packagesite=None):
'''
Return a list of tuples to seed the "env" list, which is used to set
environment variables for any pkg_add commands that are spawned.
If ``fromrepo`` or ``packagesite`` are None, then their corresponding
config parameter will be looked up with config.get.
If both ``fromrepo`` and ``packagesite`` are None, and neither
freebsdpkg.PACKAGEROOT nor freebsdpkg.PACKAGESITE are specified, then an
empty list is returned, and it is assumed that the system defaults (or
environment variables) will be used.
'''
root = fromrepo if fromrepo is not None \
else __salt__['config.get']('freebsdpkg.PACKAGEROOT', None)
site = packagesite if packagesite is not None \
else __salt__['config.get']('freebsdpkg.PACKAGESITE', None)
ret = {}
if root is not None:
ret['PACKAGEROOT'] = root
if site is not None:
ret['PACKAGESITE'] = site
return ret
def _match(names):
'''
Since pkg_delete requires the full "pkgname-version" string, this function
will attempt to match the package name with its version. Returns a list of
partial matches and package names that match the "pkgname-version" string
required by pkg_delete, and a list of errors encountered.
'''
pkgs = list_pkgs(versions_as_list=True)
errors = []
# Look for full matches
full_pkg_strings = []
out = __salt__['cmd.run_stdout'](['pkg_info'],
output_loglevel='trace',
python_shell=False)
for line in out.splitlines():
try:
full_pkg_strings.append(line.split()[0])
except IndexError:
continue
full_matches = [x for x in names if x in full_pkg_strings]
# Look for pkgname-only matches
matches = []
ambiguous = []
for name in set(names) - set(full_matches):
cver = pkgs.get(name)
if cver is not None:
if len(cver) == 1:
matches.append('{0}-{1}'.format(name, cver[0]))
else:
ambiguous.append(name)
errors.append(
'Ambiguous package \'{0}\'. Full name/version required. '
'Possible matches: {1}'.format(
name,
', '.join(['{0}-{1}'.format(name, x) for x in cver])
)
)
# Find packages that did not match anything
not_matched = \
set(names) - set(matches) - set(full_matches) - set(ambiguous)
for name in not_matched:
errors.append('Package \'{0}\' not found'.format(name))
return matches + full_matches, errors
def latest_version(*names, **kwargs):
'''
``pkg_add(1)`` is not capable of querying for remote packages, so this
function will always return results as if there is no package available for
install or upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
return '' if len(names) == 1 else dict((x, '') for x in names)
# 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.
with_origin : False
Return a nested dictionary containing both the origin name and version
for each specified package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
with_origin = kwargs.pop('with_origin', False)
ret = __salt__['pkg_resource.version'](*names, **kwargs)
if not salt.utils.data.is_true(with_origin):
return ret
# Put the return value back into a dict since we're adding a subdict
if len(names) == 1:
ret = {names[0]: ret}
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
def refresh_db(**kwargs):
'''
``pkg_add(1)`` does not use a local database of available packages, so this
function simply returns ``True``. it exists merely for API compatibility.
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__)
return True
def list_pkgs(versions_as_list=False, with_origin=False, **kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
with_origin : False
Return a nested dictionary containing both the origin name and version
for each installed package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
ret = {}
origins = {}
out = __salt__['cmd.run_stdout'](['pkg_info', '-ao'],
output_loglevel='trace',
python_shell=False)
pkgs_re = re.compile(r'Information for ([^:]+):\s*Origin:\n([^\n]+)')
for pkg, origin in pkgs_re.findall(out):
if not pkg:
continue
try:
pkgname, pkgver = pkg.rsplit('-', 1)
except ValueError:
continue
__salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver)
origins[pkgname] = origin
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
__context__['pkg.origin'] = origins
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
**kwargs):
'''
Install package(s) using ``pkg_add(1)``
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo or packageroot
Specify a package repository from which to install. Overrides the
system default, as well as the PACKAGEROOT environment variable.
packagesite
Specify the exact directory from which to install the remote package.
Overrides the PACKAGESITE environment variable, if present.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
sources
A list of 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.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"}, {"bar": "salt://bar.deb"}]'
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
'''
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
packageroot = kwargs.get('packageroot')
if not fromrepo and packageroot:
fromrepo = packageroot
env = _get_repo_options(fromrepo, kwargs.get('packagesite'))
args = []
if pkg_type == 'repository':
args.append('-r') # use remote repo
args.extend(pkg_params)
old = list_pkgs()
out = __salt__['cmd.run_all'](
['pkg_add'] + args,
env=env,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
_rehash()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
# Support pkg.delete to remove packages to more closely match pkg_delete
delete = salt.utils.functools.alias_function(remove, 'delete')
# No equivalent to purge packages, use remove instead
purge = salt.utils.functools.alias_function(remove, 'purge')
def _rehash():
'''
Recomputes internal hash table for the PATH variable. Use whenever a new
command is created during the current session.
'''
shell = __salt__['environ.get']('SHELL')
if shell.split('/')[-1] in ('csh', 'tcsh'):
__salt__['cmd.shell']('rehash', output_loglevel='trace')
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
'''
ret = file_dict(*packages)
files = []
for pkg_files in six.itervalues(ret['files']):
files.extend(pkg_files)
ret['files'] = files
return ret
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the
system's package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
files = {}
if packages:
match_pattern = '\'{0}-[0-9]*\''
cmd = ['pkg_info', '-QL'] + [match_pattern.format(p) for p in packages]
else:
cmd = ['pkg_info', '-QLa']
ret = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in ret['stderr'].splitlines():
errors.append(line)
pkg = None
for line in ret['stdout'].splitlines():
if pkg is not None and line.startswith('/'):
files[pkg].append(line)
elif ':/' in line:
pkg, fn = line.split(':', 1)
pkg, ver = pkg.rsplit('-', 1)
files[pkg] = [fn]
else:
continue # unexpected string
return {'errors': errors, 'files': files}
|
saltstack/salt
|
salt/modules/freebsdpkg.py
|
file_dict
|
python
|
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the
system's package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
files = {}
if packages:
match_pattern = '\'{0}-[0-9]*\''
cmd = ['pkg_info', '-QL'] + [match_pattern.format(p) for p in packages]
else:
cmd = ['pkg_info', '-QLa']
ret = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in ret['stderr'].splitlines():
errors.append(line)
pkg = None
for line in ret['stdout'].splitlines():
if pkg is not None and line.startswith('/'):
files[pkg].append(line)
elif ':/' in line:
pkg, fn = line.split(':', 1)
pkg, ver = pkg.rsplit('-', 1)
files[pkg] = [fn]
else:
continue # unexpected string
return {'errors': errors, 'files': files}
|
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the
system's package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdpkg.py#L528-L569
| null |
# -*- coding: utf-8 -*-
'''
Remote package support using ``pkg_add(1)``
.. 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>`.
.. warning::
This module has been completely rewritten. Up to and including version
0.17.0, it supported ``pkg_add(1)``, but checked for the existence of a
pkgng local database and, if found, would provide some of pkgng's
functionality. The rewrite of this module has removed all pkgng support,
and moved it to the :mod:`pkgng <salt.modules.pkgng>` execution module. For
versions <= 0.17.0, the documentation here should not be considered
accurate. If your Minion is running one of these versions, then the
documentation for this module can be viewed using the :mod:`sys.doc
<salt.modules.sys.doc>` function:
.. code-block:: bash
salt bsdminion sys.doc pkg
This module acts as the default package provider for FreeBSD 9 and older. If
you need to use pkgng on a FreeBSD 9 system, you will need to override the
``pkg`` provider by setting the :conf_minion:`providers` parameter in your
Minion config file, in order to use pkgng.
.. code-block:: yaml
providers:
pkg: pkgng
More information on pkgng support can be found in the documentation for the
:mod:`pkgng <salt.modules.pkgng>` module.
This module will respect the ``PACKAGEROOT`` and ``PACKAGESITE`` environment
variables, if set, but these values can also be overridden in several ways:
1. :strong:`Salt configuration parameters.` The configuration parameters
``freebsdpkg.PACKAGEROOT`` and ``freebsdpkg.PACKAGESITE`` are recognized.
These config parameters are looked up using :mod:`config.get
<salt.modules.config.get>` and can thus be specified in the Master config
file, Grains, Pillar, or in the Minion config file. Example:
.. code-block:: yaml
freebsdpkg.PACKAGEROOT: ftp://ftp.freebsd.org/
freebsdpkg.PACKAGESITE: ftp://ftp.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
2. :strong:`CLI arguments.` Both the ``packageroot`` (used interchangeably with
``fromrepo`` for API compatibility) and ``packagesite`` CLI arguments are
recognized, and override their config counterparts from section 1 above.
.. code-block:: bash
salt -G 'os:FreeBSD' pkg.install zsh fromrepo=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packageroot=ftp://ftp2.freebsd.org/
salt -G 'os:FreeBSD' pkg.install zsh packagesite=ftp://ftp2.freebsd.org/pub/FreeBSD/ports/ia64/packages-9-stable/Latest/
.. note::
These arguments can also be passed through in states:
.. code-block:: yaml
zsh:
pkg.installed:
- fromrepo: ftp://ftp2.freebsd.org/
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import logging
import re
# Import salt libs
import salt.utils.data
import salt.utils.functools
import salt.utils.pkg
from salt.exceptions import CommandExecutionError, MinionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Load as 'pkg' on FreeBSD versions less than 10.
Don't load on FreeBSD 9 when the config option
``providers:pkg`` is set to 'pkgng'.
'''
if __grains__['os'] == 'FreeBSD' and float(__grains__['osrelease']) < 10:
providers = {}
if 'providers' in __opts__:
providers = __opts__['providers']
if providers and 'pkg' in providers and providers['pkg'] == 'pkgng':
log.debug('Configuration option \'providers:pkg\' is set to '
'\'pkgng\', won\'t load old provider \'freebsdpkg\'.')
return (False, 'The freebsdpkg execution module cannot be loaded: the configuration option \'providers:pkg\' is set to \'pkgng\'')
return __virtualname__
return (False, 'The freebsdpkg execution module cannot be loaded: either the os is not FreeBSD or the version of FreeBSD is >= 10.')
def _get_repo_options(fromrepo=None, packagesite=None):
'''
Return a list of tuples to seed the "env" list, which is used to set
environment variables for any pkg_add commands that are spawned.
If ``fromrepo`` or ``packagesite`` are None, then their corresponding
config parameter will be looked up with config.get.
If both ``fromrepo`` and ``packagesite`` are None, and neither
freebsdpkg.PACKAGEROOT nor freebsdpkg.PACKAGESITE are specified, then an
empty list is returned, and it is assumed that the system defaults (or
environment variables) will be used.
'''
root = fromrepo if fromrepo is not None \
else __salt__['config.get']('freebsdpkg.PACKAGEROOT', None)
site = packagesite if packagesite is not None \
else __salt__['config.get']('freebsdpkg.PACKAGESITE', None)
ret = {}
if root is not None:
ret['PACKAGEROOT'] = root
if site is not None:
ret['PACKAGESITE'] = site
return ret
def _match(names):
'''
Since pkg_delete requires the full "pkgname-version" string, this function
will attempt to match the package name with its version. Returns a list of
partial matches and package names that match the "pkgname-version" string
required by pkg_delete, and a list of errors encountered.
'''
pkgs = list_pkgs(versions_as_list=True)
errors = []
# Look for full matches
full_pkg_strings = []
out = __salt__['cmd.run_stdout'](['pkg_info'],
output_loglevel='trace',
python_shell=False)
for line in out.splitlines():
try:
full_pkg_strings.append(line.split()[0])
except IndexError:
continue
full_matches = [x for x in names if x in full_pkg_strings]
# Look for pkgname-only matches
matches = []
ambiguous = []
for name in set(names) - set(full_matches):
cver = pkgs.get(name)
if cver is not None:
if len(cver) == 1:
matches.append('{0}-{1}'.format(name, cver[0]))
else:
ambiguous.append(name)
errors.append(
'Ambiguous package \'{0}\'. Full name/version required. '
'Possible matches: {1}'.format(
name,
', '.join(['{0}-{1}'.format(name, x) for x in cver])
)
)
# Find packages that did not match anything
not_matched = \
set(names) - set(matches) - set(full_matches) - set(ambiguous)
for name in not_matched:
errors.append('Package \'{0}\' not found'.format(name))
return matches + full_matches, errors
def latest_version(*names, **kwargs):
'''
``pkg_add(1)`` is not capable of querying for remote packages, so this
function will always return results as if there is no package available for
install or upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
return '' if len(names) == 1 else dict((x, '') for x in names)
# 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.
with_origin : False
Return a nested dictionary containing both the origin name and version
for each specified package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
with_origin = kwargs.pop('with_origin', False)
ret = __salt__['pkg_resource.version'](*names, **kwargs)
if not salt.utils.data.is_true(with_origin):
return ret
# Put the return value back into a dict since we're adding a subdict
if len(names) == 1:
ret = {names[0]: ret}
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
def refresh_db(**kwargs):
'''
``pkg_add(1)`` does not use a local database of available packages, so this
function simply returns ``True``. it exists merely for API compatibility.
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__)
return True
def list_pkgs(versions_as_list=False, with_origin=False, **kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
with_origin : False
Return a nested dictionary containing both the origin name and version
for each installed package.
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
origins = __context__.get('pkg.origin', {})
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
ret = {}
origins = {}
out = __salt__['cmd.run_stdout'](['pkg_info', '-ao'],
output_loglevel='trace',
python_shell=False)
pkgs_re = re.compile(r'Information for ([^:]+):\s*Origin:\n([^\n]+)')
for pkg, origin in pkgs_re.findall(out):
if not pkg:
continue
try:
pkgname, pkgver = pkg.rsplit('-', 1)
except ValueError:
continue
__salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver)
origins[pkgname] = origin
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
__context__['pkg.origin'] = origins
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
if salt.utils.data.is_true(with_origin):
return dict([
(x, {'origin': origins.get(x, ''), 'version': y})
for x, y in six.iteritems(ret)
])
return ret
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
**kwargs):
'''
Install package(s) using ``pkg_add(1)``
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo or packageroot
Specify a package repository from which to install. Overrides the
system default, as well as the PACKAGEROOT environment variable.
packagesite
Specify the exact directory from which to install the remote package.
Overrides the PACKAGESITE environment variable, if present.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
sources
A list of 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.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"}, {"bar": "salt://bar.deb"}]'
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
'''
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
packageroot = kwargs.get('packageroot')
if not fromrepo and packageroot:
fromrepo = packageroot
env = _get_repo_options(fromrepo, kwargs.get('packagesite'))
args = []
if pkg_type == 'repository':
args.append('-r') # use remote repo
args.extend(pkg_params)
old = list_pkgs()
out = __salt__['cmd.run_all'](
['pkg_add'] + args,
env=env,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
_rehash()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def remove(name=None, pkgs=None, **kwargs):
'''
Remove packages using ``pkg_delete(1)``
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"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets, errors = _match([x for x in pkg_params])
for error in errors:
log.error(error)
if not targets:
return {}
out = __salt__['cmd.run_all'](
['pkg_delete'] + targets,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
# Support pkg.delete to remove packages to more closely match pkg_delete
delete = salt.utils.functools.alias_function(remove, 'delete')
# No equivalent to purge packages, use remove instead
purge = salt.utils.functools.alias_function(remove, 'purge')
def _rehash():
'''
Recomputes internal hash table for the PATH variable. Use whenever a new
command is created during the current session.
'''
shell = __salt__['environ.get']('SHELL')
if shell.split('/')[-1] in ('csh', 'tcsh'):
__salt__['cmd.shell']('rehash', output_loglevel='trace')
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
'''
ret = file_dict(*packages)
files = []
for pkg_files in six.itervalues(ret['files']):
files.extend(pkg_files)
ret['files'] = files
return ret
|
saltstack/salt
|
salt/utils/functools.py
|
namespaced_function
|
python
|
def namespaced_function(function, global_dict, defaults=None, preserve_context=False):
'''
Redefine (clone) a function under a different globals() namespace scope
preserve_context:
Allow keeping the context taken from orignal namespace,
and extend it with globals() taken from
new targetted namespace.
'''
if defaults is None:
defaults = function.__defaults__
if preserve_context:
_global_dict = function.__globals__.copy()
_global_dict.update(global_dict)
global_dict = _global_dict
new_namespaced_function = types.FunctionType(
function.__code__,
global_dict,
name=function.__name__,
argdefs=defaults,
closure=function.__closure__
)
new_namespaced_function.__dict__.update(function.__dict__)
return new_namespaced_function
|
Redefine (clone) a function under a different globals() namespace scope
preserve_context:
Allow keeping the context taken from orignal namespace,
and extend it with globals() taken from
new targetted namespace.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/functools.py#L15-L39
| null |
# -*- coding: utf-8 -*-
'''
Utility functions to modify other functions
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import Python libs
import types
# Import 3rd-party libs
from salt.ext import six
def alias_function(fun, name, doc=None):
'''
Copy a function
'''
alias_fun = types.FunctionType(fun.__code__,
fun.__globals__,
str(name), # future lint: disable=blacklisted-function
fun.__defaults__,
fun.__closure__)
alias_fun.__dict__.update(fun.__dict__)
if doc and isinstance(doc, six.string_types):
alias_fun.__doc__ = doc
else:
orig_name = fun.__name__
alias_msg = ('\nThis function is an alias of '
'``{0}``.\n'.format(orig_name))
alias_fun.__doc__ = alias_msg + (fun.__doc__ or '')
return alias_fun
|
saltstack/salt
|
salt/utils/functools.py
|
alias_function
|
python
|
def alias_function(fun, name, doc=None):
'''
Copy a function
'''
alias_fun = types.FunctionType(fun.__code__,
fun.__globals__,
str(name), # future lint: disable=blacklisted-function
fun.__defaults__,
fun.__closure__)
alias_fun.__dict__.update(fun.__dict__)
if doc and isinstance(doc, six.string_types):
alias_fun.__doc__ = doc
else:
orig_name = fun.__name__
alias_msg = ('\nThis function is an alias of '
'``{0}``.\n'.format(orig_name))
alias_fun.__doc__ = alias_msg + (fun.__doc__ or '')
return alias_fun
|
Copy a function
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/functools.py#L42-L61
| null |
# -*- coding: utf-8 -*-
'''
Utility functions to modify other functions
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import Python libs
import types
# Import 3rd-party libs
from salt.ext import six
def namespaced_function(function, global_dict, defaults=None, preserve_context=False):
'''
Redefine (clone) a function under a different globals() namespace scope
preserve_context:
Allow keeping the context taken from orignal namespace,
and extend it with globals() taken from
new targetted namespace.
'''
if defaults is None:
defaults = function.__defaults__
if preserve_context:
_global_dict = function.__globals__.copy()
_global_dict.update(global_dict)
global_dict = _global_dict
new_namespaced_function = types.FunctionType(
function.__code__,
global_dict,
name=function.__name__,
argdefs=defaults,
closure=function.__closure__
)
new_namespaced_function.__dict__.update(function.__dict__)
return new_namespaced_function
|
saltstack/salt
|
salt/states/win_dns_client.py
|
dns_exists
|
python
|
def dns_exists(name, servers=None, interface='Local Area Connection', replace=False):
'''
Configure the DNS server list in the specified interface
Example:
.. code-block:: yaml
config_dns_servers:
win_dns_client.dns_exists:
- replace: True #remove any servers not in the "servers" list, default is False
- servers:
- 8.8.8.8
- 8.8.8.9
'''
ret = {'name': name,
'result': True,
'changes': {'Servers Reordered': [], 'Servers Added': [], 'Servers Removed': []},
'comment': ''}
if __opts__['test']:
ret['comment'] = 'DNS Servers are set to be updated'
ret['result'] = None
else:
ret['comment'] = 'DNS Servers have been updated'
# Validate syntax
if not isinstance(servers, list):
ret['result'] = False
ret['comment'] = 'servers entry is not a list !'
return ret
# Do nothing is already configured
configured_list = __salt__['win_dns_client.get_dns_servers'](interface)
if configured_list == servers:
ret['comment'] = '{0} are already configured'.format(servers)
ret['changes'] = {}
ret['result'] = True
return ret
# add the DNS servers
for i, server in enumerate(servers):
if __opts__['test']:
if server in configured_list:
if configured_list.index(server) != i:
ret['changes']['Servers Reordered'].append(server)
else:
ret['changes']['Servers Added'].append(server)
else:
if not __salt__['win_dns_client.add_dns'](server, interface, i + 1):
ret['comment'] = (
'Failed to add {0} as DNS server number {1}'
).format(server, i + 1)
ret['result'] = False
ret['changes'] = {}
return ret
else:
if server in configured_list:
if configured_list.index(server) != i:
ret['changes']['Servers Reordered'].append(server)
else:
ret['changes']['Servers Added'].append(server)
# remove dns servers that weren't in our list
if replace:
for i, server in enumerate(configured_list):
if server not in servers:
if __opts__['test']:
ret['changes']['Servers Removed'].append(server)
else:
if not __salt__['win_dns_client.rm_dns'](server, interface):
ret['comment'] = (
'Failed to remove {0} from DNS server list').format(server)
ret['result'] = False
return ret
else:
ret['changes']['Servers Removed'].append(server)
return ret
|
Configure the DNS server list in the specified interface
Example:
.. code-block:: yaml
config_dns_servers:
win_dns_client.dns_exists:
- replace: True #remove any servers not in the "servers" list, default is False
- servers:
- 8.8.8.8
- 8.8.8.9
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_dns_client.py#L15-L93
| null |
# -*- coding: utf-8 -*-
'''
Module for configuring DNS Client on Windows systems
'''
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Load if the module win_dns_client is loaded
'''
return 'win_dns_client' if 'win_dns_client.add_dns' in __salt__ else False
def dns_dhcp(name, interface='Local Area Connection'):
'''
Configure the DNS server list from DHCP Server
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
# Check the config
config = __salt__['win_dns_client.get_dns_config'](interface)
if config == 'dhcp':
ret['comment'] = '{0} already configured with DNS from DHCP'.format(
interface)
return ret
else:
ret['changes'] = {'dns': 'configured from DHCP'}
if __opts__['test']:
ret['result'] = None
return ret
# change the configuration
ret['result'] = __salt__['win_dns_client.dns_dhcp'](interface)
if not ret['result']:
ret['changes'] = {}
ret['comment'] = (
'Could not configure "{0}" DNS servers from DHCP'
).format(interface)
return ret
def primary_suffix(name,
suffix=None,
updates=False):
'''
.. versionadded:: 2014.7.0
Configure the global primary DNS suffix of a DHCP client.
suffix : None
The suffix which is advertised for this client when acquiring a DHCP lease
When none is set, the explicitly configured DNS suffix will be removed.
updates : False
Allow syncing the DNS suffix with the AD domain when the client's AD domain membership changes
.. code-block:: yaml
primary_dns_suffix:
win_dns_client.primary_suffix:
- suffix: sub.domain.tld
- updates: True
'''
ret = {
'name': name,
'changes': {},
'result': True,
'comment': 'No changes needed'
}
suffix = str(suffix)
if not isinstance(updates, bool):
ret['result'] = False
ret['comment'] = '\'updates\' must be a boolean value'
return ret
# TODO: waiting for an implementation of
# https://github.com/saltstack/salt/issues/6792 to be able to handle the
# requirement for a reboot to actually apply this state.
# Until then, this method will only be able to verify that the required
# value has been written to the registry and rebooting needs to be handled
# manually
reg_data = {
'suffix': {
'hive': 'HKEY_LOCAL_MACHINE',
'key': r'SYSTEM\CurrentControlSet\services\Tcpip\Parameters',
'vname': 'NV Domain',
'vtype': 'REG_SZ',
'old': None,
'new': suffix
},
'updates': {
'hive': 'HKEY_LOCAL_MACHINE',
'key': r'SYSTEM\CurrentControlSet\services\Tcpip\Parameters',
'vname': 'SyncDomainWithMembership',
'vtype': 'REG_DWORD',
'old': None,
'new': updates
}
}
reg_data['suffix']['old'] = __utils__['reg.read_value'](
reg_data['suffix']['hive'],
reg_data['suffix']['key'],
reg_data['suffix']['vname'],)['vdata']
reg_data['updates']['old'] = bool(__utils__['reg.read_value'](
reg_data['updates']['hive'],
reg_data['updates']['key'],
reg_data['updates']['vname'],)['vdata'])
updates_operation = 'enabled' if reg_data['updates']['new'] else 'disabled'
# No changes to suffix needed
if reg_data['suffix']['new'] == reg_data['suffix']['old']:
# No changes to updates policy needed
if reg_data['updates']['new'] == reg_data['updates']['old']:
return ret
# Changes to update policy needed
else:
ret['comment'] = '{0} suffix updates'.format(updates_operation)
ret['changes'] = {
'old': {
'updates': reg_data['updates']['old']},
'new': {
'updates': reg_data['updates']['new']}}
# Changes to suffix needed
else:
# Changes to updates policy needed
if reg_data['updates']['new'] != reg_data['updates']['old']:
ret['comment'] = 'Updated primary DNS suffix ({0}) and {1} suffix updates'.format(suffix, updates_operation)
ret['changes'] = {
'old': {
'suffix': reg_data['suffix']['old'],
'updates': reg_data['updates']['old']},
'new': {
'suffix': reg_data['suffix']['new'],
'updates': reg_data['updates']['new']}}
# No changes to updates policy needed
else:
ret['comment'] = 'Updated primary DNS suffix ({0})'.format(suffix)
ret['changes'] = {
'old': {
'suffix': reg_data['suffix']['old']},
'new': {
'suffix': reg_data['suffix']['new']}}
suffix_result = __utils__['reg.set_value'](
reg_data['suffix']['hive'],
reg_data['suffix']['key'],
reg_data['suffix']['vname'],
reg_data['suffix']['new'],
reg_data['suffix']['vtype'])
updates_result = __utils__['reg.set_value'](
reg_data['updates']['hive'],
reg_data['updates']['key'],
reg_data['updates']['vname'],
reg_data['updates']['new'],
reg_data['updates']['vtype'])
ret['result'] = suffix_result & updates_result
return ret
|
saltstack/salt
|
salt/states/win_dns_client.py
|
dns_dhcp
|
python
|
def dns_dhcp(name, interface='Local Area Connection'):
'''
Configure the DNS server list from DHCP Server
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
# Check the config
config = __salt__['win_dns_client.get_dns_config'](interface)
if config == 'dhcp':
ret['comment'] = '{0} already configured with DNS from DHCP'.format(
interface)
return ret
else:
ret['changes'] = {'dns': 'configured from DHCP'}
if __opts__['test']:
ret['result'] = None
return ret
# change the configuration
ret['result'] = __salt__['win_dns_client.dns_dhcp'](interface)
if not ret['result']:
ret['changes'] = {}
ret['comment'] = (
'Could not configure "{0}" DNS servers from DHCP'
).format(interface)
return ret
|
Configure the DNS server list from DHCP Server
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_dns_client.py#L96-L126
| null |
# -*- coding: utf-8 -*-
'''
Module for configuring DNS Client on Windows systems
'''
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Load if the module win_dns_client is loaded
'''
return 'win_dns_client' if 'win_dns_client.add_dns' in __salt__ else False
def dns_exists(name, servers=None, interface='Local Area Connection', replace=False):
'''
Configure the DNS server list in the specified interface
Example:
.. code-block:: yaml
config_dns_servers:
win_dns_client.dns_exists:
- replace: True #remove any servers not in the "servers" list, default is False
- servers:
- 8.8.8.8
- 8.8.8.9
'''
ret = {'name': name,
'result': True,
'changes': {'Servers Reordered': [], 'Servers Added': [], 'Servers Removed': []},
'comment': ''}
if __opts__['test']:
ret['comment'] = 'DNS Servers are set to be updated'
ret['result'] = None
else:
ret['comment'] = 'DNS Servers have been updated'
# Validate syntax
if not isinstance(servers, list):
ret['result'] = False
ret['comment'] = 'servers entry is not a list !'
return ret
# Do nothing is already configured
configured_list = __salt__['win_dns_client.get_dns_servers'](interface)
if configured_list == servers:
ret['comment'] = '{0} are already configured'.format(servers)
ret['changes'] = {}
ret['result'] = True
return ret
# add the DNS servers
for i, server in enumerate(servers):
if __opts__['test']:
if server in configured_list:
if configured_list.index(server) != i:
ret['changes']['Servers Reordered'].append(server)
else:
ret['changes']['Servers Added'].append(server)
else:
if not __salt__['win_dns_client.add_dns'](server, interface, i + 1):
ret['comment'] = (
'Failed to add {0} as DNS server number {1}'
).format(server, i + 1)
ret['result'] = False
ret['changes'] = {}
return ret
else:
if server in configured_list:
if configured_list.index(server) != i:
ret['changes']['Servers Reordered'].append(server)
else:
ret['changes']['Servers Added'].append(server)
# remove dns servers that weren't in our list
if replace:
for i, server in enumerate(configured_list):
if server not in servers:
if __opts__['test']:
ret['changes']['Servers Removed'].append(server)
else:
if not __salt__['win_dns_client.rm_dns'](server, interface):
ret['comment'] = (
'Failed to remove {0} from DNS server list').format(server)
ret['result'] = False
return ret
else:
ret['changes']['Servers Removed'].append(server)
return ret
def primary_suffix(name,
suffix=None,
updates=False):
'''
.. versionadded:: 2014.7.0
Configure the global primary DNS suffix of a DHCP client.
suffix : None
The suffix which is advertised for this client when acquiring a DHCP lease
When none is set, the explicitly configured DNS suffix will be removed.
updates : False
Allow syncing the DNS suffix with the AD domain when the client's AD domain membership changes
.. code-block:: yaml
primary_dns_suffix:
win_dns_client.primary_suffix:
- suffix: sub.domain.tld
- updates: True
'''
ret = {
'name': name,
'changes': {},
'result': True,
'comment': 'No changes needed'
}
suffix = str(suffix)
if not isinstance(updates, bool):
ret['result'] = False
ret['comment'] = '\'updates\' must be a boolean value'
return ret
# TODO: waiting for an implementation of
# https://github.com/saltstack/salt/issues/6792 to be able to handle the
# requirement for a reboot to actually apply this state.
# Until then, this method will only be able to verify that the required
# value has been written to the registry and rebooting needs to be handled
# manually
reg_data = {
'suffix': {
'hive': 'HKEY_LOCAL_MACHINE',
'key': r'SYSTEM\CurrentControlSet\services\Tcpip\Parameters',
'vname': 'NV Domain',
'vtype': 'REG_SZ',
'old': None,
'new': suffix
},
'updates': {
'hive': 'HKEY_LOCAL_MACHINE',
'key': r'SYSTEM\CurrentControlSet\services\Tcpip\Parameters',
'vname': 'SyncDomainWithMembership',
'vtype': 'REG_DWORD',
'old': None,
'new': updates
}
}
reg_data['suffix']['old'] = __utils__['reg.read_value'](
reg_data['suffix']['hive'],
reg_data['suffix']['key'],
reg_data['suffix']['vname'],)['vdata']
reg_data['updates']['old'] = bool(__utils__['reg.read_value'](
reg_data['updates']['hive'],
reg_data['updates']['key'],
reg_data['updates']['vname'],)['vdata'])
updates_operation = 'enabled' if reg_data['updates']['new'] else 'disabled'
# No changes to suffix needed
if reg_data['suffix']['new'] == reg_data['suffix']['old']:
# No changes to updates policy needed
if reg_data['updates']['new'] == reg_data['updates']['old']:
return ret
# Changes to update policy needed
else:
ret['comment'] = '{0} suffix updates'.format(updates_operation)
ret['changes'] = {
'old': {
'updates': reg_data['updates']['old']},
'new': {
'updates': reg_data['updates']['new']}}
# Changes to suffix needed
else:
# Changes to updates policy needed
if reg_data['updates']['new'] != reg_data['updates']['old']:
ret['comment'] = 'Updated primary DNS suffix ({0}) and {1} suffix updates'.format(suffix, updates_operation)
ret['changes'] = {
'old': {
'suffix': reg_data['suffix']['old'],
'updates': reg_data['updates']['old']},
'new': {
'suffix': reg_data['suffix']['new'],
'updates': reg_data['updates']['new']}}
# No changes to updates policy needed
else:
ret['comment'] = 'Updated primary DNS suffix ({0})'.format(suffix)
ret['changes'] = {
'old': {
'suffix': reg_data['suffix']['old']},
'new': {
'suffix': reg_data['suffix']['new']}}
suffix_result = __utils__['reg.set_value'](
reg_data['suffix']['hive'],
reg_data['suffix']['key'],
reg_data['suffix']['vname'],
reg_data['suffix']['new'],
reg_data['suffix']['vtype'])
updates_result = __utils__['reg.set_value'](
reg_data['updates']['hive'],
reg_data['updates']['key'],
reg_data['updates']['vname'],
reg_data['updates']['new'],
reg_data['updates']['vtype'])
ret['result'] = suffix_result & updates_result
return ret
|
saltstack/salt
|
salt/states/win_dns_client.py
|
primary_suffix
|
python
|
def primary_suffix(name,
suffix=None,
updates=False):
'''
.. versionadded:: 2014.7.0
Configure the global primary DNS suffix of a DHCP client.
suffix : None
The suffix which is advertised for this client when acquiring a DHCP lease
When none is set, the explicitly configured DNS suffix will be removed.
updates : False
Allow syncing the DNS suffix with the AD domain when the client's AD domain membership changes
.. code-block:: yaml
primary_dns_suffix:
win_dns_client.primary_suffix:
- suffix: sub.domain.tld
- updates: True
'''
ret = {
'name': name,
'changes': {},
'result': True,
'comment': 'No changes needed'
}
suffix = str(suffix)
if not isinstance(updates, bool):
ret['result'] = False
ret['comment'] = '\'updates\' must be a boolean value'
return ret
# TODO: waiting for an implementation of
# https://github.com/saltstack/salt/issues/6792 to be able to handle the
# requirement for a reboot to actually apply this state.
# Until then, this method will only be able to verify that the required
# value has been written to the registry and rebooting needs to be handled
# manually
reg_data = {
'suffix': {
'hive': 'HKEY_LOCAL_MACHINE',
'key': r'SYSTEM\CurrentControlSet\services\Tcpip\Parameters',
'vname': 'NV Domain',
'vtype': 'REG_SZ',
'old': None,
'new': suffix
},
'updates': {
'hive': 'HKEY_LOCAL_MACHINE',
'key': r'SYSTEM\CurrentControlSet\services\Tcpip\Parameters',
'vname': 'SyncDomainWithMembership',
'vtype': 'REG_DWORD',
'old': None,
'new': updates
}
}
reg_data['suffix']['old'] = __utils__['reg.read_value'](
reg_data['suffix']['hive'],
reg_data['suffix']['key'],
reg_data['suffix']['vname'],)['vdata']
reg_data['updates']['old'] = bool(__utils__['reg.read_value'](
reg_data['updates']['hive'],
reg_data['updates']['key'],
reg_data['updates']['vname'],)['vdata'])
updates_operation = 'enabled' if reg_data['updates']['new'] else 'disabled'
# No changes to suffix needed
if reg_data['suffix']['new'] == reg_data['suffix']['old']:
# No changes to updates policy needed
if reg_data['updates']['new'] == reg_data['updates']['old']:
return ret
# Changes to update policy needed
else:
ret['comment'] = '{0} suffix updates'.format(updates_operation)
ret['changes'] = {
'old': {
'updates': reg_data['updates']['old']},
'new': {
'updates': reg_data['updates']['new']}}
# Changes to suffix needed
else:
# Changes to updates policy needed
if reg_data['updates']['new'] != reg_data['updates']['old']:
ret['comment'] = 'Updated primary DNS suffix ({0}) and {1} suffix updates'.format(suffix, updates_operation)
ret['changes'] = {
'old': {
'suffix': reg_data['suffix']['old'],
'updates': reg_data['updates']['old']},
'new': {
'suffix': reg_data['suffix']['new'],
'updates': reg_data['updates']['new']}}
# No changes to updates policy needed
else:
ret['comment'] = 'Updated primary DNS suffix ({0})'.format(suffix)
ret['changes'] = {
'old': {
'suffix': reg_data['suffix']['old']},
'new': {
'suffix': reg_data['suffix']['new']}}
suffix_result = __utils__['reg.set_value'](
reg_data['suffix']['hive'],
reg_data['suffix']['key'],
reg_data['suffix']['vname'],
reg_data['suffix']['new'],
reg_data['suffix']['vtype'])
updates_result = __utils__['reg.set_value'](
reg_data['updates']['hive'],
reg_data['updates']['key'],
reg_data['updates']['vname'],
reg_data['updates']['new'],
reg_data['updates']['vtype'])
ret['result'] = suffix_result & updates_result
return ret
|
.. versionadded:: 2014.7.0
Configure the global primary DNS suffix of a DHCP client.
suffix : None
The suffix which is advertised for this client when acquiring a DHCP lease
When none is set, the explicitly configured DNS suffix will be removed.
updates : False
Allow syncing the DNS suffix with the AD domain when the client's AD domain membership changes
.. code-block:: yaml
primary_dns_suffix:
win_dns_client.primary_suffix:
- suffix: sub.domain.tld
- updates: True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_dns_client.py#L129-L254
| null |
# -*- coding: utf-8 -*-
'''
Module for configuring DNS Client on Windows systems
'''
from __future__ import absolute_import, unicode_literals, print_function
def __virtual__():
'''
Load if the module win_dns_client is loaded
'''
return 'win_dns_client' if 'win_dns_client.add_dns' in __salt__ else False
def dns_exists(name, servers=None, interface='Local Area Connection', replace=False):
'''
Configure the DNS server list in the specified interface
Example:
.. code-block:: yaml
config_dns_servers:
win_dns_client.dns_exists:
- replace: True #remove any servers not in the "servers" list, default is False
- servers:
- 8.8.8.8
- 8.8.8.9
'''
ret = {'name': name,
'result': True,
'changes': {'Servers Reordered': [], 'Servers Added': [], 'Servers Removed': []},
'comment': ''}
if __opts__['test']:
ret['comment'] = 'DNS Servers are set to be updated'
ret['result'] = None
else:
ret['comment'] = 'DNS Servers have been updated'
# Validate syntax
if not isinstance(servers, list):
ret['result'] = False
ret['comment'] = 'servers entry is not a list !'
return ret
# Do nothing is already configured
configured_list = __salt__['win_dns_client.get_dns_servers'](interface)
if configured_list == servers:
ret['comment'] = '{0} are already configured'.format(servers)
ret['changes'] = {}
ret['result'] = True
return ret
# add the DNS servers
for i, server in enumerate(servers):
if __opts__['test']:
if server in configured_list:
if configured_list.index(server) != i:
ret['changes']['Servers Reordered'].append(server)
else:
ret['changes']['Servers Added'].append(server)
else:
if not __salt__['win_dns_client.add_dns'](server, interface, i + 1):
ret['comment'] = (
'Failed to add {0} as DNS server number {1}'
).format(server, i + 1)
ret['result'] = False
ret['changes'] = {}
return ret
else:
if server in configured_list:
if configured_list.index(server) != i:
ret['changes']['Servers Reordered'].append(server)
else:
ret['changes']['Servers Added'].append(server)
# remove dns servers that weren't in our list
if replace:
for i, server in enumerate(configured_list):
if server not in servers:
if __opts__['test']:
ret['changes']['Servers Removed'].append(server)
else:
if not __salt__['win_dns_client.rm_dns'](server, interface):
ret['comment'] = (
'Failed to remove {0} from DNS server list').format(server)
ret['result'] = False
return ret
else:
ret['changes']['Servers Removed'].append(server)
return ret
def dns_dhcp(name, interface='Local Area Connection'):
'''
Configure the DNS server list from DHCP Server
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
# Check the config
config = __salt__['win_dns_client.get_dns_config'](interface)
if config == 'dhcp':
ret['comment'] = '{0} already configured with DNS from DHCP'.format(
interface)
return ret
else:
ret['changes'] = {'dns': 'configured from DHCP'}
if __opts__['test']:
ret['result'] = None
return ret
# change the configuration
ret['result'] = __salt__['win_dns_client.dns_dhcp'](interface)
if not ret['result']:
ret['changes'] = {}
ret['comment'] = (
'Could not configure "{0}" DNS servers from DHCP'
).format(interface)
return ret
|
saltstack/salt
|
salt/states/iptables.py
|
insert
|
python
|
def insert(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
position
The numerical representation of where the rule should be inserted into
the chain. Note that ``-1`` is not a supported position value.
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
save = True
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = insert(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full=True, family=family, command='I', **kwargs)
if __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already set for {1} ({2})'.format(
name,
family,
command.strip())
if 'save' in kwargs and kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
saved_rules = __salt__['iptables.get_saved_rules'](family=family)
_rules = __salt__['iptables.get_rules'](family=family)
__rules = []
for table in _rules:
for chain in _rules[table]:
__rules.append(_rules[table][chain].get('rules'))
__saved_rules = []
for table in saved_rules:
for chain in saved_rules[table]:
__saved_rules.append(saved_rules[table][chain].get('rules'))
# Only save if rules in memory are different than saved rules
if __rules != __saved_rules:
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] += ('\nSaved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if not __salt__['iptables.insert'](table, kwargs['chain'], kwargs['position'], rule, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set iptables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
out = __salt__['iptables.save'](filename=None, family=family)
ret['comment'] = ('Set and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set iptables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
|
.. versionadded:: 2014.1.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
position
The numerical representation of where the rule should be inserted into
the chain. Note that ``-1`` is not a supported position value.
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/iptables.py#L489-L614
|
[
"def insert(name, table='filter', family='ipv4', **kwargs):\n '''\n .. versionadded:: 2014.1.0\n\n Insert a rule into a chain\n\n name\n A user-defined name to call this rule by in another part of a state or\n formula. This should not be an actual rule.\n\n table\n The table that owns the chain that should be modified\n\n family\n Networking family, either ipv4 or ipv6\n\n position\n The numerical representation of where the rule should be inserted into\n the chain. Note that ``-1`` is not a supported position value.\n\n All other arguments are passed in with the same name as the long option\n that would normally be used for iptables, with one exception: ``--state`` is\n specified as `connstate` instead of `state` (not to be confused with\n `ctstate`).\n\n Jump options that doesn't take arguments should be passed in with an empty\n string.\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': None,\n 'comment': ''}\n\n if 'rules' in kwargs:\n ret['changes']['locale'] = []\n comments = []\n save = False\n for rule in kwargs['rules']:\n if 'rules' in rule:\n del rule['rules']\n if '__agg__' in rule:\n del rule['__agg__']\n if 'save' in rule and rule['save']:\n save = True\n if rule['save'] is not True:\n save_file = rule['save']\n else:\n save_file = True\n rule['save'] = False\n _ret = insert(**rule)\n if 'locale' in _ret['changes']:\n ret['changes']['locale'].append(_ret['changes']['locale'])\n comments.append(_ret['comment'])\n ret['result'] = _ret['result']\n if save:\n if save_file is True:\n save_file = None\n __salt__['iptables.save'](save_file, family=family)\n if not ret['changes']['locale']:\n del ret['changes']['locale']\n ret['comment'] = '\\n'.join(comments)\n return ret\n\n for ignore in _STATE_INTERNAL_KEYWORDS:\n if ignore in kwargs:\n del kwargs[ignore]\n kwargs['name'] = name\n kwargs['table'] = table\n rule = __salt__['iptables.build_rule'](family=family, **kwargs)\n command = __salt__['iptables.build_rule'](full=True, family=family, command='I', **kwargs)\n if __salt__['iptables.check'](table,\n kwargs['chain'],\n rule,\n family) is True:\n ret['result'] = True\n ret['comment'] = 'iptables rule for {0} already set for {1} ({2})'.format(\n name,\n family,\n command.strip())\n if 'save' in kwargs and kwargs['save']:\n if kwargs['save'] is not True:\n filename = kwargs['save']\n else:\n filename = None\n saved_rules = __salt__['iptables.get_saved_rules'](family=family)\n _rules = __salt__['iptables.get_rules'](family=family)\n __rules = []\n for table in _rules:\n for chain in _rules[table]:\n __rules.append(_rules[table][chain].get('rules'))\n __saved_rules = []\n for table in saved_rules:\n for chain in saved_rules[table]:\n __saved_rules.append(saved_rules[table][chain].get('rules'))\n # Only save if rules in memory are different than saved rules\n if __rules != __saved_rules:\n out = __salt__['iptables.save'](filename, family=family)\n ret['comment'] += ('\\nSaved iptables rule {0} for {1}\\n'\n '{2}\\n{3}').format(name, family, command.strip(), out)\n return ret\n if __opts__['test']:\n ret['comment'] = 'iptables rule for {0} needs to be set for {1} ({2})'.format(\n name,\n family,\n command.strip())\n return ret\n if not __salt__['iptables.insert'](table, kwargs['chain'], kwargs['position'], rule, family):\n ret['changes'] = {'locale': name}\n ret['result'] = True\n ret['comment'] = 'Set iptables rule for {0} to: {1} for {2}'.format(\n name,\n command.strip(),\n family)\n if 'save' in kwargs:\n if kwargs['save']:\n out = __salt__['iptables.save'](filename=None, family=family)\n ret['comment'] = ('Set and saved iptables rule {0} for {1}\\n'\n '{2}\\n{3}').format(name, family, command.strip(), out)\n return ret\n else:\n ret['result'] = False\n ret['comment'] = ('Failed to set iptables rule for {0}.\\n'\n 'Attempted rule was {1}').format(\n name,\n command.strip())\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Management of iptables
======================
This is an iptables-specific module designed to manage Linux firewalls. It is
expected that this state module, and other system-specific firewall states, may
at some point be deprecated in favor of a more generic ``firewall`` state.
.. code-block:: yaml
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: '127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
.. Invert Rule
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: '! 127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: 'not 127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- family: ipv4
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dports:
- 80
- 443
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.insert:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.insert:
- position: 1
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
default to accept:
iptables.set_policy:
- chain: INPUT
- policy: ACCEPT
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms of
``--protocol``, if ``--proto`` appears in an iptables command after the
appearance of ``-m policy``, it is interpreted as the ``--proto`` option of
the policy extension (see the iptables-extensions(8) man page).
Example rules for IPSec policy:
.. code-block:: yaml
accept_esp_in:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- source: 10.20.0.0/24
- destination: 10.10.0.0/24
- in-interface: eth0
- match: policy
- dir: in
- pol: ipsec
- reqid: 1
- proto: esp
accept_esp_forward_in:
iptables.append:
- use:
- iptables: accept_esp_in
- chain: FORWARD
accept_esp_out:
iptables.append:
- table: filter
- chain: OUTPUT
- jump: ACCEPT
- source: 10.10.0.0/24
- destination: 10.20.0.0/24
- out-interface: eth0
- match: policy
- dir: out
- pol: ipsec
- reqid: 1
- proto: esp
accept_esp_forward_out:
iptables.append:
- use:
- iptables: accept_esp_out
- chain: FORWARD
.. note::
Various functions of the ``iptables`` module use the ``--check`` option. If
the version of ``iptables`` on the target system does not include this
option, an alternate version of this check will be performed using the
output of iptables-save. This may have unintended consequences on legacy
releases of ``iptables``.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
def __virtual__():
'''
Only load if the locale module is available in __salt__
'''
return 'iptables.version' in __salt__
def chain_present(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.1.0
Verify the chain is exist.
name
A user-defined chain name.
table
The table to own the chain.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['iptables.check_chain'](table, name, family)
if chain_check is True:
ret['result'] = True
ret['comment'] = ('iptables {0} chain is already exist in {1} table for {2}'
.format(name, table, family))
return ret
if __opts__['test']:
ret['comment'] = 'iptables {0} chain in {1} table needs to be set for {2}'.format(
name,
table,
family)
return ret
command = __salt__['iptables.new_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('iptables {0} chain in {1} table create success for {2}'
.format(name, table, family))
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format(
name,
table,
command.strip(),
family
)
return ret
def chain_absent(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.1.0
Verify the chain is absent.
table
The table to remove the chain from
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['iptables.check_chain'](table, name, family)
if not chain_check:
ret['result'] = True
ret['comment'] = ('iptables {0} chain is already absent in {1} table for {2}'
.format(name, table, family))
return ret
if __opts__['test']:
ret['comment'] = 'iptables {0} chain in {1} table needs to be removed {2}'.format(
name,
table,
family)
return ret
flush_chain = __salt__['iptables.flush'](table, name, family)
if not flush_chain:
command = __salt__['iptables.delete_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('iptables {0} chain in {1} table delete success for {2}'
.format(name, table, family))
else:
ret['result'] = False
ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}'
.format(name, table, command.strip(), family))
else:
ret['result'] = False
ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format(
name,
table,
flush_chain.strip(),
family
)
return ret
def append(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 0.17.0
Add a rule to the end of the specified chain.
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain which should be modified
family
Network family, ipv4 or ipv6.
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
save = True
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = append(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full='True', family=family, command='A', **kwargs)
if __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already set ({1}) for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs and kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
saved_rules = __salt__['iptables.get_saved_rules'](family=family)
_rules = __salt__['iptables.get_rules'](family=family)
__rules = []
for table in _rules:
for chain in _rules[table]:
__rules.append(_rules[table][chain].get('rules'))
__saved_rules = []
for table in saved_rules:
for chain in saved_rules[table]:
__saved_rules.append(saved_rules[table][chain].get('rules'))
# Only save if rules in memory are different than saved rules
if __rules != __saved_rules:
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] += ('\nSaved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
if __salt__['iptables.append'](table, kwargs['chain'], rule, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set iptables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] = ('Set and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set iptables rule for {0}.\n'
'Attempted rule was {1} for {2}').format(
name,
command.strip(), family)
return ret
def delete(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = delete(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full=True, family=family, command='D', **kwargs)
if not __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
if 'position' not in kwargs:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already absent for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be deleted for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'position' in kwargs:
result = __salt__['iptables.delete'](
table,
kwargs['chain'],
family=family,
position=kwargs['position'])
else:
result = __salt__['iptables.delete'](
table,
kwargs['chain'],
family=family,
rule=rule)
if not result:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Delete iptables rule for {0} {1}'.format(
name,
command.strip())
if 'save' in kwargs:
if kwargs['save']:
out = __salt__['iptables.save'](filename=None, family=family)
ret['comment'] = ('Deleted and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to delete iptables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def set_policy(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Sets the default policy for iptables firewall tables
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
policy
The requested table policy
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if __salt__['iptables.get_policy'](
table,
kwargs['chain'],
family) == kwargs['policy']:
ret['result'] = True
ret['comment'] = ('iptables default policy for chain {0} on table {1} for {2} already set to {3}'
.format(kwargs['chain'], table, family, kwargs['policy']))
return ret
if __opts__['test']:
ret['comment'] = 'iptables default policy for chain {0} on table {1} for {2} needs to be set to {3}'.format(
kwargs['chain'],
table,
family,
kwargs['policy']
)
return ret
if not __salt__['iptables.set_policy'](
table,
kwargs['chain'],
kwargs['policy'],
family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set default policy for {0} to {1} family {2}'.format(
kwargs['chain'],
kwargs['policy'],
family
)
if 'save' in kwargs:
if kwargs['save']:
__salt__['iptables.save'](filename=None, family=family)
ret['comment'] = 'Set and saved default policy for {0} to {1} family {2}'.format(
kwargs['chain'],
kwargs['policy'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set iptables default policy'
return ret
def flush(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Flush current iptables state
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if 'chain' not in kwargs:
kwargs['chain'] = ''
if __opts__['test']:
ret['comment'] = 'iptables rules in {0} table {1} chain {2} family needs to be flushed'.format(
name,
table,
family)
return ret
if not __salt__['iptables.flush'](table, kwargs['chain'], family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Flush iptables rules in {0} table {1} chain {2} family'.format(
table,
kwargs['chain'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to flush iptables rules'
return ret
def mod_aggregate(low, chunks, running):
'''
The mod_aggregate function which looks up all rules in the available
low chunks and merges them into a single rules ref in the present low data
'''
rules = []
agg_enabled = [
'append',
'insert',
]
if low.get('fun') not in agg_enabled:
return low
for chunk in chunks:
tag = __utils__['state.gen_tag'](chunk)
if tag in running:
# Already ran the iptables state, skip aggregation
continue
if chunk.get('state') == 'iptables':
if '__agg__' in chunk:
continue
# Check for the same function
if chunk.get('fun') != low.get('fun'):
continue
if chunk not in rules:
rules.append(chunk)
chunk['__agg__'] = True
if rules:
if 'rules' in low:
low['rules'].extend(rules)
else:
low['rules'] = rules
return low
|
saltstack/salt
|
salt/states/iptables.py
|
delete
|
python
|
def delete(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = delete(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full=True, family=family, command='D', **kwargs)
if not __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
if 'position' not in kwargs:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already absent for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be deleted for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'position' in kwargs:
result = __salt__['iptables.delete'](
table,
kwargs['chain'],
family=family,
position=kwargs['position'])
else:
result = __salt__['iptables.delete'](
table,
kwargs['chain'],
family=family,
rule=rule)
if not result:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Delete iptables rule for {0} {1}'.format(
name,
command.strip())
if 'save' in kwargs:
if kwargs['save']:
out = __salt__['iptables.save'](filename=None, family=family)
ret['comment'] = ('Deleted and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to delete iptables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
|
.. versionadded:: 2014.1.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/iptables.py#L617-L732
|
[
"def delete(name, table='filter', family='ipv4', **kwargs):\n '''\n .. versionadded:: 2014.1.0\n\n Delete a rule to a chain\n\n name\n A user-defined name to call this rule by in another part of a state or\n formula. This should not be an actual rule.\n\n table\n The table that owns the chain that should be modified\n\n family\n Networking family, either ipv4 or ipv6\n\n All other arguments are passed in with the same name as the long option\n that would normally be used for iptables, with one exception: ``--state`` is\n specified as `connstate` instead of `state` (not to be confused with\n `ctstate`).\n\n Jump options that doesn't take arguments should be passed in with an empty\n string.\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': None,\n 'comment': ''}\n\n if 'rules' in kwargs:\n ret['changes']['locale'] = []\n comments = []\n save = False\n for rule in kwargs['rules']:\n if 'rules' in rule:\n del rule['rules']\n if '__agg__' in rule:\n del rule['__agg__']\n if 'save' in rule and rule['save']:\n if rule['save'] is not True:\n save_file = rule['save']\n else:\n save_file = True\n rule['save'] = False\n _ret = delete(**rule)\n if 'locale' in _ret['changes']:\n ret['changes']['locale'].append(_ret['changes']['locale'])\n comments.append(_ret['comment'])\n ret['result'] = _ret['result']\n if save:\n if save_file is True:\n save_file = None\n __salt__['iptables.save'](save_file, family=family)\n if not ret['changes']['locale']:\n del ret['changes']['locale']\n ret['comment'] = '\\n'.join(comments)\n return ret\n\n for ignore in _STATE_INTERNAL_KEYWORDS:\n if ignore in kwargs:\n del kwargs[ignore]\n kwargs['name'] = name\n kwargs['table'] = table\n rule = __salt__['iptables.build_rule'](family=family, **kwargs)\n command = __salt__['iptables.build_rule'](full=True, family=family, command='D', **kwargs)\n\n if not __salt__['iptables.check'](table,\n kwargs['chain'],\n rule,\n family) is True:\n if 'position' not in kwargs:\n ret['result'] = True\n ret['comment'] = 'iptables rule for {0} already absent for {1} ({2})'.format(\n name,\n family,\n command.strip())\n return ret\n if __opts__['test']:\n ret['comment'] = 'iptables rule for {0} needs to be deleted for {1} ({2})'.format(\n name,\n family,\n command.strip())\n return ret\n\n if 'position' in kwargs:\n result = __salt__['iptables.delete'](\n table,\n kwargs['chain'],\n family=family,\n position=kwargs['position'])\n else:\n result = __salt__['iptables.delete'](\n table,\n kwargs['chain'],\n family=family,\n rule=rule)\n\n if not result:\n ret['changes'] = {'locale': name}\n ret['result'] = True\n ret['comment'] = 'Delete iptables rule for {0} {1}'.format(\n name,\n command.strip())\n if 'save' in kwargs:\n if kwargs['save']:\n out = __salt__['iptables.save'](filename=None, family=family)\n ret['comment'] = ('Deleted and saved iptables rule {0} for {1}\\n'\n '{2}\\n{3}').format(name, family, command.strip(), out)\n return ret\n else:\n ret['result'] = False\n ret['comment'] = ('Failed to delete iptables rule for {0}.\\n'\n 'Attempted rule was {1}').format(\n name,\n command.strip())\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Management of iptables
======================
This is an iptables-specific module designed to manage Linux firewalls. It is
expected that this state module, and other system-specific firewall states, may
at some point be deprecated in favor of a more generic ``firewall`` state.
.. code-block:: yaml
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: '127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
.. Invert Rule
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: '! 127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: 'not 127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- family: ipv4
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dports:
- 80
- 443
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.insert:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.insert:
- position: 1
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
default to accept:
iptables.set_policy:
- chain: INPUT
- policy: ACCEPT
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms of
``--protocol``, if ``--proto`` appears in an iptables command after the
appearance of ``-m policy``, it is interpreted as the ``--proto`` option of
the policy extension (see the iptables-extensions(8) man page).
Example rules for IPSec policy:
.. code-block:: yaml
accept_esp_in:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- source: 10.20.0.0/24
- destination: 10.10.0.0/24
- in-interface: eth0
- match: policy
- dir: in
- pol: ipsec
- reqid: 1
- proto: esp
accept_esp_forward_in:
iptables.append:
- use:
- iptables: accept_esp_in
- chain: FORWARD
accept_esp_out:
iptables.append:
- table: filter
- chain: OUTPUT
- jump: ACCEPT
- source: 10.10.0.0/24
- destination: 10.20.0.0/24
- out-interface: eth0
- match: policy
- dir: out
- pol: ipsec
- reqid: 1
- proto: esp
accept_esp_forward_out:
iptables.append:
- use:
- iptables: accept_esp_out
- chain: FORWARD
.. note::
Various functions of the ``iptables`` module use the ``--check`` option. If
the version of ``iptables`` on the target system does not include this
option, an alternate version of this check will be performed using the
output of iptables-save. This may have unintended consequences on legacy
releases of ``iptables``.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
def __virtual__():
'''
Only load if the locale module is available in __salt__
'''
return 'iptables.version' in __salt__
def chain_present(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.1.0
Verify the chain is exist.
name
A user-defined chain name.
table
The table to own the chain.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['iptables.check_chain'](table, name, family)
if chain_check is True:
ret['result'] = True
ret['comment'] = ('iptables {0} chain is already exist in {1} table for {2}'
.format(name, table, family))
return ret
if __opts__['test']:
ret['comment'] = 'iptables {0} chain in {1} table needs to be set for {2}'.format(
name,
table,
family)
return ret
command = __salt__['iptables.new_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('iptables {0} chain in {1} table create success for {2}'
.format(name, table, family))
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format(
name,
table,
command.strip(),
family
)
return ret
def chain_absent(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.1.0
Verify the chain is absent.
table
The table to remove the chain from
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['iptables.check_chain'](table, name, family)
if not chain_check:
ret['result'] = True
ret['comment'] = ('iptables {0} chain is already absent in {1} table for {2}'
.format(name, table, family))
return ret
if __opts__['test']:
ret['comment'] = 'iptables {0} chain in {1} table needs to be removed {2}'.format(
name,
table,
family)
return ret
flush_chain = __salt__['iptables.flush'](table, name, family)
if not flush_chain:
command = __salt__['iptables.delete_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('iptables {0} chain in {1} table delete success for {2}'
.format(name, table, family))
else:
ret['result'] = False
ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}'
.format(name, table, command.strip(), family))
else:
ret['result'] = False
ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format(
name,
table,
flush_chain.strip(),
family
)
return ret
def append(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 0.17.0
Add a rule to the end of the specified chain.
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain which should be modified
family
Network family, ipv4 or ipv6.
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
save = True
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = append(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full='True', family=family, command='A', **kwargs)
if __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already set ({1}) for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs and kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
saved_rules = __salt__['iptables.get_saved_rules'](family=family)
_rules = __salt__['iptables.get_rules'](family=family)
__rules = []
for table in _rules:
for chain in _rules[table]:
__rules.append(_rules[table][chain].get('rules'))
__saved_rules = []
for table in saved_rules:
for chain in saved_rules[table]:
__saved_rules.append(saved_rules[table][chain].get('rules'))
# Only save if rules in memory are different than saved rules
if __rules != __saved_rules:
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] += ('\nSaved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
if __salt__['iptables.append'](table, kwargs['chain'], rule, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set iptables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] = ('Set and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set iptables rule for {0}.\n'
'Attempted rule was {1} for {2}').format(
name,
command.strip(), family)
return ret
def insert(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
position
The numerical representation of where the rule should be inserted into
the chain. Note that ``-1`` is not a supported position value.
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
save = True
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = insert(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full=True, family=family, command='I', **kwargs)
if __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already set for {1} ({2})'.format(
name,
family,
command.strip())
if 'save' in kwargs and kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
saved_rules = __salt__['iptables.get_saved_rules'](family=family)
_rules = __salt__['iptables.get_rules'](family=family)
__rules = []
for table in _rules:
for chain in _rules[table]:
__rules.append(_rules[table][chain].get('rules'))
__saved_rules = []
for table in saved_rules:
for chain in saved_rules[table]:
__saved_rules.append(saved_rules[table][chain].get('rules'))
# Only save if rules in memory are different than saved rules
if __rules != __saved_rules:
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] += ('\nSaved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if not __salt__['iptables.insert'](table, kwargs['chain'], kwargs['position'], rule, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set iptables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
out = __salt__['iptables.save'](filename=None, family=family)
ret['comment'] = ('Set and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set iptables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def set_policy(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Sets the default policy for iptables firewall tables
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
policy
The requested table policy
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if __salt__['iptables.get_policy'](
table,
kwargs['chain'],
family) == kwargs['policy']:
ret['result'] = True
ret['comment'] = ('iptables default policy for chain {0} on table {1} for {2} already set to {3}'
.format(kwargs['chain'], table, family, kwargs['policy']))
return ret
if __opts__['test']:
ret['comment'] = 'iptables default policy for chain {0} on table {1} for {2} needs to be set to {3}'.format(
kwargs['chain'],
table,
family,
kwargs['policy']
)
return ret
if not __salt__['iptables.set_policy'](
table,
kwargs['chain'],
kwargs['policy'],
family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set default policy for {0} to {1} family {2}'.format(
kwargs['chain'],
kwargs['policy'],
family
)
if 'save' in kwargs:
if kwargs['save']:
__salt__['iptables.save'](filename=None, family=family)
ret['comment'] = 'Set and saved default policy for {0} to {1} family {2}'.format(
kwargs['chain'],
kwargs['policy'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set iptables default policy'
return ret
def flush(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Flush current iptables state
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if 'chain' not in kwargs:
kwargs['chain'] = ''
if __opts__['test']:
ret['comment'] = 'iptables rules in {0} table {1} chain {2} family needs to be flushed'.format(
name,
table,
family)
return ret
if not __salt__['iptables.flush'](table, kwargs['chain'], family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Flush iptables rules in {0} table {1} chain {2} family'.format(
table,
kwargs['chain'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to flush iptables rules'
return ret
def mod_aggregate(low, chunks, running):
'''
The mod_aggregate function which looks up all rules in the available
low chunks and merges them into a single rules ref in the present low data
'''
rules = []
agg_enabled = [
'append',
'insert',
]
if low.get('fun') not in agg_enabled:
return low
for chunk in chunks:
tag = __utils__['state.gen_tag'](chunk)
if tag in running:
# Already ran the iptables state, skip aggregation
continue
if chunk.get('state') == 'iptables':
if '__agg__' in chunk:
continue
# Check for the same function
if chunk.get('fun') != low.get('fun'):
continue
if chunk not in rules:
rules.append(chunk)
chunk['__agg__'] = True
if rules:
if 'rules' in low:
low['rules'].extend(rules)
else:
low['rules'] = rules
return low
|
saltstack/salt
|
salt/states/iptables.py
|
set_policy
|
python
|
def set_policy(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Sets the default policy for iptables firewall tables
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
policy
The requested table policy
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if __salt__['iptables.get_policy'](
table,
kwargs['chain'],
family) == kwargs['policy']:
ret['result'] = True
ret['comment'] = ('iptables default policy for chain {0} on table {1} for {2} already set to {3}'
.format(kwargs['chain'], table, family, kwargs['policy']))
return ret
if __opts__['test']:
ret['comment'] = 'iptables default policy for chain {0} on table {1} for {2} needs to be set to {3}'.format(
kwargs['chain'],
table,
family,
kwargs['policy']
)
return ret
if not __salt__['iptables.set_policy'](
table,
kwargs['chain'],
kwargs['policy'],
family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set default policy for {0} to {1} family {2}'.format(
kwargs['chain'],
kwargs['policy'],
family
)
if 'save' in kwargs:
if kwargs['save']:
__salt__['iptables.save'](filename=None, family=family)
ret['comment'] = 'Set and saved default policy for {0} to {1} family {2}'.format(
kwargs['chain'],
kwargs['policy'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set iptables default policy'
return ret
|
.. versionadded:: 2014.1.0
Sets the default policy for iptables firewall tables
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
policy
The requested table policy
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/iptables.py#L735-L800
| null |
# -*- coding: utf-8 -*-
'''
Management of iptables
======================
This is an iptables-specific module designed to manage Linux firewalls. It is
expected that this state module, and other system-specific firewall states, may
at some point be deprecated in favor of a more generic ``firewall`` state.
.. code-block:: yaml
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: '127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
.. Invert Rule
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: '! 127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: 'not 127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- family: ipv4
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dports:
- 80
- 443
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.insert:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.insert:
- position: 1
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
default to accept:
iptables.set_policy:
- chain: INPUT
- policy: ACCEPT
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms of
``--protocol``, if ``--proto`` appears in an iptables command after the
appearance of ``-m policy``, it is interpreted as the ``--proto`` option of
the policy extension (see the iptables-extensions(8) man page).
Example rules for IPSec policy:
.. code-block:: yaml
accept_esp_in:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- source: 10.20.0.0/24
- destination: 10.10.0.0/24
- in-interface: eth0
- match: policy
- dir: in
- pol: ipsec
- reqid: 1
- proto: esp
accept_esp_forward_in:
iptables.append:
- use:
- iptables: accept_esp_in
- chain: FORWARD
accept_esp_out:
iptables.append:
- table: filter
- chain: OUTPUT
- jump: ACCEPT
- source: 10.10.0.0/24
- destination: 10.20.0.0/24
- out-interface: eth0
- match: policy
- dir: out
- pol: ipsec
- reqid: 1
- proto: esp
accept_esp_forward_out:
iptables.append:
- use:
- iptables: accept_esp_out
- chain: FORWARD
.. note::
Various functions of the ``iptables`` module use the ``--check`` option. If
the version of ``iptables`` on the target system does not include this
option, an alternate version of this check will be performed using the
output of iptables-save. This may have unintended consequences on legacy
releases of ``iptables``.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
def __virtual__():
'''
Only load if the locale module is available in __salt__
'''
return 'iptables.version' in __salt__
def chain_present(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.1.0
Verify the chain is exist.
name
A user-defined chain name.
table
The table to own the chain.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['iptables.check_chain'](table, name, family)
if chain_check is True:
ret['result'] = True
ret['comment'] = ('iptables {0} chain is already exist in {1} table for {2}'
.format(name, table, family))
return ret
if __opts__['test']:
ret['comment'] = 'iptables {0} chain in {1} table needs to be set for {2}'.format(
name,
table,
family)
return ret
command = __salt__['iptables.new_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('iptables {0} chain in {1} table create success for {2}'
.format(name, table, family))
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format(
name,
table,
command.strip(),
family
)
return ret
def chain_absent(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.1.0
Verify the chain is absent.
table
The table to remove the chain from
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['iptables.check_chain'](table, name, family)
if not chain_check:
ret['result'] = True
ret['comment'] = ('iptables {0} chain is already absent in {1} table for {2}'
.format(name, table, family))
return ret
if __opts__['test']:
ret['comment'] = 'iptables {0} chain in {1} table needs to be removed {2}'.format(
name,
table,
family)
return ret
flush_chain = __salt__['iptables.flush'](table, name, family)
if not flush_chain:
command = __salt__['iptables.delete_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('iptables {0} chain in {1} table delete success for {2}'
.format(name, table, family))
else:
ret['result'] = False
ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}'
.format(name, table, command.strip(), family))
else:
ret['result'] = False
ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format(
name,
table,
flush_chain.strip(),
family
)
return ret
def append(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 0.17.0
Add a rule to the end of the specified chain.
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain which should be modified
family
Network family, ipv4 or ipv6.
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
save = True
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = append(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full='True', family=family, command='A', **kwargs)
if __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already set ({1}) for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs and kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
saved_rules = __salt__['iptables.get_saved_rules'](family=family)
_rules = __salt__['iptables.get_rules'](family=family)
__rules = []
for table in _rules:
for chain in _rules[table]:
__rules.append(_rules[table][chain].get('rules'))
__saved_rules = []
for table in saved_rules:
for chain in saved_rules[table]:
__saved_rules.append(saved_rules[table][chain].get('rules'))
# Only save if rules in memory are different than saved rules
if __rules != __saved_rules:
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] += ('\nSaved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
if __salt__['iptables.append'](table, kwargs['chain'], rule, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set iptables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] = ('Set and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set iptables rule for {0}.\n'
'Attempted rule was {1} for {2}').format(
name,
command.strip(), family)
return ret
def insert(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
position
The numerical representation of where the rule should be inserted into
the chain. Note that ``-1`` is not a supported position value.
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
save = True
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = insert(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full=True, family=family, command='I', **kwargs)
if __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already set for {1} ({2})'.format(
name,
family,
command.strip())
if 'save' in kwargs and kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
saved_rules = __salt__['iptables.get_saved_rules'](family=family)
_rules = __salt__['iptables.get_rules'](family=family)
__rules = []
for table in _rules:
for chain in _rules[table]:
__rules.append(_rules[table][chain].get('rules'))
__saved_rules = []
for table in saved_rules:
for chain in saved_rules[table]:
__saved_rules.append(saved_rules[table][chain].get('rules'))
# Only save if rules in memory are different than saved rules
if __rules != __saved_rules:
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] += ('\nSaved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if not __salt__['iptables.insert'](table, kwargs['chain'], kwargs['position'], rule, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set iptables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
out = __salt__['iptables.save'](filename=None, family=family)
ret['comment'] = ('Set and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set iptables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def delete(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = delete(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full=True, family=family, command='D', **kwargs)
if not __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
if 'position' not in kwargs:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already absent for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be deleted for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'position' in kwargs:
result = __salt__['iptables.delete'](
table,
kwargs['chain'],
family=family,
position=kwargs['position'])
else:
result = __salt__['iptables.delete'](
table,
kwargs['chain'],
family=family,
rule=rule)
if not result:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Delete iptables rule for {0} {1}'.format(
name,
command.strip())
if 'save' in kwargs:
if kwargs['save']:
out = __salt__['iptables.save'](filename=None, family=family)
ret['comment'] = ('Deleted and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to delete iptables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def flush(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Flush current iptables state
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if 'chain' not in kwargs:
kwargs['chain'] = ''
if __opts__['test']:
ret['comment'] = 'iptables rules in {0} table {1} chain {2} family needs to be flushed'.format(
name,
table,
family)
return ret
if not __salt__['iptables.flush'](table, kwargs['chain'], family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Flush iptables rules in {0} table {1} chain {2} family'.format(
table,
kwargs['chain'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to flush iptables rules'
return ret
def mod_aggregate(low, chunks, running):
'''
The mod_aggregate function which looks up all rules in the available
low chunks and merges them into a single rules ref in the present low data
'''
rules = []
agg_enabled = [
'append',
'insert',
]
if low.get('fun') not in agg_enabled:
return low
for chunk in chunks:
tag = __utils__['state.gen_tag'](chunk)
if tag in running:
# Already ran the iptables state, skip aggregation
continue
if chunk.get('state') == 'iptables':
if '__agg__' in chunk:
continue
# Check for the same function
if chunk.get('fun') != low.get('fun'):
continue
if chunk not in rules:
rules.append(chunk)
chunk['__agg__'] = True
if rules:
if 'rules' in low:
low['rules'].extend(rules)
else:
low['rules'] = rules
return low
|
saltstack/salt
|
salt/states/iptables.py
|
flush
|
python
|
def flush(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Flush current iptables state
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if 'chain' not in kwargs:
kwargs['chain'] = ''
if __opts__['test']:
ret['comment'] = 'iptables rules in {0} table {1} chain {2} family needs to be flushed'.format(
name,
table,
family)
return ret
if not __salt__['iptables.flush'](table, kwargs['chain'], family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Flush iptables rules in {0} table {1} chain {2} family'.format(
table,
kwargs['chain'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to flush iptables rules'
return ret
|
.. versionadded:: 2014.1.0
Flush current iptables state
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/iptables.py#L803-L845
| null |
# -*- coding: utf-8 -*-
'''
Management of iptables
======================
This is an iptables-specific module designed to manage Linux firewalls. It is
expected that this state module, and other system-specific firewall states, may
at some point be deprecated in favor of a more generic ``firewall`` state.
.. code-block:: yaml
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: '127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
.. Invert Rule
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: '! 127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: 'not 127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- family: ipv4
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dports:
- 80
- 443
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.insert:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.insert:
- position: 1
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
default to accept:
iptables.set_policy:
- chain: INPUT
- policy: ACCEPT
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms of
``--protocol``, if ``--proto`` appears in an iptables command after the
appearance of ``-m policy``, it is interpreted as the ``--proto`` option of
the policy extension (see the iptables-extensions(8) man page).
Example rules for IPSec policy:
.. code-block:: yaml
accept_esp_in:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- source: 10.20.0.0/24
- destination: 10.10.0.0/24
- in-interface: eth0
- match: policy
- dir: in
- pol: ipsec
- reqid: 1
- proto: esp
accept_esp_forward_in:
iptables.append:
- use:
- iptables: accept_esp_in
- chain: FORWARD
accept_esp_out:
iptables.append:
- table: filter
- chain: OUTPUT
- jump: ACCEPT
- source: 10.10.0.0/24
- destination: 10.20.0.0/24
- out-interface: eth0
- match: policy
- dir: out
- pol: ipsec
- reqid: 1
- proto: esp
accept_esp_forward_out:
iptables.append:
- use:
- iptables: accept_esp_out
- chain: FORWARD
.. note::
Various functions of the ``iptables`` module use the ``--check`` option. If
the version of ``iptables`` on the target system does not include this
option, an alternate version of this check will be performed using the
output of iptables-save. This may have unintended consequences on legacy
releases of ``iptables``.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
def __virtual__():
'''
Only load if the locale module is available in __salt__
'''
return 'iptables.version' in __salt__
def chain_present(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.1.0
Verify the chain is exist.
name
A user-defined chain name.
table
The table to own the chain.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['iptables.check_chain'](table, name, family)
if chain_check is True:
ret['result'] = True
ret['comment'] = ('iptables {0} chain is already exist in {1} table for {2}'
.format(name, table, family))
return ret
if __opts__['test']:
ret['comment'] = 'iptables {0} chain in {1} table needs to be set for {2}'.format(
name,
table,
family)
return ret
command = __salt__['iptables.new_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('iptables {0} chain in {1} table create success for {2}'
.format(name, table, family))
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format(
name,
table,
command.strip(),
family
)
return ret
def chain_absent(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.1.0
Verify the chain is absent.
table
The table to remove the chain from
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['iptables.check_chain'](table, name, family)
if not chain_check:
ret['result'] = True
ret['comment'] = ('iptables {0} chain is already absent in {1} table for {2}'
.format(name, table, family))
return ret
if __opts__['test']:
ret['comment'] = 'iptables {0} chain in {1} table needs to be removed {2}'.format(
name,
table,
family)
return ret
flush_chain = __salt__['iptables.flush'](table, name, family)
if not flush_chain:
command = __salt__['iptables.delete_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('iptables {0} chain in {1} table delete success for {2}'
.format(name, table, family))
else:
ret['result'] = False
ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}'
.format(name, table, command.strip(), family))
else:
ret['result'] = False
ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format(
name,
table,
flush_chain.strip(),
family
)
return ret
def append(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 0.17.0
Add a rule to the end of the specified chain.
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain which should be modified
family
Network family, ipv4 or ipv6.
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
save = True
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = append(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full='True', family=family, command='A', **kwargs)
if __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already set ({1}) for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs and kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
saved_rules = __salt__['iptables.get_saved_rules'](family=family)
_rules = __salt__['iptables.get_rules'](family=family)
__rules = []
for table in _rules:
for chain in _rules[table]:
__rules.append(_rules[table][chain].get('rules'))
__saved_rules = []
for table in saved_rules:
for chain in saved_rules[table]:
__saved_rules.append(saved_rules[table][chain].get('rules'))
# Only save if rules in memory are different than saved rules
if __rules != __saved_rules:
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] += ('\nSaved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
if __salt__['iptables.append'](table, kwargs['chain'], rule, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set iptables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] = ('Set and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set iptables rule for {0}.\n'
'Attempted rule was {1} for {2}').format(
name,
command.strip(), family)
return ret
def insert(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
position
The numerical representation of where the rule should be inserted into
the chain. Note that ``-1`` is not a supported position value.
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
save = True
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = insert(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full=True, family=family, command='I', **kwargs)
if __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already set for {1} ({2})'.format(
name,
family,
command.strip())
if 'save' in kwargs and kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
saved_rules = __salt__['iptables.get_saved_rules'](family=family)
_rules = __salt__['iptables.get_rules'](family=family)
__rules = []
for table in _rules:
for chain in _rules[table]:
__rules.append(_rules[table][chain].get('rules'))
__saved_rules = []
for table in saved_rules:
for chain in saved_rules[table]:
__saved_rules.append(saved_rules[table][chain].get('rules'))
# Only save if rules in memory are different than saved rules
if __rules != __saved_rules:
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] += ('\nSaved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if not __salt__['iptables.insert'](table, kwargs['chain'], kwargs['position'], rule, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set iptables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
out = __salt__['iptables.save'](filename=None, family=family)
ret['comment'] = ('Set and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set iptables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def delete(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = delete(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full=True, family=family, command='D', **kwargs)
if not __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
if 'position' not in kwargs:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already absent for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be deleted for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'position' in kwargs:
result = __salt__['iptables.delete'](
table,
kwargs['chain'],
family=family,
position=kwargs['position'])
else:
result = __salt__['iptables.delete'](
table,
kwargs['chain'],
family=family,
rule=rule)
if not result:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Delete iptables rule for {0} {1}'.format(
name,
command.strip())
if 'save' in kwargs:
if kwargs['save']:
out = __salt__['iptables.save'](filename=None, family=family)
ret['comment'] = ('Deleted and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to delete iptables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def set_policy(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Sets the default policy for iptables firewall tables
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
policy
The requested table policy
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if __salt__['iptables.get_policy'](
table,
kwargs['chain'],
family) == kwargs['policy']:
ret['result'] = True
ret['comment'] = ('iptables default policy for chain {0} on table {1} for {2} already set to {3}'
.format(kwargs['chain'], table, family, kwargs['policy']))
return ret
if __opts__['test']:
ret['comment'] = 'iptables default policy for chain {0} on table {1} for {2} needs to be set to {3}'.format(
kwargs['chain'],
table,
family,
kwargs['policy']
)
return ret
if not __salt__['iptables.set_policy'](
table,
kwargs['chain'],
kwargs['policy'],
family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set default policy for {0} to {1} family {2}'.format(
kwargs['chain'],
kwargs['policy'],
family
)
if 'save' in kwargs:
if kwargs['save']:
__salt__['iptables.save'](filename=None, family=family)
ret['comment'] = 'Set and saved default policy for {0} to {1} family {2}'.format(
kwargs['chain'],
kwargs['policy'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set iptables default policy'
return ret
def mod_aggregate(low, chunks, running):
'''
The mod_aggregate function which looks up all rules in the available
low chunks and merges them into a single rules ref in the present low data
'''
rules = []
agg_enabled = [
'append',
'insert',
]
if low.get('fun') not in agg_enabled:
return low
for chunk in chunks:
tag = __utils__['state.gen_tag'](chunk)
if tag in running:
# Already ran the iptables state, skip aggregation
continue
if chunk.get('state') == 'iptables':
if '__agg__' in chunk:
continue
# Check for the same function
if chunk.get('fun') != low.get('fun'):
continue
if chunk not in rules:
rules.append(chunk)
chunk['__agg__'] = True
if rules:
if 'rules' in low:
low['rules'].extend(rules)
else:
low['rules'] = rules
return low
|
saltstack/salt
|
salt/states/iptables.py
|
mod_aggregate
|
python
|
def mod_aggregate(low, chunks, running):
'''
The mod_aggregate function which looks up all rules in the available
low chunks and merges them into a single rules ref in the present low data
'''
rules = []
agg_enabled = [
'append',
'insert',
]
if low.get('fun') not in agg_enabled:
return low
for chunk in chunks:
tag = __utils__['state.gen_tag'](chunk)
if tag in running:
# Already ran the iptables state, skip aggregation
continue
if chunk.get('state') == 'iptables':
if '__agg__' in chunk:
continue
# Check for the same function
if chunk.get('fun') != low.get('fun'):
continue
if chunk not in rules:
rules.append(chunk)
chunk['__agg__'] = True
if rules:
if 'rules' in low:
low['rules'].extend(rules)
else:
low['rules'] = rules
return low
|
The mod_aggregate function which looks up all rules in the available
low chunks and merges them into a single rules ref in the present low data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/iptables.py#L848-L881
| null |
# -*- coding: utf-8 -*-
'''
Management of iptables
======================
This is an iptables-specific module designed to manage Linux firewalls. It is
expected that this state module, and other system-specific firewall states, may
at some point be deprecated in favor of a more generic ``firewall`` state.
.. code-block:: yaml
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: '127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
.. Invert Rule
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: '! 127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match:
- state
- comment
- comment: "Allow HTTP"
- connstate: NEW
- source: 'not 127.0.0.1'
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.append:
- table: filter
- family: ipv4
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dports:
- 80
- 443
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.insert:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.insert:
- position: 1
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
httpd:
iptables.delete:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- protocol: tcp
- sport: 1025:65535
- save: True
default to accept:
iptables.set_policy:
- chain: INPUT
- policy: ACCEPT
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms of
``--protocol``, if ``--proto`` appears in an iptables command after the
appearance of ``-m policy``, it is interpreted as the ``--proto`` option of
the policy extension (see the iptables-extensions(8) man page).
Example rules for IPSec policy:
.. code-block:: yaml
accept_esp_in:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- source: 10.20.0.0/24
- destination: 10.10.0.0/24
- in-interface: eth0
- match: policy
- dir: in
- pol: ipsec
- reqid: 1
- proto: esp
accept_esp_forward_in:
iptables.append:
- use:
- iptables: accept_esp_in
- chain: FORWARD
accept_esp_out:
iptables.append:
- table: filter
- chain: OUTPUT
- jump: ACCEPT
- source: 10.10.0.0/24
- destination: 10.20.0.0/24
- out-interface: eth0
- match: policy
- dir: out
- pol: ipsec
- reqid: 1
- proto: esp
accept_esp_forward_out:
iptables.append:
- use:
- iptables: accept_esp_out
- chain: FORWARD
.. note::
Various functions of the ``iptables`` module use the ``--check`` option. If
the version of ``iptables`` on the target system does not include this
option, an alternate version of this check will be performed using the
output of iptables-save. This may have unintended consequences on legacy
releases of ``iptables``.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
def __virtual__():
'''
Only load if the locale module is available in __salt__
'''
return 'iptables.version' in __salt__
def chain_present(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.1.0
Verify the chain is exist.
name
A user-defined chain name.
table
The table to own the chain.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['iptables.check_chain'](table, name, family)
if chain_check is True:
ret['result'] = True
ret['comment'] = ('iptables {0} chain is already exist in {1} table for {2}'
.format(name, table, family))
return ret
if __opts__['test']:
ret['comment'] = 'iptables {0} chain in {1} table needs to be set for {2}'.format(
name,
table,
family)
return ret
command = __salt__['iptables.new_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('iptables {0} chain in {1} table create success for {2}'
.format(name, table, family))
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format(
name,
table,
command.strip(),
family
)
return ret
def chain_absent(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.1.0
Verify the chain is absent.
table
The table to remove the chain from
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['iptables.check_chain'](table, name, family)
if not chain_check:
ret['result'] = True
ret['comment'] = ('iptables {0} chain is already absent in {1} table for {2}'
.format(name, table, family))
return ret
if __opts__['test']:
ret['comment'] = 'iptables {0} chain in {1} table needs to be removed {2}'.format(
name,
table,
family)
return ret
flush_chain = __salt__['iptables.flush'](table, name, family)
if not flush_chain:
command = __salt__['iptables.delete_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('iptables {0} chain in {1} table delete success for {2}'
.format(name, table, family))
else:
ret['result'] = False
ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}'
.format(name, table, command.strip(), family))
else:
ret['result'] = False
ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format(
name,
table,
flush_chain.strip(),
family
)
return ret
def append(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 0.17.0
Add a rule to the end of the specified chain.
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain which should be modified
family
Network family, ipv4 or ipv6.
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
save = True
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = append(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full='True', family=family, command='A', **kwargs)
if __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already set ({1}) for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs and kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
saved_rules = __salt__['iptables.get_saved_rules'](family=family)
_rules = __salt__['iptables.get_rules'](family=family)
__rules = []
for table in _rules:
for chain in _rules[table]:
__rules.append(_rules[table][chain].get('rules'))
__saved_rules = []
for table in saved_rules:
for chain in saved_rules[table]:
__saved_rules.append(saved_rules[table][chain].get('rules'))
# Only save if rules in memory are different than saved rules
if __rules != __saved_rules:
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] += ('\nSaved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
if __salt__['iptables.append'](table, kwargs['chain'], rule, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set iptables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] = ('Set and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set iptables rule for {0}.\n'
'Attempted rule was {1} for {2}').format(
name,
command.strip(), family)
return ret
def insert(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
position
The numerical representation of where the rule should be inserted into
the chain. Note that ``-1`` is not a supported position value.
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
save = True
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = insert(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full=True, family=family, command='I', **kwargs)
if __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already set for {1} ({2})'.format(
name,
family,
command.strip())
if 'save' in kwargs and kwargs['save']:
if kwargs['save'] is not True:
filename = kwargs['save']
else:
filename = None
saved_rules = __salt__['iptables.get_saved_rules'](family=family)
_rules = __salt__['iptables.get_rules'](family=family)
__rules = []
for table in _rules:
for chain in _rules[table]:
__rules.append(_rules[table][chain].get('rules'))
__saved_rules = []
for table in saved_rules:
for chain in saved_rules[table]:
__saved_rules.append(saved_rules[table][chain].get('rules'))
# Only save if rules in memory are different than saved rules
if __rules != __saved_rules:
out = __salt__['iptables.save'](filename, family=family)
ret['comment'] += ('\nSaved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if not __salt__['iptables.insert'](table, kwargs['chain'], kwargs['position'], rule, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set iptables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
out = __salt__['iptables.save'](filename=None, family=family)
ret['comment'] = ('Set and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set iptables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def delete(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for iptables, with one exception: ``--state`` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
Jump options that doesn't take arguments should be passed in with an empty
string.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if 'rules' in kwargs:
ret['changes']['locale'] = []
comments = []
save = False
for rule in kwargs['rules']:
if 'rules' in rule:
del rule['rules']
if '__agg__' in rule:
del rule['__agg__']
if 'save' in rule and rule['save']:
if rule['save'] is not True:
save_file = rule['save']
else:
save_file = True
rule['save'] = False
_ret = delete(**rule)
if 'locale' in _ret['changes']:
ret['changes']['locale'].append(_ret['changes']['locale'])
comments.append(_ret['comment'])
ret['result'] = _ret['result']
if save:
if save_file is True:
save_file = None
__salt__['iptables.save'](save_file, family=family)
if not ret['changes']['locale']:
del ret['changes']['locale']
ret['comment'] = '\n'.join(comments)
return ret
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
kwargs['name'] = name
kwargs['table'] = table
rule = __salt__['iptables.build_rule'](family=family, **kwargs)
command = __salt__['iptables.build_rule'](full=True, family=family, command='D', **kwargs)
if not __salt__['iptables.check'](table,
kwargs['chain'],
rule,
family) is True:
if 'position' not in kwargs:
ret['result'] = True
ret['comment'] = 'iptables rule for {0} already absent for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if __opts__['test']:
ret['comment'] = 'iptables rule for {0} needs to be deleted for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'position' in kwargs:
result = __salt__['iptables.delete'](
table,
kwargs['chain'],
family=family,
position=kwargs['position'])
else:
result = __salt__['iptables.delete'](
table,
kwargs['chain'],
family=family,
rule=rule)
if not result:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Delete iptables rule for {0} {1}'.format(
name,
command.strip())
if 'save' in kwargs:
if kwargs['save']:
out = __salt__['iptables.save'](filename=None, family=family)
ret['comment'] = ('Deleted and saved iptables rule {0} for {1}\n'
'{2}\n{3}').format(name, family, command.strip(), out)
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to delete iptables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def set_policy(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Sets the default policy for iptables firewall tables
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
policy
The requested table policy
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if __salt__['iptables.get_policy'](
table,
kwargs['chain'],
family) == kwargs['policy']:
ret['result'] = True
ret['comment'] = ('iptables default policy for chain {0} on table {1} for {2} already set to {3}'
.format(kwargs['chain'], table, family, kwargs['policy']))
return ret
if __opts__['test']:
ret['comment'] = 'iptables default policy for chain {0} on table {1} for {2} needs to be set to {3}'.format(
kwargs['chain'],
table,
family,
kwargs['policy']
)
return ret
if not __salt__['iptables.set_policy'](
table,
kwargs['chain'],
kwargs['policy'],
family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set default policy for {0} to {1} family {2}'.format(
kwargs['chain'],
kwargs['policy'],
family
)
if 'save' in kwargs:
if kwargs['save']:
__salt__['iptables.save'](filename=None, family=family)
ret['comment'] = 'Set and saved default policy for {0} to {1} family {2}'.format(
kwargs['chain'],
kwargs['policy'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set iptables default policy'
return ret
def flush(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Flush current iptables state
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if 'chain' not in kwargs:
kwargs['chain'] = ''
if __opts__['test']:
ret['comment'] = 'iptables rules in {0} table {1} chain {2} family needs to be flushed'.format(
name,
table,
family)
return ret
if not __salt__['iptables.flush'](table, kwargs['chain'], family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Flush iptables rules in {0} table {1} chain {2} family'.format(
table,
kwargs['chain'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to flush iptables rules'
return ret
|
saltstack/salt
|
salt/beacons/memusage.py
|
beacon
|
python
|
def beacon(config):
'''
Monitor the memory usage of the minion
Specify thresholds for percent used and only emit a beacon
if it is exceeded.
.. code-block:: yaml
beacons:
memusage:
- percent: 63%
'''
ret = []
_config = {}
list(map(_config.update, config))
_current_usage = psutil.virtual_memory()
current_usage = _current_usage.percent
monitor_usage = _config['percent']
if '%' in monitor_usage:
monitor_usage = re.sub('%', '', monitor_usage)
monitor_usage = float(monitor_usage)
if current_usage >= monitor_usage:
ret.append({'memusage': current_usage})
return ret
|
Monitor the memory usage of the minion
Specify thresholds for percent used and only emit a beacon
if it is exceeded.
.. code-block:: yaml
beacons:
memusage:
- percent: 63%
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/memusage.py#L54-L81
| null |
# -*- coding: utf-8 -*-
'''
Beacon to monitor memory usage.
.. versionadded:: 2016.3.0
:depends: python-psutil
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
import re
from salt.ext.six.moves import map
# Import Third Party Libs
try:
import psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
__virtualname__ = 'memusage'
def __virtual__():
if HAS_PSUTIL is False:
return False
else:
return __virtualname__
def validate(config):
'''
Validate the beacon configuration
'''
# Configuration for memusage beacon should be a list of dicts
if not isinstance(config, list):
return False, ('Configuration for memusage '
'beacon must be a list.')
else:
_config = {}
list(map(_config.update, config))
if 'percent' not in _config:
return False, ('Configuration for memusage beacon '
'requires percent.')
return True, 'Valid beacon configuration'
|
saltstack/salt
|
doc/_ext/saltautodoc.py
|
SaltFunctionDocumenter.format_name
|
python
|
def format_name(self):
'''
Format the function name
'''
if not hasattr(self.module, '__func_alias__'):
# Resume normal sphinx.ext.autodoc operation
return super(FunctionDocumenter, self).format_name()
if not self.objpath:
# Resume normal sphinx.ext.autodoc operation
return super(FunctionDocumenter, self).format_name()
if len(self.objpath) > 1:
# Resume normal sphinx.ext.autodoc operation
return super(FunctionDocumenter, self).format_name()
# Use the salt func aliased name instead of the real name
return self.module.__func_alias__.get(self.objpath[0], self.objpath[0])
|
Format the function name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/doc/_ext/saltautodoc.py#L22-L39
| null |
class SaltFunctionDocumenter(FunctionDocumenter):
'''
Simple override of sphinx.ext.autodoc.FunctionDocumenter to properly render
salt's aliased function names.
'''
|
saltstack/salt
|
salt/states/ntp.py
|
managed
|
python
|
def managed(name, servers=None):
'''
Manage NTP servers
servers
A list of NTP servers
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'NTP servers already configured as specified'}
if not _check_servers(servers):
ret['result'] = False
ret['comment'] = 'NTP servers must be a list of strings'
before_servers = _get_servers()
desired_servers = set(servers)
if before_servers == desired_servers:
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = ('NTP servers will be updated to: {0}'
.format(', '.join(sorted(desired_servers))))
return ret
__salt__['ntp.set_servers'](*desired_servers)
after_servers = _get_servers()
if after_servers == desired_servers:
ret['comment'] = 'NTP servers updated'
ret['changes'] = {'old': sorted(before_servers),
'new': sorted(after_servers)}
else:
ret['result'] = False
ret['comment'] = 'Failed to update NTP servers'
if before_servers != after_servers:
ret['changes'] = {'old': sorted(before_servers),
'new': sorted(after_servers)}
return ret
|
Manage NTP servers
servers
A list of NTP servers
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ntp.py#L58-L100
|
[
"def _check_servers(servers):\n if not isinstance(servers, list):\n return False\n for server in servers:\n if not isinstance(server, six.string_types):\n return False\n return True\n",
"def _get_servers():\n try:\n return set(__salt__['ntp.get_servers']())\n except TypeError:\n return set([False])\n"
] |
# -*- coding: utf-8 -*-
'''
Management of NTP servers
=========================
.. versionadded:: 2014.1.0
This state is used to manage NTP servers. Currently only Windows is supported.
.. code-block:: yaml
win_ntp:
ntp.managed:
- servers:
- pool.ntp.org
- us.pool.ntp.org
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
This only supports Windows
'''
if not salt.utils.platform.is_windows():
return False
return 'ntp'
def _check_servers(servers):
if not isinstance(servers, list):
return False
for server in servers:
if not isinstance(server, six.string_types):
return False
return True
def _get_servers():
try:
return set(__salt__['ntp.get_servers']())
except TypeError:
return set([False])
|
saltstack/salt
|
salt/modules/iptables.py
|
_iptables_cmd
|
python
|
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
|
Return correct command based on the family, e.g. ipv4 or ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L59-L66
| null |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
_has_option
|
python
|
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
|
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L69-L81
|
[
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
_conf
|
python
|
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
|
Some distros have a specific location for config files
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L84-L124
| null |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
_regex_iptables_save
|
python
|
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
|
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L142-L174
| null |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
version
|
python
|
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
|
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L177-L192
|
[
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
build_rule
|
python
|
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
|
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L195-L545
|
[
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n",
"def _has_option(option, family='ipv4'):\n '''\n Return truth of whether iptables has `option`. For example:\n\n .. code-block:: python\n\n _has_option('--wait')\n _has_option('--check', family='ipv6')\n '''\n cmd = '{0} --help'.format(_iptables_cmd(family))\n if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):\n return True\n return False\n",
"def maybe_add_negation(arg):\n '''\n Will check if the defined argument is intended to be negated,\n (i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.\n\n The prefix will be removed from the value in the kwargs dict.\n '''\n value = str(kwargs[arg])\n if value.startswith('!') or value.startswith('not'):\n kwargs[arg] = re.sub(bang_not_pat, '', value)\n return '! '\n return ''\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
get_saved_policy
|
python
|
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
|
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L581-L606
|
[
"def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):\n '''\n If a file is not passed in, and the correct one for this OS is not\n detected, return False\n '''\n if _conf() and not conf_file and not in_mem:\n conf_file = _conf(family)\n\n rules = ''\n if conf_file:\n with salt.utils.files.fopen(conf_file, 'r') as ifile:\n rules = ifile.read()\n elif in_mem:\n cmd = '{0}-save' . format(_iptables_cmd(family))\n rules = __salt__['cmd.run'](cmd)\n else:\n raise SaltException('A file was not found to parse')\n\n ret = {}\n table = ''\n parser = _parser()\n for line in rules.splitlines():\n line = salt.utils.stringutils.to_unicode(line)\n if line.startswith('*'):\n table = line.replace('*', '')\n ret[table] = {}\n elif line.startswith(':'):\n comps = line.split()\n chain = comps[0].replace(':', '')\n ret[table][chain] = {}\n ret[table][chain]['policy'] = comps[1]\n counters = comps[2].replace('[', '').replace(']', '')\n (pcount, bcount) = counters.split(':')\n ret[table][chain]['packet count'] = pcount\n ret[table][chain]['byte count'] = bcount\n ret[table][chain]['rules'] = []\n ret[table][chain]['rules_comment'] = {}\n elif line.startswith('-A'):\n args = salt.utils.args.shlex_split(line)\n index = 0\n while index + 1 < len(args):\n swap = args[index] == '!' and args[index + 1].startswith('-')\n if swap:\n args[index], args[index + 1] = args[index + 1], args[index]\n if args[index].startswith('-'):\n index += 1\n if args[index].startswith('-') or (args[index] == '!' and\n not swap):\n args.insert(index, '')\n else:\n while (index + 1 < len(args) and\n args[index + 1] != '!' and\n not args[index + 1].startswith('-')):\n args[index] += ' {0}'.format(args.pop(index + 1))\n index += 1\n if args[-1].startswith('-'):\n args.append('')\n parsed_args = []\n opts, _ = parser.parse_known_args(args)\n parsed_args = vars(opts)\n ret_args = {}\n chain = parsed_args['append']\n for arg in parsed_args:\n if parsed_args[arg] and arg is not 'append':\n ret_args[arg] = parsed_args[arg]\n if parsed_args['comment'] is not None:\n comment = parsed_args['comment'][0].strip('\"')\n ret[table][chain[0]]['rules_comment'][comment] = ret_args\n ret[table][chain[0]]['rules'].append(ret_args)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
get_policy
|
python
|
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
|
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L609-L629
|
[
"def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):\n '''\n If a file is not passed in, and the correct one for this OS is not\n detected, return False\n '''\n if _conf() and not conf_file and not in_mem:\n conf_file = _conf(family)\n\n rules = ''\n if conf_file:\n with salt.utils.files.fopen(conf_file, 'r') as ifile:\n rules = ifile.read()\n elif in_mem:\n cmd = '{0}-save' . format(_iptables_cmd(family))\n rules = __salt__['cmd.run'](cmd)\n else:\n raise SaltException('A file was not found to parse')\n\n ret = {}\n table = ''\n parser = _parser()\n for line in rules.splitlines():\n line = salt.utils.stringutils.to_unicode(line)\n if line.startswith('*'):\n table = line.replace('*', '')\n ret[table] = {}\n elif line.startswith(':'):\n comps = line.split()\n chain = comps[0].replace(':', '')\n ret[table][chain] = {}\n ret[table][chain]['policy'] = comps[1]\n counters = comps[2].replace('[', '').replace(']', '')\n (pcount, bcount) = counters.split(':')\n ret[table][chain]['packet count'] = pcount\n ret[table][chain]['byte count'] = bcount\n ret[table][chain]['rules'] = []\n ret[table][chain]['rules_comment'] = {}\n elif line.startswith('-A'):\n args = salt.utils.args.shlex_split(line)\n index = 0\n while index + 1 < len(args):\n swap = args[index] == '!' and args[index + 1].startswith('-')\n if swap:\n args[index], args[index + 1] = args[index + 1], args[index]\n if args[index].startswith('-'):\n index += 1\n if args[index].startswith('-') or (args[index] == '!' and\n not swap):\n args.insert(index, '')\n else:\n while (index + 1 < len(args) and\n args[index + 1] != '!' and\n not args[index + 1].startswith('-')):\n args[index] += ' {0}'.format(args.pop(index + 1))\n index += 1\n if args[-1].startswith('-'):\n args.append('')\n parsed_args = []\n opts, _ = parser.parse_known_args(args)\n parsed_args = vars(opts)\n ret_args = {}\n chain = parsed_args['append']\n for arg in parsed_args:\n if parsed_args[arg] and arg is not 'append':\n ret_args[arg] = parsed_args[arg]\n if parsed_args['comment'] is not None:\n comment = parsed_args['comment'][0].strip('\"')\n ret[table][chain[0]]['rules_comment'][comment] = ret_args\n ret[table][chain[0]]['rules'].append(ret_args)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
set_policy
|
python
|
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
|
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L632-L654
|
[
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n",
"def _has_option(option, family='ipv4'):\n '''\n Return truth of whether iptables has `option`. For example:\n\n .. code-block:: python\n\n _has_option('--wait')\n _has_option('--check', family='ipv6')\n '''\n cmd = '{0} --help'.format(_iptables_cmd(family))\n if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
save
|
python
|
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
|
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L657-L686
|
[
"def _conf(family='ipv4'):\n '''\n Some distros have a specific location for config files\n '''\n if __grains__['os_family'] == 'RedHat':\n if family == 'ipv6':\n return '/etc/sysconfig/ip6tables'\n else:\n return '/etc/sysconfig/iptables'\n elif __grains__['os_family'] == 'Arch':\n if family == 'ipv6':\n return '/etc/iptables/ip6tables.rules'\n else:\n return '/etc/iptables/iptables.rules'\n elif __grains__['os_family'] == 'Debian':\n if family == 'ipv6':\n return '/etc/iptables/rules.v6'\n else:\n return '/etc/iptables/rules.v4'\n elif __grains__['os_family'] == 'Gentoo':\n if family == 'ipv6':\n return '/var/lib/ip6tables/rules-save'\n else:\n return '/var/lib/iptables/rules-save'\n elif __grains__['os_family'] == 'Suse':\n # SuSE does not seem to use separate files for IPv4 and IPv6\n return '/etc/sysconfig/scripts/SuSEfirewall2-custom'\n elif __grains__['os_family'] == 'Void':\n if family == 'ipv4':\n return '/etc/iptables/iptables.rules'\n else:\n return '/etc/iptables/ip6tables.rules'\n elif __grains__['os'] == 'Alpine':\n if family == 'ipv6':\n return '/etc/iptables/rules6-save'\n else:\n return '/etc/iptables/rules-save'\n else:\n raise SaltException('Saving iptables to file is not' +\n ' supported on {0}.'.format(__grains__['os']) +\n ' Please file an issue with SaltStack')\n",
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n",
"def _conf_save_filters():\n '''\n Return array of strings from `save_filters` in config.\n\n This array will be pulled from minion config, minion grains,\n minion pillar, or master config. The default value returned is [].\n\n .. code-block:: python\n\n _conf_save_filters()\n '''\n config = __salt__['config.option']('iptables.save_filters', [])\n return config\n",
"def _regex_iptables_save(cmd_output, filters=None):\n '''\n Return string with `save_filter` regex entries removed. For example:\n\n If `filters` is not provided, it will be pulled from minion config,\n minion grains, minion pillar, or master config. Default return value\n if no filters found is the original cmd_output string.\n\n .. code-block:: python\n\n _regex_iptables_save(cmd_output, ['-A DOCKER*'])\n '''\n # grab RE compiled filters from context for performance\n if 'iptables.save_filters' not in __context__:\n __context__['iptables.save_filters'] = []\n for pattern in filters or _conf_save_filters():\n try:\n __context__['iptables.save_filters']\\\n .append(re.compile(pattern))\n except re.error as e:\n log.warning('Skipping regex rule: \\'%s\\': %s',\n pattern, e)\n continue\n\n if __context__['iptables.save_filters']:\n # line by line get rid of any regex matches\n _filtered_cmd_output = \\\n [line for line in cmd_output.splitlines(True)\n if not any(reg.search(line) for reg\n in __context__['iptables.save_filters'])]\n return ''.join(_filtered_cmd_output)\n\n return cmd_output\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
check
|
python
|
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
|
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L689-L741
|
[
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n",
"def _has_option(option, family='ipv4'):\n '''\n Return truth of whether iptables has `option`. For example:\n\n .. code-block:: python\n\n _has_option('--wait')\n _has_option('--check', family='ipv6')\n '''\n cmd = '{0} --help'.format(_iptables_cmd(family))\n if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
check_chain
|
python
|
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
|
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L744-L771
|
[
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
new_chain
|
python
|
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
|
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L774-L800
|
[
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n",
"def _has_option(option, family='ipv4'):\n '''\n Return truth of whether iptables has `option`. For example:\n\n .. code-block:: python\n\n _has_option('--wait')\n _has_option('--check', family='ipv6')\n '''\n cmd = '{0} --help'.format(_iptables_cmd(family))\n if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
append
|
python
|
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
|
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L832-L865
|
[
"def check(table='filter', chain=None, rule=None, family='ipv4'):\n '''\n Check for the existence of a rule in the table and chain\n\n This function accepts a rule in a standard iptables command format,\n starting with the chain. Trying to force users to adapt to a new\n method of creating rules would be irritating at best, and we\n already have a parser that can handle it.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' iptables.check filter INPUT \\\\\n rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'\n\n IPv6:\n salt '*' iptables.check filter INPUT \\\\\n rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\\\\n family=ipv6\n '''\n if not chain:\n return 'Error: Chain needs to be specified'\n if not rule:\n return 'Error: Rule needs to be specified'\n ipt_cmd = _iptables_cmd(family)\n\n if _has_option('--check', family):\n cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)\n out = __salt__['cmd.run'](cmd, output_loglevel='quiet')\n else:\n _chain_name = hex(uuid.getnode())\n\n # Create temporary table\n __salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))\n __salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))\n\n out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))\n\n # Clean up temporary table\n __salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))\n __salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))\n\n for i in out.splitlines():\n if i.startswith('-A {0}'.format(_chain_name)):\n if i.replace(_chain_name, chain) in out.splitlines():\n return True\n\n return False\n\n if not out:\n return True\n return out\n",
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n",
"def _has_option(option, family='ipv4'):\n '''\n Return truth of whether iptables has `option`. For example:\n\n .. code-block:: python\n\n _has_option('--wait')\n _has_option('--check', family='ipv6')\n '''\n cmd = '{0} --help'.format(_iptables_cmd(family))\n if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
insert
|
python
|
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
|
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L868-L915
|
[
"def check(table='filter', chain=None, rule=None, family='ipv4'):\n '''\n Check for the existence of a rule in the table and chain\n\n This function accepts a rule in a standard iptables command format,\n starting with the chain. Trying to force users to adapt to a new\n method of creating rules would be irritating at best, and we\n already have a parser that can handle it.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' iptables.check filter INPUT \\\\\n rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'\n\n IPv6:\n salt '*' iptables.check filter INPUT \\\\\n rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\\\\n family=ipv6\n '''\n if not chain:\n return 'Error: Chain needs to be specified'\n if not rule:\n return 'Error: Rule needs to be specified'\n ipt_cmd = _iptables_cmd(family)\n\n if _has_option('--check', family):\n cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)\n out = __salt__['cmd.run'](cmd, output_loglevel='quiet')\n else:\n _chain_name = hex(uuid.getnode())\n\n # Create temporary table\n __salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))\n __salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))\n\n out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))\n\n # Clean up temporary table\n __salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))\n __salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))\n\n for i in out.splitlines():\n if i.startswith('-A {0}'.format(_chain_name)):\n if i.replace(_chain_name, chain) in out.splitlines():\n return True\n\n return False\n\n if not out:\n return True\n return out\n",
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n",
"def _has_option(option, family='ipv4'):\n '''\n Return truth of whether iptables has `option`. For example:\n\n .. code-block:: python\n\n _has_option('--wait')\n _has_option('--check', family='ipv6')\n '''\n cmd = '{0} --help'.format(_iptables_cmd(family))\n if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):\n return True\n return False\n",
"def get_rules(family='ipv4'):\n '''\n Return a data structure of the current, in-memory rules\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' iptables.get_rules\n\n IPv6:\n salt '*' iptables.get_rules family=ipv6\n\n '''\n return _parse_conf(in_mem=True, family=family)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
delete
|
python
|
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
|
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L918-L953
|
[
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n",
"def _has_option(option, family='ipv4'):\n '''\n Return truth of whether iptables has `option`. For example:\n\n .. code-block:: python\n\n _has_option('--wait')\n _has_option('--check', family='ipv6')\n '''\n cmd = '{0} --help'.format(_iptables_cmd(family))\n if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
flush
|
python
|
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
|
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L956-L974
|
[
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n",
"def _has_option(option, family='ipv4'):\n '''\n Return truth of whether iptables has `option`. For example:\n\n .. code-block:: python\n\n _has_option('--wait')\n _has_option('--check', family='ipv6')\n '''\n cmd = '{0} --help'.format(_iptables_cmd(family))\n if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
_parse_conf
|
python
|
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
|
If a file is not passed in, and the correct one for this OS is not
detected, return False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L977-L1046
|
[
"def _parser():\n '''\n This function attempts to list all the options documented in the\n iptables(8) and iptables-extensions(8) man pages. They will not all be\n used by all parts of the module; use them intelligently and appropriately.\n '''\n add_arg = None\n if sys.version.startswith('2.6'):\n import optparse\n parser = optparse.OptionParser()\n add_arg = parser.add_option\n else:\n import argparse # pylint: disable=minimum-python-version\n parser = argparse.ArgumentParser()\n add_arg = parser.add_argument\n\n # COMMANDS\n add_arg('-A', '--append', dest='append', action='append')\n add_arg('-D', '--delete', dest='delete', action='append')\n add_arg('-I', '--insert', dest='insert', action='append')\n add_arg('-R', '--replace', dest='replace', action='append')\n add_arg('-L', '--list', dest='list', action='append')\n add_arg('-F', '--flush', dest='flush', action='append')\n add_arg('-Z', '--zero', dest='zero', action='append')\n add_arg('-N', '--new-chain', dest='new-chain', action='append')\n add_arg('-X', '--delete-chain', dest='delete-chain', action='append')\n add_arg('-P', '--policy', dest='policy', action='append')\n add_arg('-E', '--rename-chain', dest='rename-chain', action='append')\n\n # PARAMETERS\n add_arg('-p', '--protocol', dest='protocol', action='append')\n add_arg('-s', '--source', dest='source', action='append')\n add_arg('-d', '--destination', dest='destination', action='append')\n add_arg('-j', '--jump', dest='jump', action='append')\n add_arg('-g', '--goto', dest='goto', action='append')\n add_arg('-i', '--in-interface', dest='in-interface', action='append')\n add_arg('-o', '--out-interface', dest='out-interface', action='append')\n add_arg('-f', '--fragment', dest='fragment', action='append')\n add_arg('-c', '--set-counters', dest='set-counters', action='append')\n\n # MATCH EXTENSIONS\n add_arg('-m', '--match', dest='match', action='append')\n ## addrtype\n add_arg('--src-type', dest='src-type', action='append')\n add_arg('--dst-type', dest='dst-type', action='append')\n add_arg('--limit-iface-in', dest='limit-iface-in', action='append')\n add_arg('--limit-iface-out', dest='limit-iface-out', action='append')\n ## ah\n add_arg('--ahspi', dest='ahspi', action='append')\n add_arg('--ahlen', dest='ahlen', action='append')\n add_arg('--ahres', dest='ahres', action='append')\n ## bpf\n add_arg('--bytecode', dest='bytecode', action='append')\n ## cgroup\n add_arg('--cgroup', dest='cgroup', action='append')\n ## cluster\n add_arg('--cluster-total-nodes',\n dest='cluster-total-nodes',\n action='append')\n add_arg('--cluster-local-node', dest='cluster-local-node', action='append')\n add_arg('--cluster-local-nodemask',\n dest='cluster-local-nodemask',\n action='append')\n add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')\n add_arg('--h-length', dest='h-length', action='append')\n add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')\n add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')\n ## comment\n add_arg('--comment', dest='comment', action='append')\n ## connbytes\n add_arg('--connbytes', dest='connbytes', action='append')\n add_arg('--connbytes-dir', dest='connbytes-dir', action='append')\n add_arg('--connbytes-mode', dest='connbytes-mode', action='append')\n ## connlabel\n add_arg('--label', dest='label', action='append')\n ## connlimit\n add_arg('--connlimit-upto', dest='connlimit-upto', action='append')\n add_arg('--connlimit-above', dest='connlimit-above', action='append')\n add_arg('--connlimit-mask', dest='connlimit-mask', action='append')\n add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')\n add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')\n ## connmark\n add_arg('--mark', dest='mark', action='append')\n ## conntrack\n add_arg('--ctstate', dest='ctstate', action='append')\n add_arg('--ctproto', dest='ctproto', action='append')\n add_arg('--ctorigsrc', dest='ctorigsrc', action='append')\n add_arg('--ctorigdst', dest='ctorigdst', action='append')\n add_arg('--ctreplsrc', dest='ctreplsrc', action='append')\n add_arg('--ctrepldst', dest='ctrepldst', action='append')\n add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')\n add_arg('--ctorigdstport', dest='ctorigdstport', action='append')\n add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')\n add_arg('--ctrepldstport', dest='ctrepldstport', action='append')\n add_arg('--ctstatus', dest='ctstatus', action='append')\n add_arg('--ctexpire', dest='ctexpire', action='append')\n add_arg('--ctdir', dest='ctdir', action='append')\n ## cpu\n add_arg('--cpu', dest='cpu', action='append')\n ## dccp\n add_arg('--sport', '--source-port', dest='source_port', action='append')\n add_arg('--dport',\n '--destination-port',\n dest='destination_port',\n action='append')\n add_arg('--dccp-types', dest='dccp-types', action='append')\n add_arg('--dccp-option', dest='dccp-option', action='append')\n ## devgroup\n add_arg('--src-group', dest='src-group', action='append')\n add_arg('--dst-group', dest='dst-group', action='append')\n ## dscp\n add_arg('--dscp', dest='dscp', action='append')\n add_arg('--dscp-class', dest='dscp-class', action='append')\n ## dst\n add_arg('--dst-len', dest='dst-len', action='append')\n add_arg('--dst-opts', dest='dst-opts', action='append')\n ## ecn\n add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')\n add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')\n add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')\n ## esp\n add_arg('--espspi', dest='espspi', action='append')\n ## frag\n add_arg('--fragid', dest='fragid', action='append')\n add_arg('--fraglen', dest='fraglen', action='append')\n add_arg('--fragres', dest='fragres', action='append')\n add_arg('--fragfirst', dest='fragfirst', action='append')\n add_arg('--fragmore', dest='fragmore', action='append')\n add_arg('--fraglast', dest='fraglast', action='append')\n ## hashlimit\n add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')\n add_arg('--hashlimit-above', dest='hashlimit-above', action='append')\n add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')\n add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')\n add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')\n add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')\n add_arg('--hashlimit-name', dest='hashlimit-name', action='append')\n add_arg('--hashlimit-htable-size',\n dest='hashlimit-htable-size',\n action='append')\n add_arg('--hashlimit-htable-max',\n dest='hashlimit-htable-max',\n action='append')\n add_arg('--hashlimit-htable-expire',\n dest='hashlimit-htable-expire',\n action='append')\n add_arg('--hashlimit-htable-gcinterval',\n dest='hashlimit-htable-gcinterval',\n action='append')\n ## hbh\n add_arg('--hbh-len', dest='hbh-len', action='append')\n add_arg('--hbh-opts', dest='hbh-opts', action='append')\n ## helper\n add_arg('--helper', dest='helper', action='append')\n ## hl\n add_arg('--hl-eq', dest='hl-eq', action='append')\n add_arg('--hl-lt', dest='hl-lt', action='append')\n add_arg('--hl-gt', dest='hl-gt', action='append')\n ## icmp\n add_arg('--icmp-type', dest='icmp-type', action='append')\n ## icmp6\n add_arg('--icmpv6-type', dest='icmpv6-type', action='append')\n ## iprange\n add_arg('--src-range', dest='src-range', action='append')\n add_arg('--dst-range', dest='dst-range', action='append')\n ## ipv6header\n add_arg('--soft', dest='soft', action='append')\n add_arg('--header', dest='header', action='append')\n ## ipvs\n add_arg('--ipvs', dest='ipvs', action='append')\n add_arg('--vproto', dest='vproto', action='append')\n add_arg('--vaddr', dest='vaddr', action='append')\n add_arg('--vport', dest='vport', action='append')\n add_arg('--vdir', dest='vdir', action='append')\n add_arg('--vmethod', dest='vmethod', action='append')\n add_arg('--vportctl', dest='vportctl', action='append')\n ## length\n add_arg('--length', dest='length', action='append')\n ## limit\n add_arg('--limit', dest='limit', action='append')\n add_arg('--limit-burst', dest='limit-burst', action='append')\n ## mac\n add_arg('--mac-source', dest='mac-source', action='append')\n ## mh\n add_arg('--mh-type', dest='mh-type', action='append')\n ## multiport\n add_arg('--sports', '--source-ports', dest='source-ports', action='append')\n add_arg('--dports',\n '--destination-ports',\n dest='destination-ports',\n action='append')\n add_arg('--ports', dest='ports', action='append')\n ## nfacct\n add_arg('--nfacct-name', dest='nfacct-name', action='append')\n ## osf\n add_arg('--genre', dest='genre', action='append')\n add_arg('--ttl', dest='ttl', action='append')\n add_arg('--log', dest='log', action='append')\n ## owner\n add_arg('--uid-owner', dest='uid-owner', action='append')\n add_arg('--gid-owner', dest='gid-owner', action='append')\n add_arg('--socket-exists', dest='socket-exists', action='append')\n ## physdev\n add_arg('--physdev-in', dest='physdev-in', action='append')\n add_arg('--physdev-out', dest='physdev-out', action='append')\n add_arg('--physdev-is-in', dest='physdev-is-in', action='append')\n add_arg('--physdev-is-out', dest='physdev-is-out', action='append')\n add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')\n ## pkttype\n add_arg('--pkt-type', dest='pkt-type', action='append')\n ## policy\n add_arg('--dir', dest='dir', action='append')\n add_arg('--pol', dest='pol', action='append')\n add_arg('--strict', dest='strict', action='append')\n add_arg('--reqid', dest='reqid', action='append')\n add_arg('--spi', dest='spi', action='append')\n add_arg('--proto', dest='proto', action='append')\n add_arg('--mode', dest='mode', action='append')\n add_arg('--tunnel-src', dest='tunnel-src', action='append')\n add_arg('--tunnel-dst', dest='tunnel-dst', action='append')\n add_arg('--next', dest='next', action='append')\n ## quota\n add_arg('--quota', dest='quota', action='append')\n ## rateest\n add_arg('--rateest', dest='rateest', action='append')\n add_arg('--rateest1', dest='rateest1', action='append')\n add_arg('--rateest2', dest='rateest2', action='append')\n add_arg('--rateest-delta', dest='rateest-delta', action='append')\n add_arg('--rateest-bps', dest='rateest-bps', action='append')\n add_arg('--rateest-bps1', dest='rateest-bps1', action='append')\n add_arg('--rateest-bps2', dest='rateest-bps2', action='append')\n add_arg('--rateest-pps', dest='rateest-pps', action='append')\n add_arg('--rateest-pps1', dest='rateest-pps1', action='append')\n add_arg('--rateest-pps2', dest='rateest-pps2', action='append')\n add_arg('--rateest-lt', dest='rateest-lt', action='append')\n add_arg('--rateest-gt', dest='rateest-gt', action='append')\n add_arg('--rateest-eq', dest='rateest-eq', action='append')\n add_arg('--rateest-name', dest='rateest-name', action='append')\n add_arg('--rateest-interval', dest='rateest-interval', action='append')\n add_arg('--rateest-ewma', dest='rateest-ewma', action='append')\n ## realm\n add_arg('--realm', dest='realm', action='append')\n ## recent\n add_arg('--name', dest='name', action='append')\n add_arg('--set', dest='set', action='append')\n add_arg('--rsource', dest='rsource', action='append')\n add_arg('--rdest', dest='rdest', action='append')\n add_arg('--mask', dest='mask', action='append')\n add_arg('--rcheck', dest='rcheck', action='append')\n add_arg('--update', dest='update', action='append')\n add_arg('--remove', dest='remove', action='append')\n add_arg('--seconds', dest='seconds', action='append')\n add_arg('--reap', dest='reap', action='append')\n add_arg('--hitcount', dest='hitcount', action='append')\n add_arg('--rttl', dest='rttl', action='append')\n ## rpfilter\n add_arg('--loose', dest='loose', action='append')\n add_arg('--validmark', dest='validmark', action='append')\n add_arg('--accept-local', dest='accept-local', action='append')\n add_arg('--invert', dest='invert', action='append')\n ## rt\n add_arg('--rt-type', dest='rt-type', action='append')\n add_arg('--rt-segsleft', dest='rt-segsleft', action='append')\n add_arg('--rt-len', dest='rt-len', action='append')\n add_arg('--rt-0-res', dest='rt-0-res', action='append')\n add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')\n add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')\n ## sctp\n add_arg('--chunk-types', dest='chunk-types', action='append')\n ## set\n add_arg('--match-set', dest='match-set', action='append')\n add_arg('--return-nomatch', dest='return-nomatch', action='append')\n add_arg('--update-counters', dest='update-counters', action='append')\n add_arg('--update-subcounters', dest='update-subcounters', action='append')\n add_arg('--packets-eq', dest='packets-eq', action='append')\n add_arg('--packets-lt', dest='packets-lt', action='append')\n add_arg('--packets-gt', dest='packets-gt', action='append')\n add_arg('--bytes-eq', dest='bytes-eq', action='append')\n add_arg('--bytes-lt', dest='bytes-lt', action='append')\n add_arg('--bytes-gt', dest='bytes-gt', action='append')\n ## socket\n add_arg('--transparent', dest='transparent', action='append')\n add_arg('--nowildcard', dest='nowildcard', action='append')\n ## state\n add_arg('--state', dest='state', action='append')\n ## statistic\n add_arg('--probability', dest='probability', action='append')\n add_arg('--every', dest='every', action='append')\n add_arg('--packet', dest='packet', action='append')\n ## string\n add_arg('--algo', dest='algo', action='append')\n add_arg('--from', dest='from', action='append')\n add_arg('--to', dest='to', action='append')\n add_arg('--string', dest='string', action='append')\n add_arg('--hex-string', dest='hex-string', action='append')\n ## tcp\n add_arg('--tcp-flags', dest='tcp-flags', action='append')\n add_arg('--syn', dest='syn', action='append')\n add_arg('--tcp-option', dest='tcp-option', action='append')\n ## tcpmss\n add_arg('--mss', dest='mss', action='append')\n ## time\n add_arg('--datestart', dest='datestart', action='append')\n add_arg('--datestop', dest='datestop', action='append')\n add_arg('--timestart', dest='timestart', action='append')\n add_arg('--timestop', dest='timestop', action='append')\n add_arg('--monthdays', dest='monthdays', action='append')\n add_arg('--weekdays', dest='weekdays', action='append')\n add_arg('--contiguous', dest='contiguous', action='append')\n add_arg('--kerneltz', dest='kerneltz', action='append')\n add_arg('--utc', dest='utc', action='append')\n add_arg('--localtz', dest='localtz', action='append')\n ## tos\n add_arg('--tos', dest='tos', action='append')\n ## ttl\n add_arg('--ttl-eq', dest='ttl-eq', action='append')\n add_arg('--ttl-gt', dest='ttl-gt', action='append')\n add_arg('--ttl-lt', dest='ttl-lt', action='append')\n ## u32\n add_arg('--u32', dest='u32', action='append')\n\n # Xtables-addons matches\n ## condition\n add_arg('--condition', dest='condition', action='append')\n ## dhcpmac\n add_arg('--mac', dest='mac', action='append')\n ## fuzzy\n add_arg('--lower-limit', dest='lower-limit', action='append')\n add_arg('--upper-limit', dest='upper-limit', action='append')\n ## geoip\n add_arg('--src-cc',\n '--source-country',\n dest='source-country',\n action='append')\n add_arg('--dst-cc',\n '--destination-country',\n dest='destination-country',\n action='append')\n ## gradm\n add_arg('--enabled', dest='enabled', action='append')\n add_arg('--disabled', dest='disabled', action='append')\n ## iface\n add_arg('--iface', dest='iface', action='append')\n add_arg('--dev-in', dest='dev-in', action='append')\n add_arg('--dev-out', dest='dev-out', action='append')\n add_arg('--up', dest='up', action='append')\n add_arg('--down', dest='down', action='append')\n add_arg('--broadcast', dest='broadcast', action='append')\n add_arg('--loopback', dest='loopback', action='append')\n add_arg('--pointtopoint', dest='pointtopoint', action='append')\n add_arg('--running', dest='running', action='append')\n add_arg('--noarp', dest='noarp', action='append')\n add_arg('--arp', dest='arp', action='append')\n add_arg('--promisc', dest='promisc', action='append')\n add_arg('--multicast', dest='multicast', action='append')\n add_arg('--dynamic', dest='dynamic', action='append')\n add_arg('--lower-up', dest='lower-up', action='append')\n add_arg('--dormant', dest='dormant', action='append')\n ## ipp2p\n add_arg('--edk', dest='edk', action='append')\n add_arg('--kazaa', dest='kazaa', action='append')\n add_arg('--gnu', dest='gnu', action='append')\n add_arg('--dc', dest='dc', action='append')\n add_arg('--bit', dest='bit', action='append')\n add_arg('--apple', dest='apple', action='append')\n add_arg('--soul', dest='soul', action='append')\n add_arg('--winmx', dest='winmx', action='append')\n add_arg('--ares', dest='ares', action='append')\n add_arg('--debug', dest='debug', action='append')\n ## ipv4options\n add_arg('--flags', dest='flags', action='append')\n add_arg('--any', dest='any', action='append')\n ## length2\n add_arg('--layer3', dest='layer3', action='append')\n add_arg('--layer4', dest='layer4', action='append')\n add_arg('--layer5', dest='layer5', action='append')\n ## lscan\n add_arg('--stealth', dest='stealth', action='append')\n add_arg('--synscan', dest='synscan', action='append')\n add_arg('--cnscan', dest='cnscan', action='append')\n add_arg('--grscan', dest='grscan', action='append')\n ## psd\n add_arg('--psd-weight-threshold',\n dest='psd-weight-threshold',\n action='append')\n add_arg('--psd-delay-threshold',\n dest='psd-delay-threshold',\n action='append')\n add_arg('--psd-lo-ports-weight',\n dest='psd-lo-ports-weight',\n action='append')\n add_arg('--psd-hi-ports-weight',\n dest='psd-hi-ports-weight',\n action='append')\n ## quota2\n add_arg('--grow', dest='grow', action='append')\n add_arg('--no-change', dest='no-change', action='append')\n add_arg('--packets', dest='packets', action='append')\n ## pknock\n add_arg('--knockports', dest='knockports', action='append')\n add_arg('--time', dest='time', action='append')\n add_arg('--autoclose', dest='autoclose', action='append')\n add_arg('--checkip', dest='checkip', action='append')\n\n # TARGET EXTENSIONS\n ## AUDIT\n add_arg('--type', dest='type', action='append')\n ## CHECKSUM\n add_arg('--checksum-fill', dest='checksum-fill', action='append')\n ## CLASSIFY\n add_arg('--set-class', dest='set-class', action='append')\n ## CLUSTERIP\n add_arg('--new', dest='new', action='append')\n add_arg('--hashmode', dest='hashmode', action='append')\n add_arg('--clustermac', dest='clustermac', action='append')\n add_arg('--total-nodes', dest='total-nodes', action='append')\n add_arg('--local-node', dest='local-node', action='append')\n add_arg('--hash-init', dest='hash-init', action='append')\n ## CONNMARK\n add_arg('--set-xmark', dest='set-xmark', action='append')\n add_arg('--save-mark', dest='save-mark', action='append')\n add_arg('--restore-mark', dest='restore-mark', action='append')\n add_arg('--and-mark', dest='and-mark', action='append')\n add_arg('--or-mark', dest='or-mark', action='append')\n add_arg('--xor-mark', dest='xor-mark', action='append')\n add_arg('--set-mark', dest='set-mark', action='append')\n add_arg('--nfmask', dest='nfmask', action='append')\n add_arg('--ctmask', dest='ctmask', action='append')\n ## CONNSECMARK\n add_arg('--save', dest='save', action='append')\n add_arg('--restore', dest='restore', action='append')\n ## CT\n add_arg('--notrack', dest='notrack', action='append')\n add_arg('--ctevents', dest='ctevents', action='append')\n add_arg('--expevents', dest='expevents', action='append')\n add_arg('--zone', dest='zone', action='append')\n add_arg('--timeout', dest='timeout', action='append')\n ## DNAT\n add_arg('--to-destination', dest='to-destination', action='append')\n add_arg('--random', dest='random', action='append')\n add_arg('--persistent', dest='persistent', action='append')\n ## DNPT\n add_arg('--src-pfx', dest='src-pfx', action='append')\n add_arg('--dst-pfx', dest='dst-pfx', action='append')\n ## DSCP\n add_arg('--set-dscp', dest='set-dscp', action='append')\n add_arg('--set-dscp-class', dest='set-dscp-class', action='append')\n ## ECN\n add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')\n ## HL\n add_arg('--hl-set', dest='hl-set', action='append')\n add_arg('--hl-dec', dest='hl-dec', action='append')\n add_arg('--hl-inc', dest='hl-inc', action='append')\n ## HMARK\n add_arg('--hmark-tuple', dest='hmark-tuple', action='append')\n add_arg('--hmark-mod', dest='hmark-mod', action='append')\n add_arg('--hmark-offset', dest='hmark-offset', action='append')\n add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')\n add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')\n add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')\n add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')\n add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')\n add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')\n add_arg('--hmark-rnd', dest='hmark-rnd', action='append')\n ## LED\n add_arg('--led-trigger-id', dest='led-trigger-id', action='append')\n add_arg('--led-delay', dest='led-delay', action='append')\n add_arg('--led-always-blink', dest='led-always-blink', action='append')\n ## LOG\n add_arg('--log-level', dest='log-level', action='append')\n add_arg('--log-prefix', dest='log-prefix', action='append')\n add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')\n add_arg('--log-tcp-options', dest='log-tcp-options', action='append')\n add_arg('--log-ip-options', dest='log-ip-options', action='append')\n add_arg('--log-uid', dest='log-uid', action='append')\n ## MASQUERADE\n add_arg('--to-ports', dest='to-ports', action='append')\n ## NFLOG\n add_arg('--nflog-group', dest='nflog-group', action='append')\n add_arg('--nflog-prefix', dest='nflog-prefix', action='append')\n add_arg('--nflog-range', dest='nflog-range', action='append')\n add_arg('--nflog-threshold', dest='nflog-threshold', action='append')\n ## NFQUEUE\n add_arg('--queue-num', dest='queue-num', action='append')\n add_arg('--queue-balance', dest='queue-balance', action='append')\n add_arg('--queue-bypass', dest='queue-bypass', action='append')\n add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')\n ## RATEEST\n add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')\n ## REJECT\n add_arg('--reject-with', dest='reject-with', action='append')\n ## SAME\n add_arg('--nodst', dest='nodst', action='append')\n ## SECMARK\n add_arg('--selctx', dest='selctx', action='append')\n ## SET\n add_arg('--add-set', dest='add-set', action='append')\n add_arg('--del-set', dest='del-set', action='append')\n add_arg('--exist', dest='exist', action='append')\n ## SNAT\n add_arg('--to-source', dest='to-source', action='append')\n ## TCPMSS\n add_arg('--set-mss', dest='set-mss', action='append')\n add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')\n ## TCPOPTSTRIP\n add_arg('--strip-options', dest='strip-options', action='append')\n ## TEE\n add_arg('--gateway', dest='gateway', action='append')\n ## TOS\n add_arg('--set-tos', dest='set-tos', action='append')\n add_arg('--and-tos', dest='and-tos', action='append')\n add_arg('--or-tos', dest='or-tos', action='append')\n add_arg('--xor-tos', dest='xor-tos', action='append')\n ## TPROXY\n add_arg('--on-port', dest='on-port', action='append')\n add_arg('--on-ip', dest='on-ip', action='append')\n add_arg('--tproxy-mark', dest='tproxy-mark', action='append')\n ## TTL\n add_arg('--ttl-set', dest='ttl-set', action='append')\n add_arg('--ttl-dec', dest='ttl-dec', action='append')\n add_arg('--ttl-inc', dest='ttl-inc', action='append')\n ## ULOG\n add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')\n add_arg('--ulog-prefix', dest='ulog-prefix', action='append')\n add_arg('--ulog-cprange', dest='ulog-cprange', action='append')\n add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')\n\n # Xtables-addons targets\n ## ACCOUNT\n add_arg('--addr', dest='addr', action='append')\n add_arg('--tname', dest='tname', action='append')\n ## CHAOS\n add_arg('--delude', dest='delude', action='append')\n add_arg('--tarpit', dest='tarpit', action='append')\n ## DHCPMAC\n add_arg('--set-mac', dest='set-mac', action='append')\n ## DNETMAP\n add_arg('--prefix', dest='prefix', action='append')\n add_arg('--reuse', dest='reuse', action='append')\n add_arg('--static', dest='static', action='append')\n ## IPMARK\n add_arg('--and-mask', dest='and-mask', action='append')\n add_arg('--or-mask', dest='or-mask', action='append')\n add_arg('--shift', dest='shift', action='append')\n ## TARPIT\n add_arg('--honeypot', dest='honeypot', action='append')\n add_arg('--reset', dest='reset', action='append')\n\n return parser\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def _conf(family='ipv4'):\n '''\n Some distros have a specific location for config files\n '''\n if __grains__['os_family'] == 'RedHat':\n if family == 'ipv6':\n return '/etc/sysconfig/ip6tables'\n else:\n return '/etc/sysconfig/iptables'\n elif __grains__['os_family'] == 'Arch':\n if family == 'ipv6':\n return '/etc/iptables/ip6tables.rules'\n else:\n return '/etc/iptables/iptables.rules'\n elif __grains__['os_family'] == 'Debian':\n if family == 'ipv6':\n return '/etc/iptables/rules.v6'\n else:\n return '/etc/iptables/rules.v4'\n elif __grains__['os_family'] == 'Gentoo':\n if family == 'ipv6':\n return '/var/lib/ip6tables/rules-save'\n else:\n return '/var/lib/iptables/rules-save'\n elif __grains__['os_family'] == 'Suse':\n # SuSE does not seem to use separate files for IPv4 and IPv6\n return '/etc/sysconfig/scripts/SuSEfirewall2-custom'\n elif __grains__['os_family'] == 'Void':\n if family == 'ipv4':\n return '/etc/iptables/iptables.rules'\n else:\n return '/etc/iptables/ip6tables.rules'\n elif __grains__['os'] == 'Alpine':\n if family == 'ipv6':\n return '/etc/iptables/rules6-save'\n else:\n return '/etc/iptables/rules-save'\n else:\n raise SaltException('Saving iptables to file is not' +\n ' supported on {0}.'.format(__grains__['os']) +\n ' Please file an issue with SaltStack')\n",
"def _iptables_cmd(family='ipv4'):\n '''\n Return correct command based on the family, e.g. ipv4 or ipv6\n '''\n if family == 'ipv6':\n return salt.utils.path.which('ip6tables')\n else:\n return salt.utils.path.which('iptables')\n"
] |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
saltstack/salt
|
salt/modules/iptables.py
|
_parser
|
python
|
def _parser():
'''
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
'''
add_arg = None
if sys.version.startswith('2.6'):
import optparse
parser = optparse.OptionParser()
add_arg = parser.add_option
else:
import argparse # pylint: disable=minimum-python-version
parser = argparse.ArgumentParser()
add_arg = parser.add_argument
# COMMANDS
add_arg('-A', '--append', dest='append', action='append')
add_arg('-D', '--delete', dest='delete', action='append')
add_arg('-I', '--insert', dest='insert', action='append')
add_arg('-R', '--replace', dest='replace', action='append')
add_arg('-L', '--list', dest='list', action='append')
add_arg('-F', '--flush', dest='flush', action='append')
add_arg('-Z', '--zero', dest='zero', action='append')
add_arg('-N', '--new-chain', dest='new-chain', action='append')
add_arg('-X', '--delete-chain', dest='delete-chain', action='append')
add_arg('-P', '--policy', dest='policy', action='append')
add_arg('-E', '--rename-chain', dest='rename-chain', action='append')
# PARAMETERS
add_arg('-p', '--protocol', dest='protocol', action='append')
add_arg('-s', '--source', dest='source', action='append')
add_arg('-d', '--destination', dest='destination', action='append')
add_arg('-j', '--jump', dest='jump', action='append')
add_arg('-g', '--goto', dest='goto', action='append')
add_arg('-i', '--in-interface', dest='in-interface', action='append')
add_arg('-o', '--out-interface', dest='out-interface', action='append')
add_arg('-f', '--fragment', dest='fragment', action='append')
add_arg('-c', '--set-counters', dest='set-counters', action='append')
# MATCH EXTENSIONS
add_arg('-m', '--match', dest='match', action='append')
## addrtype
add_arg('--src-type', dest='src-type', action='append')
add_arg('--dst-type', dest='dst-type', action='append')
add_arg('--limit-iface-in', dest='limit-iface-in', action='append')
add_arg('--limit-iface-out', dest='limit-iface-out', action='append')
## ah
add_arg('--ahspi', dest='ahspi', action='append')
add_arg('--ahlen', dest='ahlen', action='append')
add_arg('--ahres', dest='ahres', action='append')
## bpf
add_arg('--bytecode', dest='bytecode', action='append')
## cgroup
add_arg('--cgroup', dest='cgroup', action='append')
## cluster
add_arg('--cluster-total-nodes',
dest='cluster-total-nodes',
action='append')
add_arg('--cluster-local-node', dest='cluster-local-node', action='append')
add_arg('--cluster-local-nodemask',
dest='cluster-local-nodemask',
action='append')
add_arg('--cluster-hash-seed', dest='cluster-hash-seed', action='append')
add_arg('--h-length', dest='h-length', action='append')
add_arg('--mangle-mac-s', dest='mangle-mac-s', action='append')
add_arg('--mangle-mac-d', dest='mangle-mac-d', action='append')
## comment
add_arg('--comment', dest='comment', action='append')
## connbytes
add_arg('--connbytes', dest='connbytes', action='append')
add_arg('--connbytes-dir', dest='connbytes-dir', action='append')
add_arg('--connbytes-mode', dest='connbytes-mode', action='append')
## connlabel
add_arg('--label', dest='label', action='append')
## connlimit
add_arg('--connlimit-upto', dest='connlimit-upto', action='append')
add_arg('--connlimit-above', dest='connlimit-above', action='append')
add_arg('--connlimit-mask', dest='connlimit-mask', action='append')
add_arg('--connlimit-saddr', dest='connlimit-saddr', action='append')
add_arg('--connlimit-daddr', dest='connlimit-daddr', action='append')
## connmark
add_arg('--mark', dest='mark', action='append')
## conntrack
add_arg('--ctstate', dest='ctstate', action='append')
add_arg('--ctproto', dest='ctproto', action='append')
add_arg('--ctorigsrc', dest='ctorigsrc', action='append')
add_arg('--ctorigdst', dest='ctorigdst', action='append')
add_arg('--ctreplsrc', dest='ctreplsrc', action='append')
add_arg('--ctrepldst', dest='ctrepldst', action='append')
add_arg('--ctorigsrcport', dest='ctorigsrcport', action='append')
add_arg('--ctorigdstport', dest='ctorigdstport', action='append')
add_arg('--ctreplsrcport', dest='ctreplsrcport', action='append')
add_arg('--ctrepldstport', dest='ctrepldstport', action='append')
add_arg('--ctstatus', dest='ctstatus', action='append')
add_arg('--ctexpire', dest='ctexpire', action='append')
add_arg('--ctdir', dest='ctdir', action='append')
## cpu
add_arg('--cpu', dest='cpu', action='append')
## dccp
add_arg('--sport', '--source-port', dest='source_port', action='append')
add_arg('--dport',
'--destination-port',
dest='destination_port',
action='append')
add_arg('--dccp-types', dest='dccp-types', action='append')
add_arg('--dccp-option', dest='dccp-option', action='append')
## devgroup
add_arg('--src-group', dest='src-group', action='append')
add_arg('--dst-group', dest='dst-group', action='append')
## dscp
add_arg('--dscp', dest='dscp', action='append')
add_arg('--dscp-class', dest='dscp-class', action='append')
## dst
add_arg('--dst-len', dest='dst-len', action='append')
add_arg('--dst-opts', dest='dst-opts', action='append')
## ecn
add_arg('--ecn-tcp-cwr', dest='ecn-tcp-cwr', action='append')
add_arg('--ecn-tcp-ece', dest='ecn-tcp-ece', action='append')
add_arg('--ecn-ip-ect', dest='ecn-ip-ect', action='append')
## esp
add_arg('--espspi', dest='espspi', action='append')
## frag
add_arg('--fragid', dest='fragid', action='append')
add_arg('--fraglen', dest='fraglen', action='append')
add_arg('--fragres', dest='fragres', action='append')
add_arg('--fragfirst', dest='fragfirst', action='append')
add_arg('--fragmore', dest='fragmore', action='append')
add_arg('--fraglast', dest='fraglast', action='append')
## hashlimit
add_arg('--hashlimit-upto', dest='hashlimit-upto', action='append')
add_arg('--hashlimit-above', dest='hashlimit-above', action='append')
add_arg('--hashlimit-burst', dest='hashlimit-burst', action='append')
add_arg('--hashlimit-mode', dest='hashlimit-mode', action='append')
add_arg('--hashlimit-srcmask', dest='hashlimit-srcmask', action='append')
add_arg('--hashlimit-dstmask', dest='hashlimit-dstmask', action='append')
add_arg('--hashlimit-name', dest='hashlimit-name', action='append')
add_arg('--hashlimit-htable-size',
dest='hashlimit-htable-size',
action='append')
add_arg('--hashlimit-htable-max',
dest='hashlimit-htable-max',
action='append')
add_arg('--hashlimit-htable-expire',
dest='hashlimit-htable-expire',
action='append')
add_arg('--hashlimit-htable-gcinterval',
dest='hashlimit-htable-gcinterval',
action='append')
## hbh
add_arg('--hbh-len', dest='hbh-len', action='append')
add_arg('--hbh-opts', dest='hbh-opts', action='append')
## helper
add_arg('--helper', dest='helper', action='append')
## hl
add_arg('--hl-eq', dest='hl-eq', action='append')
add_arg('--hl-lt', dest='hl-lt', action='append')
add_arg('--hl-gt', dest='hl-gt', action='append')
## icmp
add_arg('--icmp-type', dest='icmp-type', action='append')
## icmp6
add_arg('--icmpv6-type', dest='icmpv6-type', action='append')
## iprange
add_arg('--src-range', dest='src-range', action='append')
add_arg('--dst-range', dest='dst-range', action='append')
## ipv6header
add_arg('--soft', dest='soft', action='append')
add_arg('--header', dest='header', action='append')
## ipvs
add_arg('--ipvs', dest='ipvs', action='append')
add_arg('--vproto', dest='vproto', action='append')
add_arg('--vaddr', dest='vaddr', action='append')
add_arg('--vport', dest='vport', action='append')
add_arg('--vdir', dest='vdir', action='append')
add_arg('--vmethod', dest='vmethod', action='append')
add_arg('--vportctl', dest='vportctl', action='append')
## length
add_arg('--length', dest='length', action='append')
## limit
add_arg('--limit', dest='limit', action='append')
add_arg('--limit-burst', dest='limit-burst', action='append')
## mac
add_arg('--mac-source', dest='mac-source', action='append')
## mh
add_arg('--mh-type', dest='mh-type', action='append')
## multiport
add_arg('--sports', '--source-ports', dest='source-ports', action='append')
add_arg('--dports',
'--destination-ports',
dest='destination-ports',
action='append')
add_arg('--ports', dest='ports', action='append')
## nfacct
add_arg('--nfacct-name', dest='nfacct-name', action='append')
## osf
add_arg('--genre', dest='genre', action='append')
add_arg('--ttl', dest='ttl', action='append')
add_arg('--log', dest='log', action='append')
## owner
add_arg('--uid-owner', dest='uid-owner', action='append')
add_arg('--gid-owner', dest='gid-owner', action='append')
add_arg('--socket-exists', dest='socket-exists', action='append')
## physdev
add_arg('--physdev-in', dest='physdev-in', action='append')
add_arg('--physdev-out', dest='physdev-out', action='append')
add_arg('--physdev-is-in', dest='physdev-is-in', action='append')
add_arg('--physdev-is-out', dest='physdev-is-out', action='append')
add_arg('--physdev-is-bridged', dest='physdev-is-bridged', action='append')
## pkttype
add_arg('--pkt-type', dest='pkt-type', action='append')
## policy
add_arg('--dir', dest='dir', action='append')
add_arg('--pol', dest='pol', action='append')
add_arg('--strict', dest='strict', action='append')
add_arg('--reqid', dest='reqid', action='append')
add_arg('--spi', dest='spi', action='append')
add_arg('--proto', dest='proto', action='append')
add_arg('--mode', dest='mode', action='append')
add_arg('--tunnel-src', dest='tunnel-src', action='append')
add_arg('--tunnel-dst', dest='tunnel-dst', action='append')
add_arg('--next', dest='next', action='append')
## quota
add_arg('--quota', dest='quota', action='append')
## rateest
add_arg('--rateest', dest='rateest', action='append')
add_arg('--rateest1', dest='rateest1', action='append')
add_arg('--rateest2', dest='rateest2', action='append')
add_arg('--rateest-delta', dest='rateest-delta', action='append')
add_arg('--rateest-bps', dest='rateest-bps', action='append')
add_arg('--rateest-bps1', dest='rateest-bps1', action='append')
add_arg('--rateest-bps2', dest='rateest-bps2', action='append')
add_arg('--rateest-pps', dest='rateest-pps', action='append')
add_arg('--rateest-pps1', dest='rateest-pps1', action='append')
add_arg('--rateest-pps2', dest='rateest-pps2', action='append')
add_arg('--rateest-lt', dest='rateest-lt', action='append')
add_arg('--rateest-gt', dest='rateest-gt', action='append')
add_arg('--rateest-eq', dest='rateest-eq', action='append')
add_arg('--rateest-name', dest='rateest-name', action='append')
add_arg('--rateest-interval', dest='rateest-interval', action='append')
add_arg('--rateest-ewma', dest='rateest-ewma', action='append')
## realm
add_arg('--realm', dest='realm', action='append')
## recent
add_arg('--name', dest='name', action='append')
add_arg('--set', dest='set', action='append')
add_arg('--rsource', dest='rsource', action='append')
add_arg('--rdest', dest='rdest', action='append')
add_arg('--mask', dest='mask', action='append')
add_arg('--rcheck', dest='rcheck', action='append')
add_arg('--update', dest='update', action='append')
add_arg('--remove', dest='remove', action='append')
add_arg('--seconds', dest='seconds', action='append')
add_arg('--reap', dest='reap', action='append')
add_arg('--hitcount', dest='hitcount', action='append')
add_arg('--rttl', dest='rttl', action='append')
## rpfilter
add_arg('--loose', dest='loose', action='append')
add_arg('--validmark', dest='validmark', action='append')
add_arg('--accept-local', dest='accept-local', action='append')
add_arg('--invert', dest='invert', action='append')
## rt
add_arg('--rt-type', dest='rt-type', action='append')
add_arg('--rt-segsleft', dest='rt-segsleft', action='append')
add_arg('--rt-len', dest='rt-len', action='append')
add_arg('--rt-0-res', dest='rt-0-res', action='append')
add_arg('--rt-0-addrs', dest='rt-0-addrs', action='append')
add_arg('--rt-0-not-strict', dest='rt-0-not-strict', action='append')
## sctp
add_arg('--chunk-types', dest='chunk-types', action='append')
## set
add_arg('--match-set', dest='match-set', action='append')
add_arg('--return-nomatch', dest='return-nomatch', action='append')
add_arg('--update-counters', dest='update-counters', action='append')
add_arg('--update-subcounters', dest='update-subcounters', action='append')
add_arg('--packets-eq', dest='packets-eq', action='append')
add_arg('--packets-lt', dest='packets-lt', action='append')
add_arg('--packets-gt', dest='packets-gt', action='append')
add_arg('--bytes-eq', dest='bytes-eq', action='append')
add_arg('--bytes-lt', dest='bytes-lt', action='append')
add_arg('--bytes-gt', dest='bytes-gt', action='append')
## socket
add_arg('--transparent', dest='transparent', action='append')
add_arg('--nowildcard', dest='nowildcard', action='append')
## state
add_arg('--state', dest='state', action='append')
## statistic
add_arg('--probability', dest='probability', action='append')
add_arg('--every', dest='every', action='append')
add_arg('--packet', dest='packet', action='append')
## string
add_arg('--algo', dest='algo', action='append')
add_arg('--from', dest='from', action='append')
add_arg('--to', dest='to', action='append')
add_arg('--string', dest='string', action='append')
add_arg('--hex-string', dest='hex-string', action='append')
## tcp
add_arg('--tcp-flags', dest='tcp-flags', action='append')
add_arg('--syn', dest='syn', action='append')
add_arg('--tcp-option', dest='tcp-option', action='append')
## tcpmss
add_arg('--mss', dest='mss', action='append')
## time
add_arg('--datestart', dest='datestart', action='append')
add_arg('--datestop', dest='datestop', action='append')
add_arg('--timestart', dest='timestart', action='append')
add_arg('--timestop', dest='timestop', action='append')
add_arg('--monthdays', dest='monthdays', action='append')
add_arg('--weekdays', dest='weekdays', action='append')
add_arg('--contiguous', dest='contiguous', action='append')
add_arg('--kerneltz', dest='kerneltz', action='append')
add_arg('--utc', dest='utc', action='append')
add_arg('--localtz', dest='localtz', action='append')
## tos
add_arg('--tos', dest='tos', action='append')
## ttl
add_arg('--ttl-eq', dest='ttl-eq', action='append')
add_arg('--ttl-gt', dest='ttl-gt', action='append')
add_arg('--ttl-lt', dest='ttl-lt', action='append')
## u32
add_arg('--u32', dest='u32', action='append')
# Xtables-addons matches
## condition
add_arg('--condition', dest='condition', action='append')
## dhcpmac
add_arg('--mac', dest='mac', action='append')
## fuzzy
add_arg('--lower-limit', dest='lower-limit', action='append')
add_arg('--upper-limit', dest='upper-limit', action='append')
## geoip
add_arg('--src-cc',
'--source-country',
dest='source-country',
action='append')
add_arg('--dst-cc',
'--destination-country',
dest='destination-country',
action='append')
## gradm
add_arg('--enabled', dest='enabled', action='append')
add_arg('--disabled', dest='disabled', action='append')
## iface
add_arg('--iface', dest='iface', action='append')
add_arg('--dev-in', dest='dev-in', action='append')
add_arg('--dev-out', dest='dev-out', action='append')
add_arg('--up', dest='up', action='append')
add_arg('--down', dest='down', action='append')
add_arg('--broadcast', dest='broadcast', action='append')
add_arg('--loopback', dest='loopback', action='append')
add_arg('--pointtopoint', dest='pointtopoint', action='append')
add_arg('--running', dest='running', action='append')
add_arg('--noarp', dest='noarp', action='append')
add_arg('--arp', dest='arp', action='append')
add_arg('--promisc', dest='promisc', action='append')
add_arg('--multicast', dest='multicast', action='append')
add_arg('--dynamic', dest='dynamic', action='append')
add_arg('--lower-up', dest='lower-up', action='append')
add_arg('--dormant', dest='dormant', action='append')
## ipp2p
add_arg('--edk', dest='edk', action='append')
add_arg('--kazaa', dest='kazaa', action='append')
add_arg('--gnu', dest='gnu', action='append')
add_arg('--dc', dest='dc', action='append')
add_arg('--bit', dest='bit', action='append')
add_arg('--apple', dest='apple', action='append')
add_arg('--soul', dest='soul', action='append')
add_arg('--winmx', dest='winmx', action='append')
add_arg('--ares', dest='ares', action='append')
add_arg('--debug', dest='debug', action='append')
## ipv4options
add_arg('--flags', dest='flags', action='append')
add_arg('--any', dest='any', action='append')
## length2
add_arg('--layer3', dest='layer3', action='append')
add_arg('--layer4', dest='layer4', action='append')
add_arg('--layer5', dest='layer5', action='append')
## lscan
add_arg('--stealth', dest='stealth', action='append')
add_arg('--synscan', dest='synscan', action='append')
add_arg('--cnscan', dest='cnscan', action='append')
add_arg('--grscan', dest='grscan', action='append')
## psd
add_arg('--psd-weight-threshold',
dest='psd-weight-threshold',
action='append')
add_arg('--psd-delay-threshold',
dest='psd-delay-threshold',
action='append')
add_arg('--psd-lo-ports-weight',
dest='psd-lo-ports-weight',
action='append')
add_arg('--psd-hi-ports-weight',
dest='psd-hi-ports-weight',
action='append')
## quota2
add_arg('--grow', dest='grow', action='append')
add_arg('--no-change', dest='no-change', action='append')
add_arg('--packets', dest='packets', action='append')
## pknock
add_arg('--knockports', dest='knockports', action='append')
add_arg('--time', dest='time', action='append')
add_arg('--autoclose', dest='autoclose', action='append')
add_arg('--checkip', dest='checkip', action='append')
# TARGET EXTENSIONS
## AUDIT
add_arg('--type', dest='type', action='append')
## CHECKSUM
add_arg('--checksum-fill', dest='checksum-fill', action='append')
## CLASSIFY
add_arg('--set-class', dest='set-class', action='append')
## CLUSTERIP
add_arg('--new', dest='new', action='append')
add_arg('--hashmode', dest='hashmode', action='append')
add_arg('--clustermac', dest='clustermac', action='append')
add_arg('--total-nodes', dest='total-nodes', action='append')
add_arg('--local-node', dest='local-node', action='append')
add_arg('--hash-init', dest='hash-init', action='append')
## CONNMARK
add_arg('--set-xmark', dest='set-xmark', action='append')
add_arg('--save-mark', dest='save-mark', action='append')
add_arg('--restore-mark', dest='restore-mark', action='append')
add_arg('--and-mark', dest='and-mark', action='append')
add_arg('--or-mark', dest='or-mark', action='append')
add_arg('--xor-mark', dest='xor-mark', action='append')
add_arg('--set-mark', dest='set-mark', action='append')
add_arg('--nfmask', dest='nfmask', action='append')
add_arg('--ctmask', dest='ctmask', action='append')
## CONNSECMARK
add_arg('--save', dest='save', action='append')
add_arg('--restore', dest='restore', action='append')
## CT
add_arg('--notrack', dest='notrack', action='append')
add_arg('--ctevents', dest='ctevents', action='append')
add_arg('--expevents', dest='expevents', action='append')
add_arg('--zone', dest='zone', action='append')
add_arg('--timeout', dest='timeout', action='append')
## DNAT
add_arg('--to-destination', dest='to-destination', action='append')
add_arg('--random', dest='random', action='append')
add_arg('--persistent', dest='persistent', action='append')
## DNPT
add_arg('--src-pfx', dest='src-pfx', action='append')
add_arg('--dst-pfx', dest='dst-pfx', action='append')
## DSCP
add_arg('--set-dscp', dest='set-dscp', action='append')
add_arg('--set-dscp-class', dest='set-dscp-class', action='append')
## ECN
add_arg('--ecn-tcp-remove', dest='ecn-tcp-remove', action='append')
## HL
add_arg('--hl-set', dest='hl-set', action='append')
add_arg('--hl-dec', dest='hl-dec', action='append')
add_arg('--hl-inc', dest='hl-inc', action='append')
## HMARK
add_arg('--hmark-tuple', dest='hmark-tuple', action='append')
add_arg('--hmark-mod', dest='hmark-mod', action='append')
add_arg('--hmark-offset', dest='hmark-offset', action='append')
add_arg('--hmark-src-prefix', dest='hmark-src-prefix', action='append')
add_arg('--hmark-dst-prefix', dest='hmark-dst-prefix', action='append')
add_arg('--hmark-sport-mask', dest='hmark-sport-mask', action='append')
add_arg('--hmark-dport-mask', dest='hmark-dport-mask', action='append')
add_arg('--hmark-spi-mask', dest='hmark-spi-mask', action='append')
add_arg('--hmark-proto-mask', dest='hmark-proto-mask', action='append')
add_arg('--hmark-rnd', dest='hmark-rnd', action='append')
## LED
add_arg('--led-trigger-id', dest='led-trigger-id', action='append')
add_arg('--led-delay', dest='led-delay', action='append')
add_arg('--led-always-blink', dest='led-always-blink', action='append')
## LOG
add_arg('--log-level', dest='log-level', action='append')
add_arg('--log-prefix', dest='log-prefix', action='append')
add_arg('--log-tcp-sequence', dest='log-tcp-sequence', action='append')
add_arg('--log-tcp-options', dest='log-tcp-options', action='append')
add_arg('--log-ip-options', dest='log-ip-options', action='append')
add_arg('--log-uid', dest='log-uid', action='append')
## MASQUERADE
add_arg('--to-ports', dest='to-ports', action='append')
## NFLOG
add_arg('--nflog-group', dest='nflog-group', action='append')
add_arg('--nflog-prefix', dest='nflog-prefix', action='append')
add_arg('--nflog-range', dest='nflog-range', action='append')
add_arg('--nflog-threshold', dest='nflog-threshold', action='append')
## NFQUEUE
add_arg('--queue-num', dest='queue-num', action='append')
add_arg('--queue-balance', dest='queue-balance', action='append')
add_arg('--queue-bypass', dest='queue-bypass', action='append')
add_arg('--queue-cpu-fanout', dest='queue-cpu-fanout', action='append')
## RATEEST
add_arg('--rateest-ewmalog', dest='rateest-ewmalog', action='append')
## REJECT
add_arg('--reject-with', dest='reject-with', action='append')
## SAME
add_arg('--nodst', dest='nodst', action='append')
## SECMARK
add_arg('--selctx', dest='selctx', action='append')
## SET
add_arg('--add-set', dest='add-set', action='append')
add_arg('--del-set', dest='del-set', action='append')
add_arg('--exist', dest='exist', action='append')
## SNAT
add_arg('--to-source', dest='to-source', action='append')
## TCPMSS
add_arg('--set-mss', dest='set-mss', action='append')
add_arg('--clamp-mss-to-pmtu', dest='clamp-mss-to-pmtu', action='append')
## TCPOPTSTRIP
add_arg('--strip-options', dest='strip-options', action='append')
## TEE
add_arg('--gateway', dest='gateway', action='append')
## TOS
add_arg('--set-tos', dest='set-tos', action='append')
add_arg('--and-tos', dest='and-tos', action='append')
add_arg('--or-tos', dest='or-tos', action='append')
add_arg('--xor-tos', dest='xor-tos', action='append')
## TPROXY
add_arg('--on-port', dest='on-port', action='append')
add_arg('--on-ip', dest='on-ip', action='append')
add_arg('--tproxy-mark', dest='tproxy-mark', action='append')
## TTL
add_arg('--ttl-set', dest='ttl-set', action='append')
add_arg('--ttl-dec', dest='ttl-dec', action='append')
add_arg('--ttl-inc', dest='ttl-inc', action='append')
## ULOG
add_arg('--ulog-nlgroup', dest='ulog-nlgroup', action='append')
add_arg('--ulog-prefix', dest='ulog-prefix', action='append')
add_arg('--ulog-cprange', dest='ulog-cprange', action='append')
add_arg('--ulog-qthreshold', dest='ulog-qthreshold', action='append')
# Xtables-addons targets
## ACCOUNT
add_arg('--addr', dest='addr', action='append')
add_arg('--tname', dest='tname', action='append')
## CHAOS
add_arg('--delude', dest='delude', action='append')
add_arg('--tarpit', dest='tarpit', action='append')
## DHCPMAC
add_arg('--set-mac', dest='set-mac', action='append')
## DNETMAP
add_arg('--prefix', dest='prefix', action='append')
add_arg('--reuse', dest='reuse', action='append')
add_arg('--static', dest='static', action='append')
## IPMARK
add_arg('--and-mask', dest='and-mask', action='append')
add_arg('--or-mask', dest='or-mask', action='append')
add_arg('--shift', dest='shift', action='append')
## TARPIT
add_arg('--honeypot', dest='honeypot', action='append')
add_arg('--reset', dest='reset', action='append')
return parser
|
This function attempts to list all the options documented in the
iptables(8) and iptables-extensions(8) man pages. They will not all be
used by all parts of the module; use them intelligently and appropriately.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L1049-L1597
| null |
# -*- coding: utf-8 -*-
'''
Support for iptables
Configuration Options
---------------------
The following options can be set in the minion config, grains, pillar, or
master config. The configuration is read using :py:func:`config.get
<salt.modules.config.get>`.
- ``iptables.save_filters``: List of REGEX strings to FILTER OUT matching lines
This is useful for filtering out chains, rules, etc that you do not wish to
persist, such as ephemeral Docker rules.
The default is to not filter out anything.
.. code-block:: yaml
iptables.save_filters:
- "-j CATTLE_PREROUTING"
- "-j DOCKER"
- "-A POSTROUTING"
- "-A CATTLE_POSTROUTING"
- "-A FORWARD"
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import sys
import uuid
import string
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
from salt.exceptions import SaltException
from salt.ext import six
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if iptables is installed
'''
if not salt.utils.path.which('iptables'):
return (False, 'The iptables execution module cannot be loaded: iptables not installed.')
return True
def _iptables_cmd(family='ipv4'):
'''
Return correct command based on the family, e.g. ipv4 or ipv6
'''
if family == 'ipv6':
return salt.utils.path.which('ip6tables')
else:
return salt.utils.path.which('iptables')
def _has_option(option, family='ipv4'):
'''
Return truth of whether iptables has `option`. For example:
.. code-block:: python
_has_option('--wait')
_has_option('--check', family='ipv6')
'''
cmd = '{0} --help'.format(_iptables_cmd(family))
if option in __salt__['cmd.run'](cmd, output_loglevel='quiet'):
return True
return False
def _conf(family='ipv4'):
'''
Some distros have a specific location for config files
'''
if __grains__['os_family'] == 'RedHat':
if family == 'ipv6':
return '/etc/sysconfig/ip6tables'
else:
return '/etc/sysconfig/iptables'
elif __grains__['os_family'] == 'Arch':
if family == 'ipv6':
return '/etc/iptables/ip6tables.rules'
else:
return '/etc/iptables/iptables.rules'
elif __grains__['os_family'] == 'Debian':
if family == 'ipv6':
return '/etc/iptables/rules.v6'
else:
return '/etc/iptables/rules.v4'
elif __grains__['os_family'] == 'Gentoo':
if family == 'ipv6':
return '/var/lib/ip6tables/rules-save'
else:
return '/var/lib/iptables/rules-save'
elif __grains__['os_family'] == 'Suse':
# SuSE does not seem to use separate files for IPv4 and IPv6
return '/etc/sysconfig/scripts/SuSEfirewall2-custom'
elif __grains__['os_family'] == 'Void':
if family == 'ipv4':
return '/etc/iptables/iptables.rules'
else:
return '/etc/iptables/ip6tables.rules'
elif __grains__['os'] == 'Alpine':
if family == 'ipv6':
return '/etc/iptables/rules6-save'
else:
return '/etc/iptables/rules-save'
else:
raise SaltException('Saving iptables to file is not' +
' supported on {0}.'.format(__grains__['os']) +
' Please file an issue with SaltStack')
def _conf_save_filters():
'''
Return array of strings from `save_filters` in config.
This array will be pulled from minion config, minion grains,
minion pillar, or master config. The default value returned is [].
.. code-block:: python
_conf_save_filters()
'''
config = __salt__['config.option']('iptables.save_filters', [])
return config
def _regex_iptables_save(cmd_output, filters=None):
'''
Return string with `save_filter` regex entries removed. For example:
If `filters` is not provided, it will be pulled from minion config,
minion grains, minion pillar, or master config. Default return value
if no filters found is the original cmd_output string.
.. code-block:: python
_regex_iptables_save(cmd_output, ['-A DOCKER*'])
'''
# grab RE compiled filters from context for performance
if 'iptables.save_filters' not in __context__:
__context__['iptables.save_filters'] = []
for pattern in filters or _conf_save_filters():
try:
__context__['iptables.save_filters']\
.append(re.compile(pattern))
except re.error as e:
log.warning('Skipping regex rule: \'%s\': %s',
pattern, e)
continue
if __context__['iptables.save_filters']:
# line by line get rid of any regex matches
_filtered_cmd_output = \
[line for line in cmd_output.splitlines(True)
if not any(reg.search(line) for reg
in __context__['iptables.save_filters'])]
return ''.join(_filtered_cmd_output)
return cmd_output
def version(family='ipv4'):
'''
Return version from iptables --version
CLI Example:
.. code-block:: bash
salt '*' iptables.version
IPv6:
salt '*' iptables.version family=ipv6
'''
cmd = '{0} --version' . format(_iptables_cmd(family))
out = __salt__['cmd.run'](cmd).split()
return out[1]
def build_rule(table='filter', chain=None, command=None, position='', full=None, family='ipv4',
**kwargs):
'''
Build a well-formatted iptables rule based on kwargs. A `table` and `chain`
are not required, unless `full` is True.
If `full` is `True`, then `table`, `chain` and `command` are required.
`command` may be specified as either a short option ('I') or a long option
(`--insert`). This will return the iptables command, exactly as it would
be used from the command line.
If a position is required (as with `-I` or `-D`), it may be specified as
`position`. This will only be useful if `full` is True.
If `state` is passed, it will be ignored, use `connstate`.
If `connstate` is passed in, it will automatically be changed to `state`.
To pass in jump options that doesn't take arguments, pass in an empty
string.
.. note::
Whereas iptables will accept ``-p``, ``--proto[c[o[l]]]`` as synonyms
of ``--protocol``, if ``--proto`` appears in an iptables command after
the appearance of ``-m policy``, it is interpreted as the ``--proto``
option of the policy extension (see the iptables-extensions(8) man
page).
CLI Examples:
.. code-block:: bash
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='127.0.0.1' jump=ACCEPT
.. Invert Rules
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
source='!127.0.0.1' jump=ACCEPT
salt '*' iptables.build_rule filter INPUT command=A \\
full=True match=state connstate=RELATED,ESTABLISHED \\
destination='not 127.0.0.1' jump=ACCEPT
IPv6:
salt '*' iptables.build_rule match=state \\
connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
salt '*' iptables.build_rule filter INPUT command=I position=3 \\
full=True match=state connstate=RELATED,ESTABLISHED jump=ACCEPT \\
family=ipv6
'''
if 'target' in kwargs:
kwargs['jump'] = kwargs.pop('target')
# Ignore name and state for this function
kwargs.pop('name', None)
kwargs.pop('state', None)
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['chain', 'save', 'table']:
if ignore in kwargs:
del kwargs[ignore]
rule = []
protocol = False
bang_not_pat = re.compile(r'(!|not)\s?')
def maybe_add_negation(arg):
'''
Will check if the defined argument is intended to be negated,
(i.e. prefixed with '!' or 'not'), and add a '! ' to the rule.
The prefix will be removed from the value in the kwargs dict.
'''
value = str(kwargs[arg])
if value.startswith('!') or value.startswith('not'):
kwargs[arg] = re.sub(bang_not_pat, '', value)
return '! '
return ''
if 'if' in kwargs:
rule.append('{0}-i {1}'.format(maybe_add_negation('if'), kwargs['if']))
del kwargs['if']
if 'of' in kwargs:
rule.append('{0}-o {1}'.format(maybe_add_negation('of'), kwargs['of']))
del kwargs['of']
if 'proto' in kwargs and kwargs.get('match') != 'policy':
kwargs['protocol'] = kwargs['proto']
del kwargs['proto']
# Handle the case 'proto' in kwargs and kwargs.get('match') == 'policy' below
if 'protocol' in kwargs:
if not protocol:
rule.append('{0}-p {1}'.format(maybe_add_negation('protocol'), kwargs['protocol']))
protocol = True
del kwargs['protocol']
if 'match' in kwargs:
match_value = kwargs['match']
if not isinstance(match_value, list):
match_value = match_value.split(',')
for match in match_value:
rule.append('-m {0}'.format(match))
if 'name_' in kwargs and match.strip() in ('pknock', 'quota2', 'recent'):
rule.append('--name {0}'.format(kwargs['name_']))
del kwargs['name_']
if 'proto' in kwargs and kwargs.get('match') == 'policy':
rule.append('{0}--proto {1}'.format(maybe_add_negation('proto'), kwargs['proto']))
del kwargs['proto']
del kwargs['match']
if 'match-set' in kwargs:
if isinstance(kwargs['match-set'], six.string_types):
kwargs['match-set'] = [kwargs['match-set']]
for match_set in kwargs['match-set']:
negative_match_set = ''
if match_set.startswith('!') or match_set.startswith('not'):
negative_match_set = '! '
match_set = re.sub(bang_not_pat, '', match_set)
rule.append('-m set {0}--match-set {1}'.format(negative_match_set, match_set))
del kwargs['match-set']
if 'connstate' in kwargs:
if '-m state' not in rule:
rule.append('-m state')
rule.append('{0}--state {1}'.format(maybe_add_negation('connstate'), kwargs['connstate']))
del kwargs['connstate']
if 'dport' in kwargs:
rule.append('{0}--dport {1}'.format(maybe_add_negation('dport'), kwargs['dport']))
del kwargs['dport']
if 'sport' in kwargs:
rule.append('{0}--sport {1}'.format(maybe_add_negation('sport'), kwargs['sport']))
del kwargs['sport']
for multiport_arg in ('dports', 'sports'):
if multiport_arg in kwargs:
if '-m multiport' not in rule:
rule.append('-m multiport')
if not protocol:
return 'Error: protocol must be specified'
mp_value = kwargs[multiport_arg]
if isinstance(mp_value, list):
if any(i for i in mp_value if str(i).startswith('!') or str(i).startswith('not')):
mp_value = [re.sub(bang_not_pat, '', str(item)) for item in mp_value]
rule.append('!')
dports = ','.join(str(i) for i in mp_value)
else:
if str(mp_value).startswith('!') or str(mp_value).startswith('not'):
dports = re.sub(bang_not_pat, '', mp_value)
rule.append('!')
else:
dports = mp_value
rule.append('--{0} {1}'.format(multiport_arg, dports))
del kwargs[multiport_arg]
if 'comment' in kwargs:
if '-m comment' not in rule:
rule.append('-m comment')
rule.append('--comment "{0}"'.format(kwargs['comment']))
del kwargs['comment']
# --set in ipset is deprecated, works but returns error.
# rewrite to --match-set if not empty, otherwise treat as recent option
if 'set' in kwargs and kwargs['set']:
rule.append('{0}--match-set {1}'.format(maybe_add_negation('set'), kwargs['set']))
del kwargs['set']
# Jumps should appear last, except for any arguments that are passed to
# jumps, which of course need to follow.
after_jump = []
# All jump arguments as extracted from man iptables-extensions, man iptables,
# man xtables-addons and http://www.iptables.info/en/iptables-targets-and-jumps.html
after_jump_arguments = (
'j', # j and jump needs to be first
'jump',
# IPTABLES
'add-set',
'and-mark',
'and-tos',
'checksum-fill',
'clamp-mss-to-pmtu',
'clustermac',
'ctevents',
'ctmask',
'del-set',
'ecn-tcp-remove',
'exist',
'expevents',
'gateway',
'hash-init',
'hashmode',
'helper',
'label',
'local-node',
'log-ip-options',
'log-level',
'log-prefix',
'log-tcp-options',
'log-tcp-sequence',
'log-uid',
'mask',
'new',
'nfmask',
'nflog-group',
'nflog-prefix',
'nflog-range',
'nflog-threshold',
'nodst',
'notrack',
'on-ip',
'on-port',
'or-mark',
'or-tos',
'persistent',
'queue-balance',
'queue-bypass',
'queue-num',
'random',
'rateest-ewmalog',
'rateest-interval',
'rateest-name',
'reject-with',
'restore',
'restore-mark',
#'save', # no arg, problematic name: How do we avoid collision with this?
'save-mark',
'selctx',
'set-class',
'set-dscp',
'set-dscp-class',
'set-mark',
'set-mss',
'set-tos',
'set-xmark',
'strip-options',
'timeout',
'to',
'to-destination',
'to-ports',
'to-source',
'total-nodes',
'tproxy-mark',
'ttl-dec',
'ttl-inc',
'ttl-set',
'type',
'ulog-cprange',
'ulog-nlgroup',
'ulog-prefix',
'ulog-qthreshold',
'xor-mark',
'xor-tos',
'zone',
# IPTABLES-EXTENSIONS
'dst-pfx',
'hl-dec',
'hl-inc',
'hl-set',
'hmark-dport-mask',
'hmark-dst-prefix',
'hmark-mod',
'hmark-offset',
'hmark-proto-mask',
'hmark-rnd',
'hmark-spi-mask',
'hmark-sport-mask',
'hmark-src-prefix',
'hmark-tuple',
'led-always-blink',
'led-delay',
'led-trigger-id',
'queue-cpu-fanout',
'src-pfx',
# WEB
'to-port',
# XTABLES
'addr',
'and-mask',
'delude',
'honeypot',
'or-mask',
'prefix',
'reset',
'reuse',
'set-mac',
'shift',
'static',
'tarpit',
'tname',
'ttl',
)
for after_jump_argument in after_jump_arguments:
if after_jump_argument in kwargs:
value = kwargs[after_jump_argument]
if value in (None, ''): # options without arguments
after_jump.append('--{0}'.format(after_jump_argument))
elif any(ws_char in str(value) for ws_char in string.whitespace):
after_jump.append('--{0} "{1}"'.format(after_jump_argument, value))
else:
after_jump.append('--{0} {1}'.format(after_jump_argument, value))
del kwargs[after_jump_argument]
for key in kwargs:
negation = maybe_add_negation(key)
# don't use .items() since maybe_add_negation removes the prefix from
# the value in the kwargs, thus we need to fetch it after that has run
value = kwargs[key]
flag = '-' if len(key) == 1 else '--'
value = '' if value in (None, '') else ' {0}'.format(value)
rule.append('{0}{1}{2}{3}'.format(negation, flag, key, value))
rule += after_jump
if full:
if not table:
return 'Error: Table needs to be specified'
if not chain:
return 'Error: Chain needs to be specified'
if not command:
return 'Error: Command needs to be specified'
if command in 'ACDIRLSFZNXPE':
flag = '-'
else:
flag = '--'
wait = '--wait' if _has_option('--wait', family) else ''
return '{0} {1} -t {2} {3}{4} {5} {6} {7}'.format(_iptables_cmd(family),
wait, table, flag, command, chain, position, ' '.join(rule))
return ' '.join(rule)
def get_saved_rules(conf_file=None, family='ipv4'):
'''
Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' iptables.get_saved_rules
IPv6:
salt '*' iptables.get_saved_rules family=ipv6
'''
return _parse_conf(conf_file=conf_file, family=family)
def get_rules(family='ipv4'):
'''
Return a data structure of the current, in-memory rules
CLI Example:
.. code-block:: bash
salt '*' iptables.get_rules
IPv6:
salt '*' iptables.get_rules family=ipv6
'''
return _parse_conf(in_mem=True, family=family)
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved
IPv6:
salt '*' iptables.get_saved_policy filter INPUT family=ipv6
salt '*' iptables.get_saved_policy filter INPUT \\
conf_file=/etc/iptables.saved family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(conf_file, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
rules = _parse_conf(in_mem=True, family=family)
try:
return rules[table][chain]['policy']
except KeyError:
return None
def set_policy(table='filter', chain=None, policy=None, family='ipv4'):
'''
Set the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.set_policy filter INPUT ACCEPT
IPv6:
salt '*' iptables.set_policy filter INPUT ACCEPT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not policy:
return 'Error: Policy needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -P {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, policy)
out = __salt__['cmd.run'](cmd)
return out
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
filename = _conf(family)
log.debug('Saving rules to %s', filename)
parent_dir = os.path.dirname(filename)
if not os.path.isdir(parent_dir):
os.makedirs(parent_dir)
cmd = '{0}-save'.format(_iptables_cmd(family))
ipt = __salt__['cmd.run'](cmd)
# regex out the output if configured with filters
if _conf_save_filters():
ipt = _regex_iptables_save(ipt)
out = __salt__['file.write'](filename, ipt)
return out
def check(table='filter', chain=None, rule=None, family='ipv4'):
'''
Check for the existence of a rule in the table and chain
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.check filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
ipt_cmd = _iptables_cmd(family)
if _has_option('--check', family):
cmd = '{0} -t {1} -C {2} {3}'.format(ipt_cmd, table, chain, rule)
out = __salt__['cmd.run'](cmd, output_loglevel='quiet')
else:
_chain_name = hex(uuid.getnode())
# Create temporary table
__salt__['cmd.run']('{0} -t {1} -N {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -A {2} {3}'.format(ipt_cmd, table, _chain_name, rule))
out = __salt__['cmd.run']('{0}-save'.format(ipt_cmd))
# Clean up temporary table
__salt__['cmd.run']('{0} -t {1} -F {2}'.format(ipt_cmd, table, _chain_name))
__salt__['cmd.run']('{0} -t {1} -X {2}'.format(ipt_cmd, table, _chain_name))
for i in out.splitlines():
if i.startswith('-A {0}'.format(_chain_name)):
if i.replace(_chain_name, chain) in out.splitlines():
return True
return False
if not out:
return True
return out
def check_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Check for the existence of a chain in the table
CLI Example:
.. code-block:: bash
salt '*' iptables.check_chain filter INPUT
IPv6:
salt '*' iptables.check_chain filter INPUT family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))
if out != -1:
out = True
else:
out = False
return out
def new_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Create new custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.new_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.new_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -N {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def delete_chain(table='filter', chain=None, family='ipv4'):
'''
.. versionadded:: 2014.1.0
Delete custom chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' iptables.delete_chain filter CUSTOM_CHAIN
IPv6:
salt '*' iptables.delete_chain filter CUSTOM_CHAIN family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -X {3}'.format(
_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
if not out:
out = True
return out
def append(table='filter', chain=None, rule=None, family='ipv4'):
'''
Append a rule to the specified table/chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Example:
.. code-block:: bash
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.append filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not rule:
return 'Error: Rule needs to be specified'
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -A {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return not out
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'):
'''
Insert a rule into the specified table/chain, at the specified position.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
If the position specified is a negative number, then the insert will be
performed counting from the end of the list. For instance, a position
of -1 will insert the rule as the second to last rule. To insert a rule
in the last position, use the append function instead.
CLI Examples:
.. code-block:: bash
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.insert filter INPUT position=3 \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if not chain:
return 'Error: Chain needs to be specified'
if not position:
return 'Error: Position needs to be specified or use append (-A)'
if not rule:
return 'Error: Rule needs to be specified'
if position < 0:
rules = get_rules(family=family)
size = len(rules[table][chain]['rules'])
position = (size + position) + 1
if position is 0:
position = 1
wait = '--wait' if _has_option('--wait', family) else ''
returnCheck = check(table, chain, rule, family)
if isinstance(returnCheck, bool) and returnCheck:
return False
cmd = '{0} {1} -t {2} -I {3} {4} {5}'.format(
_iptables_cmd(family), wait, table, chain, position, rule)
out = __salt__['cmd.run'](cmd)
return out
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the chain. Trying to force users to adapt to a new
method of creating rules would be irritating at best, and we
already have a parser that can handle it.
CLI Examples:
.. code-block:: bash
salt '*' iptables.delete filter INPUT position=3
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
IPv6:
salt '*' iptables.delete filter INPUT position=3 family=ipv6
salt '*' iptables.delete filter INPUT \\
rule='-m state --state RELATED,ESTABLISHED -j ACCEPT' \\
family=ipv6
'''
if position and rule:
return 'Error: Only specify a position or a rule, not both'
if position:
rule = position
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -D {3} {4}'.format(
_iptables_cmd(family), wait, table, chain, rule)
out = __salt__['cmd.run'](cmd)
return out
def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6
'''
wait = '--wait' if _has_option('--wait', family) else ''
cmd = '{0} {1} -t {2} -F {3}'.format(_iptables_cmd(family), wait, table, chain)
out = __salt__['cmd.run'](cmd)
return out
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
'''
If a file is not passed in, and the correct one for this OS is not
detected, return False
'''
if _conf() and not conf_file and not in_mem:
conf_file = _conf(family)
rules = ''
if conf_file:
with salt.utils.files.fopen(conf_file, 'r') as ifile:
rules = ifile.read()
elif in_mem:
cmd = '{0}-save' . format(_iptables_cmd(family))
rules = __salt__['cmd.run'](cmd)
else:
raise SaltException('A file was not found to parse')
ret = {}
table = ''
parser = _parser()
for line in rules.splitlines():
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('*'):
table = line.replace('*', '')
ret[table] = {}
elif line.startswith(':'):
comps = line.split()
chain = comps[0].replace(':', '')
ret[table][chain] = {}
ret[table][chain]['policy'] = comps[1]
counters = comps[2].replace('[', '').replace(']', '')
(pcount, bcount) = counters.split(':')
ret[table][chain]['packet count'] = pcount
ret[table][chain]['byte count'] = bcount
ret[table][chain]['rules'] = []
ret[table][chain]['rules_comment'] = {}
elif line.startswith('-A'):
args = salt.utils.args.shlex_split(line)
index = 0
while index + 1 < len(args):
swap = args[index] == '!' and args[index + 1].startswith('-')
if swap:
args[index], args[index + 1] = args[index + 1], args[index]
if args[index].startswith('-'):
index += 1
if args[index].startswith('-') or (args[index] == '!' and
not swap):
args.insert(index, '')
else:
while (index + 1 < len(args) and
args[index + 1] != '!' and
not args[index + 1].startswith('-')):
args[index] += ' {0}'.format(args.pop(index + 1))
index += 1
if args[-1].startswith('-'):
args.append('')
parsed_args = []
opts, _ = parser.parse_known_args(args)
parsed_args = vars(opts)
ret_args = {}
chain = parsed_args['append']
for arg in parsed_args:
if parsed_args[arg] and arg is not 'append':
ret_args[arg] = parsed_args[arg]
if parsed_args['comment'] is not None:
comment = parsed_args['comment'][0].strip('"')
ret[table][chain[0]]['rules_comment'][comment] = ret_args
ret[table][chain[0]]['rules'].append(ret_args)
return ret
|
saltstack/salt
|
salt/states/group.py
|
_changes
|
python
|
def _changes(name,
gid=None,
addusers=None,
delusers=None,
members=None):
'''
Return a dict of the changes required for a group if the group is present,
otherwise return False.
'''
lgrp = __salt__['group.info'](name)
if not lgrp:
return False
# User and Domain names are not case sensitive in Windows. Let's make them
# all lower case so we can compare properly
if salt.utils.platform.is_windows():
if lgrp['members']:
lgrp['members'] = [user.lower() for user in lgrp['members']]
if members:
members = [salt.utils.win_functions.get_sam_name(user).lower() for user in members]
if addusers:
addusers = [salt.utils.win_functions.get_sam_name(user).lower() for user in addusers]
if delusers:
delusers = [salt.utils.win_functions.get_sam_name(user).lower() for user in delusers]
change = {}
ret = {}
if gid:
try:
gid = int(gid)
if lgrp['gid'] != gid:
change['gid'] = gid
except (TypeError, ValueError):
ret['result'] = False
ret['comment'] = 'Invalid gid'
return ret
if members is not None and not members:
if set(lgrp['members']).symmetric_difference(members):
change['delusers'] = set(lgrp['members'])
elif members:
# if new member list if different than the current
if set(lgrp['members']).symmetric_difference(members):
change['members'] = members
if addusers:
users_2add = [user for user in addusers if user not in lgrp['members']]
if users_2add:
change['addusers'] = users_2add
if delusers:
users_2del = [user for user in delusers if user in lgrp['members']]
if users_2del:
change['delusers'] = users_2del
return change
|
Return a dict of the changes required for a group if the group is present,
otherwise return False.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/group.py#L49-L104
| null |
# -*- coding: utf-8 -*-
'''
Management of user groups
=========================
The group module is used to create and manage group settings, groups can be
either present or absent. User/Group names can be passed to the ``adduser``,
``deluser``, and ``members`` parameters. ``adduser`` and ``deluser`` can be used
together but not with ``members``.
In Windows, if no domain is specified in the user or group name (i.e.
``DOMAIN\\username``) the module will assume a local user or group.
.. code-block:: yaml
cheese:
group.present:
- gid: 7648
- system: True
- addusers:
- user1
- users2
- delusers:
- foo
cheese:
group.present:
- gid: 7648
- system: True
- members:
- foo
- bar
- user1
- user2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import sys
# Import 3rd-party libs
from salt.ext import six
# Import Salt libs
import salt.utils.platform
import salt.utils.win_functions
def present(name,
gid=None,
system=False,
addusers=None,
delusers=None,
members=None):
r'''
Ensure that a group is present
Args:
name (str):
The name of the group to manage
gid (str):
The group id to assign to the named group; if left empty, then the
next available group id will be assigned. Ignored on Windows
system (bool):
Whether or not the named group is a system group. This is essentially
the '-r' option of 'groupadd'. Ignored on Windows
addusers (list):
List of additional users to be added as a group members. Cannot
conflict with names in delusers. Cannot be used in conjunction with
members.
delusers (list):
Ensure these user are removed from the group membership. Cannot
conflict with names in addusers. Cannot be used in conjunction with
members.
members (list):
Replace existing group members with a list of new members. Cannot be
used in conjunction with addusers or delusers.
Example:
.. code-block:: yaml
# Adds DOMAIN\db_admins and Administrators to the local db_admin group
# Removes Users
db_admin:
group.present:
- addusers:
- DOMAIN\db_admins
- Administrators
- delusers:
- Users
# Ensures only DOMAIN\domain_admins and the local Administrator are
# members of the local Administrators group. All other users are
# removed
Administrators:
group.present:
- members:
- DOMAIN\domain_admins
- Administrator
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Group {0} is present and up to date'.format(name)}
if members is not None and (addusers is not None or delusers is not None):
ret['result'] = None
ret['comment'] = (
'Error: Conflicting options "members" with "addusers" and/or'
' "delusers" can not be used together. ')
return ret
if addusers and delusers:
# -- if trying to add and delete the same user(s) at the same time.
if not set(addusers).isdisjoint(set(delusers)):
ret['result'] = None
ret['comment'] = (
'Error. Same user(s) can not be added and deleted'
' simultaneously')
return ret
changes = _changes(name,
gid,
addusers,
delusers,
members)
if changes:
ret['comment'] = (
'The following group attributes are set to be changed:\n')
for key, val in six.iteritems(changes):
ret['comment'] += '{0}: {1}\n'.format(key, val)
if __opts__['test']:
ret['result'] = None
return ret
for key, val in six.iteritems(changes):
if key == 'gid':
__salt__['group.chgid'](name, gid)
continue
if key == 'addusers':
for user in val:
__salt__['group.adduser'](name, user)
continue
if key == 'delusers':
for user in val:
__salt__['group.deluser'](name, user)
continue
if key == 'members':
__salt__['group.members'](name, ','.join(members))
continue
# Clear cached group data
sys.modules[
__salt__['test.ping'].__module__
].__context__.pop('group.getent', None)
changes = _changes(name,
gid,
addusers,
delusers,
members)
if changes:
ret['result'] = False
ret['comment'] += 'Some changes could not be applied'
ret['changes'] = {'Failed': changes}
else:
ret['changes'] = {'Final': 'All changes applied successfully'}
if changes is False:
# The group is not present, make it!
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Group {0} set to be added'.format(name)
return ret
grps = __salt__['group.getent']()
# Test if gid is free
if gid is not None:
gid_group = None
for lgrp in grps:
if lgrp['gid'] == gid:
gid_group = lgrp['name']
break
if gid_group is not None:
ret['result'] = False
ret['comment'] = (
'Group {0} is not present but gid {1} is already taken by'
' group {2}'.format(name, gid, gid_group))
return ret
# Group is not present, make it.
if __salt__['group.add'](name, gid=gid, system=system):
# if members to be added
grp_members = None
if members:
grp_members = ','.join(members)
if addusers:
grp_members = ','.join(addusers)
if grp_members:
__salt__['group.members'](name, grp_members)
# Clear cached group data
sys.modules[__salt__['test.ping'].__module__].__context__.pop(
'group.getent', None)
ret['comment'] = 'New group {0} created'.format(name)
ret['changes'] = __salt__['group.info'](name)
changes = _changes(name,
gid,
addusers,
delusers,
members)
if changes:
ret['result'] = False
ret['comment'] = (
'Group {0} has been created but, some changes could not'
' be applied'.format(name))
ret['changes'] = {'Failed': changes}
else:
ret['result'] = False
ret['comment'] = 'Failed to create new group {0}'.format(name)
return ret
def absent(name):
'''
Ensure that the named group is absent
Args:
name (str):
The name of the group to remove
Example:
.. code-block:: yaml
# Removes the local group `db_admin`
db_admin:
group.absent
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
grp_info = __salt__['group.info'](name)
if grp_info:
# Group already exists. Remove the group.
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Group {0} is set for removal'.format(name)
return ret
ret['result'] = __salt__['group.delete'](name)
if ret['result']:
ret['changes'] = {name: ''}
ret['comment'] = 'Removed group {0}'.format(name)
return ret
else:
ret['comment'] = 'Failed to remove group {0}'.format(name)
return ret
else:
ret['comment'] = 'Group not present'
return ret
|
saltstack/salt
|
salt/states/group.py
|
present
|
python
|
def present(name,
gid=None,
system=False,
addusers=None,
delusers=None,
members=None):
r'''
Ensure that a group is present
Args:
name (str):
The name of the group to manage
gid (str):
The group id to assign to the named group; if left empty, then the
next available group id will be assigned. Ignored on Windows
system (bool):
Whether or not the named group is a system group. This is essentially
the '-r' option of 'groupadd'. Ignored on Windows
addusers (list):
List of additional users to be added as a group members. Cannot
conflict with names in delusers. Cannot be used in conjunction with
members.
delusers (list):
Ensure these user are removed from the group membership. Cannot
conflict with names in addusers. Cannot be used in conjunction with
members.
members (list):
Replace existing group members with a list of new members. Cannot be
used in conjunction with addusers or delusers.
Example:
.. code-block:: yaml
# Adds DOMAIN\db_admins and Administrators to the local db_admin group
# Removes Users
db_admin:
group.present:
- addusers:
- DOMAIN\db_admins
- Administrators
- delusers:
- Users
# Ensures only DOMAIN\domain_admins and the local Administrator are
# members of the local Administrators group. All other users are
# removed
Administrators:
group.present:
- members:
- DOMAIN\domain_admins
- Administrator
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Group {0} is present and up to date'.format(name)}
if members is not None and (addusers is not None or delusers is not None):
ret['result'] = None
ret['comment'] = (
'Error: Conflicting options "members" with "addusers" and/or'
' "delusers" can not be used together. ')
return ret
if addusers and delusers:
# -- if trying to add and delete the same user(s) at the same time.
if not set(addusers).isdisjoint(set(delusers)):
ret['result'] = None
ret['comment'] = (
'Error. Same user(s) can not be added and deleted'
' simultaneously')
return ret
changes = _changes(name,
gid,
addusers,
delusers,
members)
if changes:
ret['comment'] = (
'The following group attributes are set to be changed:\n')
for key, val in six.iteritems(changes):
ret['comment'] += '{0}: {1}\n'.format(key, val)
if __opts__['test']:
ret['result'] = None
return ret
for key, val in six.iteritems(changes):
if key == 'gid':
__salt__['group.chgid'](name, gid)
continue
if key == 'addusers':
for user in val:
__salt__['group.adduser'](name, user)
continue
if key == 'delusers':
for user in val:
__salt__['group.deluser'](name, user)
continue
if key == 'members':
__salt__['group.members'](name, ','.join(members))
continue
# Clear cached group data
sys.modules[
__salt__['test.ping'].__module__
].__context__.pop('group.getent', None)
changes = _changes(name,
gid,
addusers,
delusers,
members)
if changes:
ret['result'] = False
ret['comment'] += 'Some changes could not be applied'
ret['changes'] = {'Failed': changes}
else:
ret['changes'] = {'Final': 'All changes applied successfully'}
if changes is False:
# The group is not present, make it!
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Group {0} set to be added'.format(name)
return ret
grps = __salt__['group.getent']()
# Test if gid is free
if gid is not None:
gid_group = None
for lgrp in grps:
if lgrp['gid'] == gid:
gid_group = lgrp['name']
break
if gid_group is not None:
ret['result'] = False
ret['comment'] = (
'Group {0} is not present but gid {1} is already taken by'
' group {2}'.format(name, gid, gid_group))
return ret
# Group is not present, make it.
if __salt__['group.add'](name, gid=gid, system=system):
# if members to be added
grp_members = None
if members:
grp_members = ','.join(members)
if addusers:
grp_members = ','.join(addusers)
if grp_members:
__salt__['group.members'](name, grp_members)
# Clear cached group data
sys.modules[__salt__['test.ping'].__module__].__context__.pop(
'group.getent', None)
ret['comment'] = 'New group {0} created'.format(name)
ret['changes'] = __salt__['group.info'](name)
changes = _changes(name,
gid,
addusers,
delusers,
members)
if changes:
ret['result'] = False
ret['comment'] = (
'Group {0} has been created but, some changes could not'
' be applied'.format(name))
ret['changes'] = {'Failed': changes}
else:
ret['result'] = False
ret['comment'] = 'Failed to create new group {0}'.format(name)
return ret
|
r'''
Ensure that a group is present
Args:
name (str):
The name of the group to manage
gid (str):
The group id to assign to the named group; if left empty, then the
next available group id will be assigned. Ignored on Windows
system (bool):
Whether or not the named group is a system group. This is essentially
the '-r' option of 'groupadd'. Ignored on Windows
addusers (list):
List of additional users to be added as a group members. Cannot
conflict with names in delusers. Cannot be used in conjunction with
members.
delusers (list):
Ensure these user are removed from the group membership. Cannot
conflict with names in addusers. Cannot be used in conjunction with
members.
members (list):
Replace existing group members with a list of new members. Cannot be
used in conjunction with addusers or delusers.
Example:
.. code-block:: yaml
# Adds DOMAIN\db_admins and Administrators to the local db_admin group
# Removes Users
db_admin:
group.present:
- addusers:
- DOMAIN\db_admins
- Administrators
- delusers:
- Users
# Ensures only DOMAIN\domain_admins and the local Administrator are
# members of the local Administrators group. All other users are
# removed
Administrators:
group.present:
- members:
- DOMAIN\domain_admins
- Administrator
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/group.py#L107-L285
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _changes(name,\n gid=None,\n addusers=None,\n delusers=None,\n members=None):\n '''\n Return a dict of the changes required for a group if the group is present,\n otherwise return False.\n '''\n lgrp = __salt__['group.info'](name)\n if not lgrp:\n return False\n\n # User and Domain names are not case sensitive in Windows. Let's make them\n # all lower case so we can compare properly\n if salt.utils.platform.is_windows():\n if lgrp['members']:\n lgrp['members'] = [user.lower() for user in lgrp['members']]\n if members:\n members = [salt.utils.win_functions.get_sam_name(user).lower() for user in members]\n if addusers:\n addusers = [salt.utils.win_functions.get_sam_name(user).lower() for user in addusers]\n if delusers:\n delusers = [salt.utils.win_functions.get_sam_name(user).lower() for user in delusers]\n\n change = {}\n ret = {}\n if gid:\n try:\n gid = int(gid)\n if lgrp['gid'] != gid:\n change['gid'] = gid\n except (TypeError, ValueError):\n ret['result'] = False\n ret['comment'] = 'Invalid gid'\n return ret\n\n if members is not None and not members:\n if set(lgrp['members']).symmetric_difference(members):\n change['delusers'] = set(lgrp['members'])\n elif members:\n # if new member list if different than the current\n if set(lgrp['members']).symmetric_difference(members):\n change['members'] = members\n\n if addusers:\n users_2add = [user for user in addusers if user not in lgrp['members']]\n if users_2add:\n change['addusers'] = users_2add\n\n if delusers:\n users_2del = [user for user in delusers if user in lgrp['members']]\n if users_2del:\n change['delusers'] = users_2del\n\n return change\n"
] |
# -*- coding: utf-8 -*-
'''
Management of user groups
=========================
The group module is used to create and manage group settings, groups can be
either present or absent. User/Group names can be passed to the ``adduser``,
``deluser``, and ``members`` parameters. ``adduser`` and ``deluser`` can be used
together but not with ``members``.
In Windows, if no domain is specified in the user or group name (i.e.
``DOMAIN\\username``) the module will assume a local user or group.
.. code-block:: yaml
cheese:
group.present:
- gid: 7648
- system: True
- addusers:
- user1
- users2
- delusers:
- foo
cheese:
group.present:
- gid: 7648
- system: True
- members:
- foo
- bar
- user1
- user2
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import sys
# Import 3rd-party libs
from salt.ext import six
# Import Salt libs
import salt.utils.platform
import salt.utils.win_functions
def _changes(name,
gid=None,
addusers=None,
delusers=None,
members=None):
'''
Return a dict of the changes required for a group if the group is present,
otherwise return False.
'''
lgrp = __salt__['group.info'](name)
if not lgrp:
return False
# User and Domain names are not case sensitive in Windows. Let's make them
# all lower case so we can compare properly
if salt.utils.platform.is_windows():
if lgrp['members']:
lgrp['members'] = [user.lower() for user in lgrp['members']]
if members:
members = [salt.utils.win_functions.get_sam_name(user).lower() for user in members]
if addusers:
addusers = [salt.utils.win_functions.get_sam_name(user).lower() for user in addusers]
if delusers:
delusers = [salt.utils.win_functions.get_sam_name(user).lower() for user in delusers]
change = {}
ret = {}
if gid:
try:
gid = int(gid)
if lgrp['gid'] != gid:
change['gid'] = gid
except (TypeError, ValueError):
ret['result'] = False
ret['comment'] = 'Invalid gid'
return ret
if members is not None and not members:
if set(lgrp['members']).symmetric_difference(members):
change['delusers'] = set(lgrp['members'])
elif members:
# if new member list if different than the current
if set(lgrp['members']).symmetric_difference(members):
change['members'] = members
if addusers:
users_2add = [user for user in addusers if user not in lgrp['members']]
if users_2add:
change['addusers'] = users_2add
if delusers:
users_2del = [user for user in delusers if user in lgrp['members']]
if users_2del:
change['delusers'] = users_2del
return change
def absent(name):
'''
Ensure that the named group is absent
Args:
name (str):
The name of the group to remove
Example:
.. code-block:: yaml
# Removes the local group `db_admin`
db_admin:
group.absent
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
grp_info = __salt__['group.info'](name)
if grp_info:
# Group already exists. Remove the group.
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Group {0} is set for removal'.format(name)
return ret
ret['result'] = __salt__['group.delete'](name)
if ret['result']:
ret['changes'] = {name: ''}
ret['comment'] = 'Removed group {0}'.format(name)
return ret
else:
ret['comment'] = 'Failed to remove group {0}'.format(name)
return ret
else:
ret['comment'] = 'Group not present'
return ret
|
saltstack/salt
|
salt/modules/nix.py
|
_run
|
python
|
def _run(cmd):
'''
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
'''
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})
|
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nix.py#L47-L51
| null |
# -*- coding: utf-8 -*-
'''
Work with Nix packages
======================
.. versionadded:: 2017.7.0
Does not require the machine to be Nixos, just have Nix installed and available
to use for the user running this command. Their profile must be located in
their home, under ``$HOME/.nix-profile/``, and the nix store, unless specially
set up, should be in ``/nix``. To easily use this with multiple users or a root
user, set up the `nix-daemon`_.
This module exposes most of the common nix operations. Currently not meant to be run as a ``pkg`` module, but explicitly as ``nix.*``.
For more information on nix, see the `nix documentation`_.
.. _`nix documentation`: https://nixos.org/nix/manual/
.. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import itertools
import os
import salt.utils.itertools
import salt.utils.path
from salt.ext.six.moves import zip
logger = logging.getLogger(__name__)
def __virtual__():
'''
This only works if we have access to nix-env
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
if salt.utils.path.which(os.path.join(nixhome, 'nix-env')) and salt.utils.path.which(os.path.join(nixhome, 'nix-collect-garbage')):
return True
else:
return (False, "The `nix` binaries required cannot be found or are not installed. (`nix-store` and `nix-env`)")
def _nix_env():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-env')]
def _nix_collect_garbage():
'''
Make sure we get the right nix-store, too.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-collect-garbage')]
def _quietnix():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
p = _nix_env()
p.append('--no-build-output')
return p
def _zip_flatten(x, ys):
'''
intersperse x into ys, with an extra element at the beginning.
'''
return itertools.chain.from_iterable(
zip(itertools.repeat(x), ys))
def _output_format(out,
operation):
'''
gets a list of all the packages that were affected by ``operation``, splits it up (there can be multiple packages on a line), and then
flattens that list. We make it to a list for easier parsing.
'''
return [s.split()[1:] for s in out
if s.startswith(operation)]
def _format_upgrade(s):
'''
split the ``upgrade`` responses on ``' to '``
'''
return s.split(' to ')
def _strip_quotes(s):
'''
nix likes to quote itself in a backtick and a single quote. This just strips those.
'''
return s.strip("'`")
def upgrade(*pkgs):
'''
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: bash
salt '*' nix.update
salt '*' nix.update pkgs=one,two
'''
cmd = _quietnix()
cmd.append('--upgrade')
cmd.extend(pkgs)
out = _run(cmd)
upgrades = [_format_upgrade(s.split(maxsplit=1)[1])
for s in out['stderr'].splitlines()
if s.startswith('upgrading')]
return [[_strip_quotes(s_) for s_ in s]
for s in upgrades]
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
:rtype: list(str)
.. code-block:: bash
salt '*' nix.install package [package2 ...]
salt '*' nix.install attributes=True attr.name [attr.name2 ...]
'''
attributes = kwargs.get('attributes', False)
if not pkgs:
return "Plese specify a package or packages to upgrade"
cmd = _quietnix()
cmd.append('--install')
if kwargs.get('attributes', False):
cmd.extend(_zip_flatten('--attr', pkgs))
else:
cmd.extend(pkgs)
out = _run(cmd)
installs = list(itertools.chain.from_iterable(
[s.split()[1:] for s in out['stderr'].splitlines()
if s.startswith('installing')]
))
return [_strip_quotes(s) for s in installs]
def list_pkgs(installed=True,
attributes=True):
'''
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the packages when listing all packages.
Default: True
:return: Packages installed or available, along with their attributes.
:rtype: list(list(str))
.. code-block:: bash
salt '*' nix.list_pkgs
salt '*' nix.list_pkgs installed=False
'''
# We don't use -Q here, as it obfuscates the attribute names on full package listings.
cmd = _nix_env()
cmd.append('--query')
if installed:
# explicitly add this option for consistency, it's normally the default
cmd.append('--installed')
if not installed:
cmd.append('--available')
# We only show attributes if we're not doing an `installed` run.
# The output of `nix-env -qaP` and `nix-env -qP` are vastly different:
# `nix-env -qaP` returns a list such as 'attr.path name-version'
# `nix-env -qP` returns a list of 'installOrder name-version'
# Install order is useful to unambiguously select packages on a single
# machine, but on more than one it can be a bad thing to specify.
if attributes:
cmd.append('--attr-path')
out = _run(cmd)
return [s.split() for s in salt.utils.itertools.split(out['stdout'], '\n')]
def uninstall(*pkgs):
'''
Erases a package from the current nix profile. Nix uninstalls work differently than other package managers, and the symlinks in the
profile are removed, while the actual package remains. There is also a ``nix.purge`` function, to clear the package cache of unused
packages.
:type pkgs: list(str)
:param pkgs:
List, single package to uninstall
:return: Packages that have been uninstalled
:rtype: list(str)
.. code-block:: bash
salt '*' nix.uninstall pkg1 [pkg2 ...]
'''
cmd = _quietnix()
cmd.append('--uninstall')
cmd.extend(pkgs)
out = _run(cmd)
fmtout = out['stderr'].splitlines(), 'uninstalling'
return [_strip_quotes(s.split()[1])
for s in out['stderr'].splitlines()
if s.startswith('uninstalling')]
def collect_garbage():
'''
Completely removed all currently 'uninstalled' packages in the nix store.
Tells the user how many store paths were removed and how much space was freed.
:return: How much space was freed and how many derivations were removed
:rtype: str
.. warning::
This is a destructive action on the nix store.
.. code-block:: bash
salt '*' nix.collect_garbage
'''
cmd = _nix_collect_garbage()
cmd.append('--delete-old')
out = _run(cmd)
return out['stdout'].splitlines()
|
saltstack/salt
|
salt/modules/nix.py
|
_nix_env
|
python
|
def _nix_env():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-env')]
|
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nix.py#L54-L60
| null |
# -*- coding: utf-8 -*-
'''
Work with Nix packages
======================
.. versionadded:: 2017.7.0
Does not require the machine to be Nixos, just have Nix installed and available
to use for the user running this command. Their profile must be located in
their home, under ``$HOME/.nix-profile/``, and the nix store, unless specially
set up, should be in ``/nix``. To easily use this with multiple users or a root
user, set up the `nix-daemon`_.
This module exposes most of the common nix operations. Currently not meant to be run as a ``pkg`` module, but explicitly as ``nix.*``.
For more information on nix, see the `nix documentation`_.
.. _`nix documentation`: https://nixos.org/nix/manual/
.. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import itertools
import os
import salt.utils.itertools
import salt.utils.path
from salt.ext.six.moves import zip
logger = logging.getLogger(__name__)
def __virtual__():
'''
This only works if we have access to nix-env
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
if salt.utils.path.which(os.path.join(nixhome, 'nix-env')) and salt.utils.path.which(os.path.join(nixhome, 'nix-collect-garbage')):
return True
else:
return (False, "The `nix` binaries required cannot be found or are not installed. (`nix-store` and `nix-env`)")
def _run(cmd):
'''
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
'''
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})
def _nix_collect_garbage():
'''
Make sure we get the right nix-store, too.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-collect-garbage')]
def _quietnix():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
p = _nix_env()
p.append('--no-build-output')
return p
def _zip_flatten(x, ys):
'''
intersperse x into ys, with an extra element at the beginning.
'''
return itertools.chain.from_iterable(
zip(itertools.repeat(x), ys))
def _output_format(out,
operation):
'''
gets a list of all the packages that were affected by ``operation``, splits it up (there can be multiple packages on a line), and then
flattens that list. We make it to a list for easier parsing.
'''
return [s.split()[1:] for s in out
if s.startswith(operation)]
def _format_upgrade(s):
'''
split the ``upgrade`` responses on ``' to '``
'''
return s.split(' to ')
def _strip_quotes(s):
'''
nix likes to quote itself in a backtick and a single quote. This just strips those.
'''
return s.strip("'`")
def upgrade(*pkgs):
'''
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: bash
salt '*' nix.update
salt '*' nix.update pkgs=one,two
'''
cmd = _quietnix()
cmd.append('--upgrade')
cmd.extend(pkgs)
out = _run(cmd)
upgrades = [_format_upgrade(s.split(maxsplit=1)[1])
for s in out['stderr'].splitlines()
if s.startswith('upgrading')]
return [[_strip_quotes(s_) for s_ in s]
for s in upgrades]
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
:rtype: list(str)
.. code-block:: bash
salt '*' nix.install package [package2 ...]
salt '*' nix.install attributes=True attr.name [attr.name2 ...]
'''
attributes = kwargs.get('attributes', False)
if not pkgs:
return "Plese specify a package or packages to upgrade"
cmd = _quietnix()
cmd.append('--install')
if kwargs.get('attributes', False):
cmd.extend(_zip_flatten('--attr', pkgs))
else:
cmd.extend(pkgs)
out = _run(cmd)
installs = list(itertools.chain.from_iterable(
[s.split()[1:] for s in out['stderr'].splitlines()
if s.startswith('installing')]
))
return [_strip_quotes(s) for s in installs]
def list_pkgs(installed=True,
attributes=True):
'''
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the packages when listing all packages.
Default: True
:return: Packages installed or available, along with their attributes.
:rtype: list(list(str))
.. code-block:: bash
salt '*' nix.list_pkgs
salt '*' nix.list_pkgs installed=False
'''
# We don't use -Q here, as it obfuscates the attribute names on full package listings.
cmd = _nix_env()
cmd.append('--query')
if installed:
# explicitly add this option for consistency, it's normally the default
cmd.append('--installed')
if not installed:
cmd.append('--available')
# We only show attributes if we're not doing an `installed` run.
# The output of `nix-env -qaP` and `nix-env -qP` are vastly different:
# `nix-env -qaP` returns a list such as 'attr.path name-version'
# `nix-env -qP` returns a list of 'installOrder name-version'
# Install order is useful to unambiguously select packages on a single
# machine, but on more than one it can be a bad thing to specify.
if attributes:
cmd.append('--attr-path')
out = _run(cmd)
return [s.split() for s in salt.utils.itertools.split(out['stdout'], '\n')]
def uninstall(*pkgs):
'''
Erases a package from the current nix profile. Nix uninstalls work differently than other package managers, and the symlinks in the
profile are removed, while the actual package remains. There is also a ``nix.purge`` function, to clear the package cache of unused
packages.
:type pkgs: list(str)
:param pkgs:
List, single package to uninstall
:return: Packages that have been uninstalled
:rtype: list(str)
.. code-block:: bash
salt '*' nix.uninstall pkg1 [pkg2 ...]
'''
cmd = _quietnix()
cmd.append('--uninstall')
cmd.extend(pkgs)
out = _run(cmd)
fmtout = out['stderr'].splitlines(), 'uninstalling'
return [_strip_quotes(s.split()[1])
for s in out['stderr'].splitlines()
if s.startswith('uninstalling')]
def collect_garbage():
'''
Completely removed all currently 'uninstalled' packages in the nix store.
Tells the user how many store paths were removed and how much space was freed.
:return: How much space was freed and how many derivations were removed
:rtype: str
.. warning::
This is a destructive action on the nix store.
.. code-block:: bash
salt '*' nix.collect_garbage
'''
cmd = _nix_collect_garbage()
cmd.append('--delete-old')
out = _run(cmd)
return out['stdout'].splitlines()
|
saltstack/salt
|
salt/modules/nix.py
|
_nix_collect_garbage
|
python
|
def _nix_collect_garbage():
'''
Make sure we get the right nix-store, too.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-collect-garbage')]
|
Make sure we get the right nix-store, too.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nix.py#L63-L68
| null |
# -*- coding: utf-8 -*-
'''
Work with Nix packages
======================
.. versionadded:: 2017.7.0
Does not require the machine to be Nixos, just have Nix installed and available
to use for the user running this command. Their profile must be located in
their home, under ``$HOME/.nix-profile/``, and the nix store, unless specially
set up, should be in ``/nix``. To easily use this with multiple users or a root
user, set up the `nix-daemon`_.
This module exposes most of the common nix operations. Currently not meant to be run as a ``pkg`` module, but explicitly as ``nix.*``.
For more information on nix, see the `nix documentation`_.
.. _`nix documentation`: https://nixos.org/nix/manual/
.. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import itertools
import os
import salt.utils.itertools
import salt.utils.path
from salt.ext.six.moves import zip
logger = logging.getLogger(__name__)
def __virtual__():
'''
This only works if we have access to nix-env
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
if salt.utils.path.which(os.path.join(nixhome, 'nix-env')) and salt.utils.path.which(os.path.join(nixhome, 'nix-collect-garbage')):
return True
else:
return (False, "The `nix` binaries required cannot be found or are not installed. (`nix-store` and `nix-env`)")
def _run(cmd):
'''
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
'''
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})
def _nix_env():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-env')]
def _quietnix():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
p = _nix_env()
p.append('--no-build-output')
return p
def _zip_flatten(x, ys):
'''
intersperse x into ys, with an extra element at the beginning.
'''
return itertools.chain.from_iterable(
zip(itertools.repeat(x), ys))
def _output_format(out,
operation):
'''
gets a list of all the packages that were affected by ``operation``, splits it up (there can be multiple packages on a line), and then
flattens that list. We make it to a list for easier parsing.
'''
return [s.split()[1:] for s in out
if s.startswith(operation)]
def _format_upgrade(s):
'''
split the ``upgrade`` responses on ``' to '``
'''
return s.split(' to ')
def _strip_quotes(s):
'''
nix likes to quote itself in a backtick and a single quote. This just strips those.
'''
return s.strip("'`")
def upgrade(*pkgs):
'''
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: bash
salt '*' nix.update
salt '*' nix.update pkgs=one,two
'''
cmd = _quietnix()
cmd.append('--upgrade')
cmd.extend(pkgs)
out = _run(cmd)
upgrades = [_format_upgrade(s.split(maxsplit=1)[1])
for s in out['stderr'].splitlines()
if s.startswith('upgrading')]
return [[_strip_quotes(s_) for s_ in s]
for s in upgrades]
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
:rtype: list(str)
.. code-block:: bash
salt '*' nix.install package [package2 ...]
salt '*' nix.install attributes=True attr.name [attr.name2 ...]
'''
attributes = kwargs.get('attributes', False)
if not pkgs:
return "Plese specify a package or packages to upgrade"
cmd = _quietnix()
cmd.append('--install')
if kwargs.get('attributes', False):
cmd.extend(_zip_flatten('--attr', pkgs))
else:
cmd.extend(pkgs)
out = _run(cmd)
installs = list(itertools.chain.from_iterable(
[s.split()[1:] for s in out['stderr'].splitlines()
if s.startswith('installing')]
))
return [_strip_quotes(s) for s in installs]
def list_pkgs(installed=True,
attributes=True):
'''
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the packages when listing all packages.
Default: True
:return: Packages installed or available, along with their attributes.
:rtype: list(list(str))
.. code-block:: bash
salt '*' nix.list_pkgs
salt '*' nix.list_pkgs installed=False
'''
# We don't use -Q here, as it obfuscates the attribute names on full package listings.
cmd = _nix_env()
cmd.append('--query')
if installed:
# explicitly add this option for consistency, it's normally the default
cmd.append('--installed')
if not installed:
cmd.append('--available')
# We only show attributes if we're not doing an `installed` run.
# The output of `nix-env -qaP` and `nix-env -qP` are vastly different:
# `nix-env -qaP` returns a list such as 'attr.path name-version'
# `nix-env -qP` returns a list of 'installOrder name-version'
# Install order is useful to unambiguously select packages on a single
# machine, but on more than one it can be a bad thing to specify.
if attributes:
cmd.append('--attr-path')
out = _run(cmd)
return [s.split() for s in salt.utils.itertools.split(out['stdout'], '\n')]
def uninstall(*pkgs):
'''
Erases a package from the current nix profile. Nix uninstalls work differently than other package managers, and the symlinks in the
profile are removed, while the actual package remains. There is also a ``nix.purge`` function, to clear the package cache of unused
packages.
:type pkgs: list(str)
:param pkgs:
List, single package to uninstall
:return: Packages that have been uninstalled
:rtype: list(str)
.. code-block:: bash
salt '*' nix.uninstall pkg1 [pkg2 ...]
'''
cmd = _quietnix()
cmd.append('--uninstall')
cmd.extend(pkgs)
out = _run(cmd)
fmtout = out['stderr'].splitlines(), 'uninstalling'
return [_strip_quotes(s.split()[1])
for s in out['stderr'].splitlines()
if s.startswith('uninstalling')]
def collect_garbage():
'''
Completely removed all currently 'uninstalled' packages in the nix store.
Tells the user how many store paths were removed and how much space was freed.
:return: How much space was freed and how many derivations were removed
:rtype: str
.. warning::
This is a destructive action on the nix store.
.. code-block:: bash
salt '*' nix.collect_garbage
'''
cmd = _nix_collect_garbage()
cmd.append('--delete-old')
out = _run(cmd)
return out['stdout'].splitlines()
|
saltstack/salt
|
salt/modules/nix.py
|
_zip_flatten
|
python
|
def _zip_flatten(x, ys):
'''
intersperse x into ys, with an extra element at the beginning.
'''
return itertools.chain.from_iterable(
zip(itertools.repeat(x), ys))
|
intersperse x into ys, with an extra element at the beginning.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nix.py#L81-L86
| null |
# -*- coding: utf-8 -*-
'''
Work with Nix packages
======================
.. versionadded:: 2017.7.0
Does not require the machine to be Nixos, just have Nix installed and available
to use for the user running this command. Their profile must be located in
their home, under ``$HOME/.nix-profile/``, and the nix store, unless specially
set up, should be in ``/nix``. To easily use this with multiple users or a root
user, set up the `nix-daemon`_.
This module exposes most of the common nix operations. Currently not meant to be run as a ``pkg`` module, but explicitly as ``nix.*``.
For more information on nix, see the `nix documentation`_.
.. _`nix documentation`: https://nixos.org/nix/manual/
.. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import itertools
import os
import salt.utils.itertools
import salt.utils.path
from salt.ext.six.moves import zip
logger = logging.getLogger(__name__)
def __virtual__():
'''
This only works if we have access to nix-env
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
if salt.utils.path.which(os.path.join(nixhome, 'nix-env')) and salt.utils.path.which(os.path.join(nixhome, 'nix-collect-garbage')):
return True
else:
return (False, "The `nix` binaries required cannot be found or are not installed. (`nix-store` and `nix-env`)")
def _run(cmd):
'''
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
'''
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})
def _nix_env():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-env')]
def _nix_collect_garbage():
'''
Make sure we get the right nix-store, too.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-collect-garbage')]
def _quietnix():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
p = _nix_env()
p.append('--no-build-output')
return p
def _output_format(out,
operation):
'''
gets a list of all the packages that were affected by ``operation``, splits it up (there can be multiple packages on a line), and then
flattens that list. We make it to a list for easier parsing.
'''
return [s.split()[1:] for s in out
if s.startswith(operation)]
def _format_upgrade(s):
'''
split the ``upgrade`` responses on ``' to '``
'''
return s.split(' to ')
def _strip_quotes(s):
'''
nix likes to quote itself in a backtick and a single quote. This just strips those.
'''
return s.strip("'`")
def upgrade(*pkgs):
'''
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: bash
salt '*' nix.update
salt '*' nix.update pkgs=one,two
'''
cmd = _quietnix()
cmd.append('--upgrade')
cmd.extend(pkgs)
out = _run(cmd)
upgrades = [_format_upgrade(s.split(maxsplit=1)[1])
for s in out['stderr'].splitlines()
if s.startswith('upgrading')]
return [[_strip_quotes(s_) for s_ in s]
for s in upgrades]
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
:rtype: list(str)
.. code-block:: bash
salt '*' nix.install package [package2 ...]
salt '*' nix.install attributes=True attr.name [attr.name2 ...]
'''
attributes = kwargs.get('attributes', False)
if not pkgs:
return "Plese specify a package or packages to upgrade"
cmd = _quietnix()
cmd.append('--install')
if kwargs.get('attributes', False):
cmd.extend(_zip_flatten('--attr', pkgs))
else:
cmd.extend(pkgs)
out = _run(cmd)
installs = list(itertools.chain.from_iterable(
[s.split()[1:] for s in out['stderr'].splitlines()
if s.startswith('installing')]
))
return [_strip_quotes(s) for s in installs]
def list_pkgs(installed=True,
attributes=True):
'''
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the packages when listing all packages.
Default: True
:return: Packages installed or available, along with their attributes.
:rtype: list(list(str))
.. code-block:: bash
salt '*' nix.list_pkgs
salt '*' nix.list_pkgs installed=False
'''
# We don't use -Q here, as it obfuscates the attribute names on full package listings.
cmd = _nix_env()
cmd.append('--query')
if installed:
# explicitly add this option for consistency, it's normally the default
cmd.append('--installed')
if not installed:
cmd.append('--available')
# We only show attributes if we're not doing an `installed` run.
# The output of `nix-env -qaP` and `nix-env -qP` are vastly different:
# `nix-env -qaP` returns a list such as 'attr.path name-version'
# `nix-env -qP` returns a list of 'installOrder name-version'
# Install order is useful to unambiguously select packages on a single
# machine, but on more than one it can be a bad thing to specify.
if attributes:
cmd.append('--attr-path')
out = _run(cmd)
return [s.split() for s in salt.utils.itertools.split(out['stdout'], '\n')]
def uninstall(*pkgs):
'''
Erases a package from the current nix profile. Nix uninstalls work differently than other package managers, and the symlinks in the
profile are removed, while the actual package remains. There is also a ``nix.purge`` function, to clear the package cache of unused
packages.
:type pkgs: list(str)
:param pkgs:
List, single package to uninstall
:return: Packages that have been uninstalled
:rtype: list(str)
.. code-block:: bash
salt '*' nix.uninstall pkg1 [pkg2 ...]
'''
cmd = _quietnix()
cmd.append('--uninstall')
cmd.extend(pkgs)
out = _run(cmd)
fmtout = out['stderr'].splitlines(), 'uninstalling'
return [_strip_quotes(s.split()[1])
for s in out['stderr'].splitlines()
if s.startswith('uninstalling')]
def collect_garbage():
'''
Completely removed all currently 'uninstalled' packages in the nix store.
Tells the user how many store paths were removed and how much space was freed.
:return: How much space was freed and how many derivations were removed
:rtype: str
.. warning::
This is a destructive action on the nix store.
.. code-block:: bash
salt '*' nix.collect_garbage
'''
cmd = _nix_collect_garbage()
cmd.append('--delete-old')
out = _run(cmd)
return out['stdout'].splitlines()
|
saltstack/salt
|
salt/modules/nix.py
|
_output_format
|
python
|
def _output_format(out,
operation):
'''
gets a list of all the packages that were affected by ``operation``, splits it up (there can be multiple packages on a line), and then
flattens that list. We make it to a list for easier parsing.
'''
return [s.split()[1:] for s in out
if s.startswith(operation)]
|
gets a list of all the packages that were affected by ``operation``, splits it up (there can be multiple packages on a line), and then
flattens that list. We make it to a list for easier parsing.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nix.py#L89-L96
| null |
# -*- coding: utf-8 -*-
'''
Work with Nix packages
======================
.. versionadded:: 2017.7.0
Does not require the machine to be Nixos, just have Nix installed and available
to use for the user running this command. Their profile must be located in
their home, under ``$HOME/.nix-profile/``, and the nix store, unless specially
set up, should be in ``/nix``. To easily use this with multiple users or a root
user, set up the `nix-daemon`_.
This module exposes most of the common nix operations. Currently not meant to be run as a ``pkg`` module, but explicitly as ``nix.*``.
For more information on nix, see the `nix documentation`_.
.. _`nix documentation`: https://nixos.org/nix/manual/
.. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import itertools
import os
import salt.utils.itertools
import salt.utils.path
from salt.ext.six.moves import zip
logger = logging.getLogger(__name__)
def __virtual__():
'''
This only works if we have access to nix-env
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
if salt.utils.path.which(os.path.join(nixhome, 'nix-env')) and salt.utils.path.which(os.path.join(nixhome, 'nix-collect-garbage')):
return True
else:
return (False, "The `nix` binaries required cannot be found or are not installed. (`nix-store` and `nix-env`)")
def _run(cmd):
'''
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
'''
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})
def _nix_env():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-env')]
def _nix_collect_garbage():
'''
Make sure we get the right nix-store, too.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-collect-garbage')]
def _quietnix():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
p = _nix_env()
p.append('--no-build-output')
return p
def _zip_flatten(x, ys):
'''
intersperse x into ys, with an extra element at the beginning.
'''
return itertools.chain.from_iterable(
zip(itertools.repeat(x), ys))
def _format_upgrade(s):
'''
split the ``upgrade`` responses on ``' to '``
'''
return s.split(' to ')
def _strip_quotes(s):
'''
nix likes to quote itself in a backtick and a single quote. This just strips those.
'''
return s.strip("'`")
def upgrade(*pkgs):
'''
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: bash
salt '*' nix.update
salt '*' nix.update pkgs=one,two
'''
cmd = _quietnix()
cmd.append('--upgrade')
cmd.extend(pkgs)
out = _run(cmd)
upgrades = [_format_upgrade(s.split(maxsplit=1)[1])
for s in out['stderr'].splitlines()
if s.startswith('upgrading')]
return [[_strip_quotes(s_) for s_ in s]
for s in upgrades]
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
:rtype: list(str)
.. code-block:: bash
salt '*' nix.install package [package2 ...]
salt '*' nix.install attributes=True attr.name [attr.name2 ...]
'''
attributes = kwargs.get('attributes', False)
if not pkgs:
return "Plese specify a package or packages to upgrade"
cmd = _quietnix()
cmd.append('--install')
if kwargs.get('attributes', False):
cmd.extend(_zip_flatten('--attr', pkgs))
else:
cmd.extend(pkgs)
out = _run(cmd)
installs = list(itertools.chain.from_iterable(
[s.split()[1:] for s in out['stderr'].splitlines()
if s.startswith('installing')]
))
return [_strip_quotes(s) for s in installs]
def list_pkgs(installed=True,
attributes=True):
'''
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the packages when listing all packages.
Default: True
:return: Packages installed or available, along with their attributes.
:rtype: list(list(str))
.. code-block:: bash
salt '*' nix.list_pkgs
salt '*' nix.list_pkgs installed=False
'''
# We don't use -Q here, as it obfuscates the attribute names on full package listings.
cmd = _nix_env()
cmd.append('--query')
if installed:
# explicitly add this option for consistency, it's normally the default
cmd.append('--installed')
if not installed:
cmd.append('--available')
# We only show attributes if we're not doing an `installed` run.
# The output of `nix-env -qaP` and `nix-env -qP` are vastly different:
# `nix-env -qaP` returns a list such as 'attr.path name-version'
# `nix-env -qP` returns a list of 'installOrder name-version'
# Install order is useful to unambiguously select packages on a single
# machine, but on more than one it can be a bad thing to specify.
if attributes:
cmd.append('--attr-path')
out = _run(cmd)
return [s.split() for s in salt.utils.itertools.split(out['stdout'], '\n')]
def uninstall(*pkgs):
'''
Erases a package from the current nix profile. Nix uninstalls work differently than other package managers, and the symlinks in the
profile are removed, while the actual package remains. There is also a ``nix.purge`` function, to clear the package cache of unused
packages.
:type pkgs: list(str)
:param pkgs:
List, single package to uninstall
:return: Packages that have been uninstalled
:rtype: list(str)
.. code-block:: bash
salt '*' nix.uninstall pkg1 [pkg2 ...]
'''
cmd = _quietnix()
cmd.append('--uninstall')
cmd.extend(pkgs)
out = _run(cmd)
fmtout = out['stderr'].splitlines(), 'uninstalling'
return [_strip_quotes(s.split()[1])
for s in out['stderr'].splitlines()
if s.startswith('uninstalling')]
def collect_garbage():
'''
Completely removed all currently 'uninstalled' packages in the nix store.
Tells the user how many store paths were removed and how much space was freed.
:return: How much space was freed and how many derivations were removed
:rtype: str
.. warning::
This is a destructive action on the nix store.
.. code-block:: bash
salt '*' nix.collect_garbage
'''
cmd = _nix_collect_garbage()
cmd.append('--delete-old')
out = _run(cmd)
return out['stdout'].splitlines()
|
saltstack/salt
|
salt/modules/nix.py
|
upgrade
|
python
|
def upgrade(*pkgs):
'''
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: bash
salt '*' nix.update
salt '*' nix.update pkgs=one,two
'''
cmd = _quietnix()
cmd.append('--upgrade')
cmd.extend(pkgs)
out = _run(cmd)
upgrades = [_format_upgrade(s.split(maxsplit=1)[1])
for s in out['stderr'].splitlines()
if s.startswith('upgrading')]
return [[_strip_quotes(s_) for s_ in s]
for s in upgrades]
|
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: bash
salt '*' nix.update
salt '*' nix.update pkgs=one,two
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nix.py#L113-L140
|
[
"def _run(cmd):\n '''\n Just a convenience function for ``__salt__['cmd.run_all'](cmd)``\n '''\n return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})\n",
"def _quietnix():\n '''\n nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to\n only show changes.\n '''\n p = _nix_env()\n p.append('--no-build-output')\n return p\n"
] |
# -*- coding: utf-8 -*-
'''
Work with Nix packages
======================
.. versionadded:: 2017.7.0
Does not require the machine to be Nixos, just have Nix installed and available
to use for the user running this command. Their profile must be located in
their home, under ``$HOME/.nix-profile/``, and the nix store, unless specially
set up, should be in ``/nix``. To easily use this with multiple users or a root
user, set up the `nix-daemon`_.
This module exposes most of the common nix operations. Currently not meant to be run as a ``pkg`` module, but explicitly as ``nix.*``.
For more information on nix, see the `nix documentation`_.
.. _`nix documentation`: https://nixos.org/nix/manual/
.. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import itertools
import os
import salt.utils.itertools
import salt.utils.path
from salt.ext.six.moves import zip
logger = logging.getLogger(__name__)
def __virtual__():
'''
This only works if we have access to nix-env
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
if salt.utils.path.which(os.path.join(nixhome, 'nix-env')) and salt.utils.path.which(os.path.join(nixhome, 'nix-collect-garbage')):
return True
else:
return (False, "The `nix` binaries required cannot be found or are not installed. (`nix-store` and `nix-env`)")
def _run(cmd):
'''
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
'''
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})
def _nix_env():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-env')]
def _nix_collect_garbage():
'''
Make sure we get the right nix-store, too.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-collect-garbage')]
def _quietnix():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
p = _nix_env()
p.append('--no-build-output')
return p
def _zip_flatten(x, ys):
'''
intersperse x into ys, with an extra element at the beginning.
'''
return itertools.chain.from_iterable(
zip(itertools.repeat(x), ys))
def _output_format(out,
operation):
'''
gets a list of all the packages that were affected by ``operation``, splits it up (there can be multiple packages on a line), and then
flattens that list. We make it to a list for easier parsing.
'''
return [s.split()[1:] for s in out
if s.startswith(operation)]
def _format_upgrade(s):
'''
split the ``upgrade`` responses on ``' to '``
'''
return s.split(' to ')
def _strip_quotes(s):
'''
nix likes to quote itself in a backtick and a single quote. This just strips those.
'''
return s.strip("'`")
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
:rtype: list(str)
.. code-block:: bash
salt '*' nix.install package [package2 ...]
salt '*' nix.install attributes=True attr.name [attr.name2 ...]
'''
attributes = kwargs.get('attributes', False)
if not pkgs:
return "Plese specify a package or packages to upgrade"
cmd = _quietnix()
cmd.append('--install')
if kwargs.get('attributes', False):
cmd.extend(_zip_flatten('--attr', pkgs))
else:
cmd.extend(pkgs)
out = _run(cmd)
installs = list(itertools.chain.from_iterable(
[s.split()[1:] for s in out['stderr'].splitlines()
if s.startswith('installing')]
))
return [_strip_quotes(s) for s in installs]
def list_pkgs(installed=True,
attributes=True):
'''
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the packages when listing all packages.
Default: True
:return: Packages installed or available, along with their attributes.
:rtype: list(list(str))
.. code-block:: bash
salt '*' nix.list_pkgs
salt '*' nix.list_pkgs installed=False
'''
# We don't use -Q here, as it obfuscates the attribute names on full package listings.
cmd = _nix_env()
cmd.append('--query')
if installed:
# explicitly add this option for consistency, it's normally the default
cmd.append('--installed')
if not installed:
cmd.append('--available')
# We only show attributes if we're not doing an `installed` run.
# The output of `nix-env -qaP` and `nix-env -qP` are vastly different:
# `nix-env -qaP` returns a list such as 'attr.path name-version'
# `nix-env -qP` returns a list of 'installOrder name-version'
# Install order is useful to unambiguously select packages on a single
# machine, but on more than one it can be a bad thing to specify.
if attributes:
cmd.append('--attr-path')
out = _run(cmd)
return [s.split() for s in salt.utils.itertools.split(out['stdout'], '\n')]
def uninstall(*pkgs):
'''
Erases a package from the current nix profile. Nix uninstalls work differently than other package managers, and the symlinks in the
profile are removed, while the actual package remains. There is also a ``nix.purge`` function, to clear the package cache of unused
packages.
:type pkgs: list(str)
:param pkgs:
List, single package to uninstall
:return: Packages that have been uninstalled
:rtype: list(str)
.. code-block:: bash
salt '*' nix.uninstall pkg1 [pkg2 ...]
'''
cmd = _quietnix()
cmd.append('--uninstall')
cmd.extend(pkgs)
out = _run(cmd)
fmtout = out['stderr'].splitlines(), 'uninstalling'
return [_strip_quotes(s.split()[1])
for s in out['stderr'].splitlines()
if s.startswith('uninstalling')]
def collect_garbage():
'''
Completely removed all currently 'uninstalled' packages in the nix store.
Tells the user how many store paths were removed and how much space was freed.
:return: How much space was freed and how many derivations were removed
:rtype: str
.. warning::
This is a destructive action on the nix store.
.. code-block:: bash
salt '*' nix.collect_garbage
'''
cmd = _nix_collect_garbage()
cmd.append('--delete-old')
out = _run(cmd)
return out['stdout'].splitlines()
|
saltstack/salt
|
salt/modules/nix.py
|
install
|
python
|
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
:rtype: list(str)
.. code-block:: bash
salt '*' nix.install package [package2 ...]
salt '*' nix.install attributes=True attr.name [attr.name2 ...]
'''
attributes = kwargs.get('attributes', False)
if not pkgs:
return "Plese specify a package or packages to upgrade"
cmd = _quietnix()
cmd.append('--install')
if kwargs.get('attributes', False):
cmd.extend(_zip_flatten('--attr', pkgs))
else:
cmd.extend(pkgs)
out = _run(cmd)
installs = list(itertools.chain.from_iterable(
[s.split()[1:] for s in out['stderr'].splitlines()
if s.startswith('installing')]
))
return [_strip_quotes(s) for s in installs]
|
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
:rtype: list(str)
.. code-block:: bash
salt '*' nix.install package [package2 ...]
salt '*' nix.install attributes=True attr.name [attr.name2 ...]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nix.py#L143-L183
|
[
"def _run(cmd):\n '''\n Just a convenience function for ``__salt__['cmd.run_all'](cmd)``\n '''\n return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})\n",
"def _quietnix():\n '''\n nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to\n only show changes.\n '''\n p = _nix_env()\n p.append('--no-build-output')\n return p\n",
"def _zip_flatten(x, ys):\n '''\n intersperse x into ys, with an extra element at the beginning.\n '''\n return itertools.chain.from_iterable(\n zip(itertools.repeat(x), ys))\n"
] |
# -*- coding: utf-8 -*-
'''
Work with Nix packages
======================
.. versionadded:: 2017.7.0
Does not require the machine to be Nixos, just have Nix installed and available
to use for the user running this command. Their profile must be located in
their home, under ``$HOME/.nix-profile/``, and the nix store, unless specially
set up, should be in ``/nix``. To easily use this with multiple users or a root
user, set up the `nix-daemon`_.
This module exposes most of the common nix operations. Currently not meant to be run as a ``pkg`` module, but explicitly as ``nix.*``.
For more information on nix, see the `nix documentation`_.
.. _`nix documentation`: https://nixos.org/nix/manual/
.. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import itertools
import os
import salt.utils.itertools
import salt.utils.path
from salt.ext.six.moves import zip
logger = logging.getLogger(__name__)
def __virtual__():
'''
This only works if we have access to nix-env
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
if salt.utils.path.which(os.path.join(nixhome, 'nix-env')) and salt.utils.path.which(os.path.join(nixhome, 'nix-collect-garbage')):
return True
else:
return (False, "The `nix` binaries required cannot be found or are not installed. (`nix-store` and `nix-env`)")
def _run(cmd):
'''
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
'''
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})
def _nix_env():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-env')]
def _nix_collect_garbage():
'''
Make sure we get the right nix-store, too.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-collect-garbage')]
def _quietnix():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
p = _nix_env()
p.append('--no-build-output')
return p
def _zip_flatten(x, ys):
'''
intersperse x into ys, with an extra element at the beginning.
'''
return itertools.chain.from_iterable(
zip(itertools.repeat(x), ys))
def _output_format(out,
operation):
'''
gets a list of all the packages that were affected by ``operation``, splits it up (there can be multiple packages on a line), and then
flattens that list. We make it to a list for easier parsing.
'''
return [s.split()[1:] for s in out
if s.startswith(operation)]
def _format_upgrade(s):
'''
split the ``upgrade`` responses on ``' to '``
'''
return s.split(' to ')
def _strip_quotes(s):
'''
nix likes to quote itself in a backtick and a single quote. This just strips those.
'''
return s.strip("'`")
def upgrade(*pkgs):
'''
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: bash
salt '*' nix.update
salt '*' nix.update pkgs=one,two
'''
cmd = _quietnix()
cmd.append('--upgrade')
cmd.extend(pkgs)
out = _run(cmd)
upgrades = [_format_upgrade(s.split(maxsplit=1)[1])
for s in out['stderr'].splitlines()
if s.startswith('upgrading')]
return [[_strip_quotes(s_) for s_ in s]
for s in upgrades]
def list_pkgs(installed=True,
attributes=True):
'''
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the packages when listing all packages.
Default: True
:return: Packages installed or available, along with their attributes.
:rtype: list(list(str))
.. code-block:: bash
salt '*' nix.list_pkgs
salt '*' nix.list_pkgs installed=False
'''
# We don't use -Q here, as it obfuscates the attribute names on full package listings.
cmd = _nix_env()
cmd.append('--query')
if installed:
# explicitly add this option for consistency, it's normally the default
cmd.append('--installed')
if not installed:
cmd.append('--available')
# We only show attributes if we're not doing an `installed` run.
# The output of `nix-env -qaP` and `nix-env -qP` are vastly different:
# `nix-env -qaP` returns a list such as 'attr.path name-version'
# `nix-env -qP` returns a list of 'installOrder name-version'
# Install order is useful to unambiguously select packages on a single
# machine, but on more than one it can be a bad thing to specify.
if attributes:
cmd.append('--attr-path')
out = _run(cmd)
return [s.split() for s in salt.utils.itertools.split(out['stdout'], '\n')]
def uninstall(*pkgs):
'''
Erases a package from the current nix profile. Nix uninstalls work differently than other package managers, and the symlinks in the
profile are removed, while the actual package remains. There is also a ``nix.purge`` function, to clear the package cache of unused
packages.
:type pkgs: list(str)
:param pkgs:
List, single package to uninstall
:return: Packages that have been uninstalled
:rtype: list(str)
.. code-block:: bash
salt '*' nix.uninstall pkg1 [pkg2 ...]
'''
cmd = _quietnix()
cmd.append('--uninstall')
cmd.extend(pkgs)
out = _run(cmd)
fmtout = out['stderr'].splitlines(), 'uninstalling'
return [_strip_quotes(s.split()[1])
for s in out['stderr'].splitlines()
if s.startswith('uninstalling')]
def collect_garbage():
'''
Completely removed all currently 'uninstalled' packages in the nix store.
Tells the user how many store paths were removed and how much space was freed.
:return: How much space was freed and how many derivations were removed
:rtype: str
.. warning::
This is a destructive action on the nix store.
.. code-block:: bash
salt '*' nix.collect_garbage
'''
cmd = _nix_collect_garbage()
cmd.append('--delete-old')
out = _run(cmd)
return out['stdout'].splitlines()
|
saltstack/salt
|
salt/modules/nix.py
|
list_pkgs
|
python
|
def list_pkgs(installed=True,
attributes=True):
'''
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the packages when listing all packages.
Default: True
:return: Packages installed or available, along with their attributes.
:rtype: list(list(str))
.. code-block:: bash
salt '*' nix.list_pkgs
salt '*' nix.list_pkgs installed=False
'''
# We don't use -Q here, as it obfuscates the attribute names on full package listings.
cmd = _nix_env()
cmd.append('--query')
if installed:
# explicitly add this option for consistency, it's normally the default
cmd.append('--installed')
if not installed:
cmd.append('--available')
# We only show attributes if we're not doing an `installed` run.
# The output of `nix-env -qaP` and `nix-env -qP` are vastly different:
# `nix-env -qaP` returns a list such as 'attr.path name-version'
# `nix-env -qP` returns a list of 'installOrder name-version'
# Install order is useful to unambiguously select packages on a single
# machine, but on more than one it can be a bad thing to specify.
if attributes:
cmd.append('--attr-path')
out = _run(cmd)
return [s.split() for s in salt.utils.itertools.split(out['stdout'], '\n')]
|
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the packages when listing all packages.
Default: True
:return: Packages installed or available, along with their attributes.
:rtype: list(list(str))
.. code-block:: bash
salt '*' nix.list_pkgs
salt '*' nix.list_pkgs installed=False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nix.py#L186-L228
|
[
"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 _run(cmd):\n '''\n Just a convenience function for ``__salt__['cmd.run_all'](cmd)``\n '''\n return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})\n",
"def _nix_env():\n '''\n nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to\n only show changes.\n '''\n nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')\n return [os.path.join(nixhome, 'nix-env')]\n"
] |
# -*- coding: utf-8 -*-
'''
Work with Nix packages
======================
.. versionadded:: 2017.7.0
Does not require the machine to be Nixos, just have Nix installed and available
to use for the user running this command. Their profile must be located in
their home, under ``$HOME/.nix-profile/``, and the nix store, unless specially
set up, should be in ``/nix``. To easily use this with multiple users or a root
user, set up the `nix-daemon`_.
This module exposes most of the common nix operations. Currently not meant to be run as a ``pkg`` module, but explicitly as ``nix.*``.
For more information on nix, see the `nix documentation`_.
.. _`nix documentation`: https://nixos.org/nix/manual/
.. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import itertools
import os
import salt.utils.itertools
import salt.utils.path
from salt.ext.six.moves import zip
logger = logging.getLogger(__name__)
def __virtual__():
'''
This only works if we have access to nix-env
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
if salt.utils.path.which(os.path.join(nixhome, 'nix-env')) and salt.utils.path.which(os.path.join(nixhome, 'nix-collect-garbage')):
return True
else:
return (False, "The `nix` binaries required cannot be found or are not installed. (`nix-store` and `nix-env`)")
def _run(cmd):
'''
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
'''
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})
def _nix_env():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-env')]
def _nix_collect_garbage():
'''
Make sure we get the right nix-store, too.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-collect-garbage')]
def _quietnix():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
p = _nix_env()
p.append('--no-build-output')
return p
def _zip_flatten(x, ys):
'''
intersperse x into ys, with an extra element at the beginning.
'''
return itertools.chain.from_iterable(
zip(itertools.repeat(x), ys))
def _output_format(out,
operation):
'''
gets a list of all the packages that were affected by ``operation``, splits it up (there can be multiple packages on a line), and then
flattens that list. We make it to a list for easier parsing.
'''
return [s.split()[1:] for s in out
if s.startswith(operation)]
def _format_upgrade(s):
'''
split the ``upgrade`` responses on ``' to '``
'''
return s.split(' to ')
def _strip_quotes(s):
'''
nix likes to quote itself in a backtick and a single quote. This just strips those.
'''
return s.strip("'`")
def upgrade(*pkgs):
'''
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: bash
salt '*' nix.update
salt '*' nix.update pkgs=one,two
'''
cmd = _quietnix()
cmd.append('--upgrade')
cmd.extend(pkgs)
out = _run(cmd)
upgrades = [_format_upgrade(s.split(maxsplit=1)[1])
for s in out['stderr'].splitlines()
if s.startswith('upgrading')]
return [[_strip_quotes(s_) for s_ in s]
for s in upgrades]
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
:rtype: list(str)
.. code-block:: bash
salt '*' nix.install package [package2 ...]
salt '*' nix.install attributes=True attr.name [attr.name2 ...]
'''
attributes = kwargs.get('attributes', False)
if not pkgs:
return "Plese specify a package or packages to upgrade"
cmd = _quietnix()
cmd.append('--install')
if kwargs.get('attributes', False):
cmd.extend(_zip_flatten('--attr', pkgs))
else:
cmd.extend(pkgs)
out = _run(cmd)
installs = list(itertools.chain.from_iterable(
[s.split()[1:] for s in out['stderr'].splitlines()
if s.startswith('installing')]
))
return [_strip_quotes(s) for s in installs]
def uninstall(*pkgs):
'''
Erases a package from the current nix profile. Nix uninstalls work differently than other package managers, and the symlinks in the
profile are removed, while the actual package remains. There is also a ``nix.purge`` function, to clear the package cache of unused
packages.
:type pkgs: list(str)
:param pkgs:
List, single package to uninstall
:return: Packages that have been uninstalled
:rtype: list(str)
.. code-block:: bash
salt '*' nix.uninstall pkg1 [pkg2 ...]
'''
cmd = _quietnix()
cmd.append('--uninstall')
cmd.extend(pkgs)
out = _run(cmd)
fmtout = out['stderr'].splitlines(), 'uninstalling'
return [_strip_quotes(s.split()[1])
for s in out['stderr'].splitlines()
if s.startswith('uninstalling')]
def collect_garbage():
'''
Completely removed all currently 'uninstalled' packages in the nix store.
Tells the user how many store paths were removed and how much space was freed.
:return: How much space was freed and how many derivations were removed
:rtype: str
.. warning::
This is a destructive action on the nix store.
.. code-block:: bash
salt '*' nix.collect_garbage
'''
cmd = _nix_collect_garbage()
cmd.append('--delete-old')
out = _run(cmd)
return out['stdout'].splitlines()
|
saltstack/salt
|
salt/modules/nix.py
|
uninstall
|
python
|
def uninstall(*pkgs):
'''
Erases a package from the current nix profile. Nix uninstalls work differently than other package managers, and the symlinks in the
profile are removed, while the actual package remains. There is also a ``nix.purge`` function, to clear the package cache of unused
packages.
:type pkgs: list(str)
:param pkgs:
List, single package to uninstall
:return: Packages that have been uninstalled
:rtype: list(str)
.. code-block:: bash
salt '*' nix.uninstall pkg1 [pkg2 ...]
'''
cmd = _quietnix()
cmd.append('--uninstall')
cmd.extend(pkgs)
out = _run(cmd)
fmtout = out['stderr'].splitlines(), 'uninstalling'
return [_strip_quotes(s.split()[1])
for s in out['stderr'].splitlines()
if s.startswith('uninstalling')]
|
Erases a package from the current nix profile. Nix uninstalls work differently than other package managers, and the symlinks in the
profile are removed, while the actual package remains. There is also a ``nix.purge`` function, to clear the package cache of unused
packages.
:type pkgs: list(str)
:param pkgs:
List, single package to uninstall
:return: Packages that have been uninstalled
:rtype: list(str)
.. code-block:: bash
salt '*' nix.uninstall pkg1 [pkg2 ...]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nix.py#L231-L259
|
[
"def _run(cmd):\n '''\n Just a convenience function for ``__salt__['cmd.run_all'](cmd)``\n '''\n return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})\n",
"def _quietnix():\n '''\n nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to\n only show changes.\n '''\n p = _nix_env()\n p.append('--no-build-output')\n return p\n"
] |
# -*- coding: utf-8 -*-
'''
Work with Nix packages
======================
.. versionadded:: 2017.7.0
Does not require the machine to be Nixos, just have Nix installed and available
to use for the user running this command. Their profile must be located in
their home, under ``$HOME/.nix-profile/``, and the nix store, unless specially
set up, should be in ``/nix``. To easily use this with multiple users or a root
user, set up the `nix-daemon`_.
This module exposes most of the common nix operations. Currently not meant to be run as a ``pkg`` module, but explicitly as ``nix.*``.
For more information on nix, see the `nix documentation`_.
.. _`nix documentation`: https://nixos.org/nix/manual/
.. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import itertools
import os
import salt.utils.itertools
import salt.utils.path
from salt.ext.six.moves import zip
logger = logging.getLogger(__name__)
def __virtual__():
'''
This only works if we have access to nix-env
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
if salt.utils.path.which(os.path.join(nixhome, 'nix-env')) and salt.utils.path.which(os.path.join(nixhome, 'nix-collect-garbage')):
return True
else:
return (False, "The `nix` binaries required cannot be found or are not installed. (`nix-store` and `nix-env`)")
def _run(cmd):
'''
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
'''
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})
def _nix_env():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-env')]
def _nix_collect_garbage():
'''
Make sure we get the right nix-store, too.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-collect-garbage')]
def _quietnix():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
p = _nix_env()
p.append('--no-build-output')
return p
def _zip_flatten(x, ys):
'''
intersperse x into ys, with an extra element at the beginning.
'''
return itertools.chain.from_iterable(
zip(itertools.repeat(x), ys))
def _output_format(out,
operation):
'''
gets a list of all the packages that were affected by ``operation``, splits it up (there can be multiple packages on a line), and then
flattens that list. We make it to a list for easier parsing.
'''
return [s.split()[1:] for s in out
if s.startswith(operation)]
def _format_upgrade(s):
'''
split the ``upgrade`` responses on ``' to '``
'''
return s.split(' to ')
def _strip_quotes(s):
'''
nix likes to quote itself in a backtick and a single quote. This just strips those.
'''
return s.strip("'`")
def upgrade(*pkgs):
'''
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: bash
salt '*' nix.update
salt '*' nix.update pkgs=one,two
'''
cmd = _quietnix()
cmd.append('--upgrade')
cmd.extend(pkgs)
out = _run(cmd)
upgrades = [_format_upgrade(s.split(maxsplit=1)[1])
for s in out['stderr'].splitlines()
if s.startswith('upgrading')]
return [[_strip_quotes(s_) for s_ in s]
for s in upgrades]
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
:rtype: list(str)
.. code-block:: bash
salt '*' nix.install package [package2 ...]
salt '*' nix.install attributes=True attr.name [attr.name2 ...]
'''
attributes = kwargs.get('attributes', False)
if not pkgs:
return "Plese specify a package or packages to upgrade"
cmd = _quietnix()
cmd.append('--install')
if kwargs.get('attributes', False):
cmd.extend(_zip_flatten('--attr', pkgs))
else:
cmd.extend(pkgs)
out = _run(cmd)
installs = list(itertools.chain.from_iterable(
[s.split()[1:] for s in out['stderr'].splitlines()
if s.startswith('installing')]
))
return [_strip_quotes(s) for s in installs]
def list_pkgs(installed=True,
attributes=True):
'''
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the packages when listing all packages.
Default: True
:return: Packages installed or available, along with their attributes.
:rtype: list(list(str))
.. code-block:: bash
salt '*' nix.list_pkgs
salt '*' nix.list_pkgs installed=False
'''
# We don't use -Q here, as it obfuscates the attribute names on full package listings.
cmd = _nix_env()
cmd.append('--query')
if installed:
# explicitly add this option for consistency, it's normally the default
cmd.append('--installed')
if not installed:
cmd.append('--available')
# We only show attributes if we're not doing an `installed` run.
# The output of `nix-env -qaP` and `nix-env -qP` are vastly different:
# `nix-env -qaP` returns a list such as 'attr.path name-version'
# `nix-env -qP` returns a list of 'installOrder name-version'
# Install order is useful to unambiguously select packages on a single
# machine, but on more than one it can be a bad thing to specify.
if attributes:
cmd.append('--attr-path')
out = _run(cmd)
return [s.split() for s in salt.utils.itertools.split(out['stdout'], '\n')]
def collect_garbage():
'''
Completely removed all currently 'uninstalled' packages in the nix store.
Tells the user how many store paths were removed and how much space was freed.
:return: How much space was freed and how many derivations were removed
:rtype: str
.. warning::
This is a destructive action on the nix store.
.. code-block:: bash
salt '*' nix.collect_garbage
'''
cmd = _nix_collect_garbage()
cmd.append('--delete-old')
out = _run(cmd)
return out['stdout'].splitlines()
|
saltstack/salt
|
salt/modules/nix.py
|
collect_garbage
|
python
|
def collect_garbage():
'''
Completely removed all currently 'uninstalled' packages in the nix store.
Tells the user how many store paths were removed and how much space was freed.
:return: How much space was freed and how many derivations were removed
:rtype: str
.. warning::
This is a destructive action on the nix store.
.. code-block:: bash
salt '*' nix.collect_garbage
'''
cmd = _nix_collect_garbage()
cmd.append('--delete-old')
out = _run(cmd)
return out['stdout'].splitlines()
|
Completely removed all currently 'uninstalled' packages in the nix store.
Tells the user how many store paths were removed and how much space was freed.
:return: How much space was freed and how many derivations were removed
:rtype: str
.. warning::
This is a destructive action on the nix store.
.. code-block:: bash
salt '*' nix.collect_garbage
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nix.py#L262-L283
|
[
"def _run(cmd):\n '''\n Just a convenience function for ``__salt__['cmd.run_all'](cmd)``\n '''\n return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})\n",
"def _nix_collect_garbage():\n '''\n Make sure we get the right nix-store, too.\n '''\n nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')\n return [os.path.join(nixhome, 'nix-collect-garbage')]\n"
] |
# -*- coding: utf-8 -*-
'''
Work with Nix packages
======================
.. versionadded:: 2017.7.0
Does not require the machine to be Nixos, just have Nix installed and available
to use for the user running this command. Their profile must be located in
their home, under ``$HOME/.nix-profile/``, and the nix store, unless specially
set up, should be in ``/nix``. To easily use this with multiple users or a root
user, set up the `nix-daemon`_.
This module exposes most of the common nix operations. Currently not meant to be run as a ``pkg`` module, but explicitly as ``nix.*``.
For more information on nix, see the `nix documentation`_.
.. _`nix documentation`: https://nixos.org/nix/manual/
.. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import itertools
import os
import salt.utils.itertools
import salt.utils.path
from salt.ext.six.moves import zip
logger = logging.getLogger(__name__)
def __virtual__():
'''
This only works if we have access to nix-env
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
if salt.utils.path.which(os.path.join(nixhome, 'nix-env')) and salt.utils.path.which(os.path.join(nixhome, 'nix-collect-garbage')):
return True
else:
return (False, "The `nix` binaries required cannot be found or are not installed. (`nix-store` and `nix-env`)")
def _run(cmd):
'''
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
'''
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})
def _nix_env():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-env')]
def _nix_collect_garbage():
'''
Make sure we get the right nix-store, too.
'''
nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')
return [os.path.join(nixhome, 'nix-collect-garbage')]
def _quietnix():
'''
nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to
only show changes.
'''
p = _nix_env()
p.append('--no-build-output')
return p
def _zip_flatten(x, ys):
'''
intersperse x into ys, with an extra element at the beginning.
'''
return itertools.chain.from_iterable(
zip(itertools.repeat(x), ys))
def _output_format(out,
operation):
'''
gets a list of all the packages that were affected by ``operation``, splits it up (there can be multiple packages on a line), and then
flattens that list. We make it to a list for easier parsing.
'''
return [s.split()[1:] for s in out
if s.startswith(operation)]
def _format_upgrade(s):
'''
split the ``upgrade`` responses on ``' to '``
'''
return s.split(' to ')
def _strip_quotes(s):
'''
nix likes to quote itself in a backtick and a single quote. This just strips those.
'''
return s.strip("'`")
def upgrade(*pkgs):
'''
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: bash
salt '*' nix.update
salt '*' nix.update pkgs=one,two
'''
cmd = _quietnix()
cmd.append('--upgrade')
cmd.extend(pkgs)
out = _run(cmd)
upgrades = [_format_upgrade(s.split(maxsplit=1)[1])
for s in out['stderr'].splitlines()
if s.startswith('upgrading')]
return [[_strip_quotes(s_) for s_ in s]
for s in upgrades]
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
:rtype: list(str)
.. code-block:: bash
salt '*' nix.install package [package2 ...]
salt '*' nix.install attributes=True attr.name [attr.name2 ...]
'''
attributes = kwargs.get('attributes', False)
if not pkgs:
return "Plese specify a package or packages to upgrade"
cmd = _quietnix()
cmd.append('--install')
if kwargs.get('attributes', False):
cmd.extend(_zip_flatten('--attr', pkgs))
else:
cmd.extend(pkgs)
out = _run(cmd)
installs = list(itertools.chain.from_iterable(
[s.split()[1:] for s in out['stderr'].splitlines()
if s.startswith('installing')]
))
return [_strip_quotes(s) for s in installs]
def list_pkgs(installed=True,
attributes=True):
'''
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the packages when listing all packages.
Default: True
:return: Packages installed or available, along with their attributes.
:rtype: list(list(str))
.. code-block:: bash
salt '*' nix.list_pkgs
salt '*' nix.list_pkgs installed=False
'''
# We don't use -Q here, as it obfuscates the attribute names on full package listings.
cmd = _nix_env()
cmd.append('--query')
if installed:
# explicitly add this option for consistency, it's normally the default
cmd.append('--installed')
if not installed:
cmd.append('--available')
# We only show attributes if we're not doing an `installed` run.
# The output of `nix-env -qaP` and `nix-env -qP` are vastly different:
# `nix-env -qaP` returns a list such as 'attr.path name-version'
# `nix-env -qP` returns a list of 'installOrder name-version'
# Install order is useful to unambiguously select packages on a single
# machine, but on more than one it can be a bad thing to specify.
if attributes:
cmd.append('--attr-path')
out = _run(cmd)
return [s.split() for s in salt.utils.itertools.split(out['stdout'], '\n')]
def uninstall(*pkgs):
'''
Erases a package from the current nix profile. Nix uninstalls work differently than other package managers, and the symlinks in the
profile are removed, while the actual package remains. There is also a ``nix.purge`` function, to clear the package cache of unused
packages.
:type pkgs: list(str)
:param pkgs:
List, single package to uninstall
:return: Packages that have been uninstalled
:rtype: list(str)
.. code-block:: bash
salt '*' nix.uninstall pkg1 [pkg2 ...]
'''
cmd = _quietnix()
cmd.append('--uninstall')
cmd.extend(pkgs)
out = _run(cmd)
fmtout = out['stderr'].splitlines(), 'uninstalling'
return [_strip_quotes(s.split()[1])
for s in out['stderr'].splitlines()
if s.startswith('uninstalling')]
|
saltstack/salt
|
salt/pillar/rethinkdb_pillar.py
|
ext_pillar
|
python
|
def ext_pillar(minion_id,
pillar,
table='pillar',
id_field=None,
field=None,
pillar_key=None):
'''
Collect minion external pillars from a RethinkDB database
Arguments:
* `table`: The RethinkDB table containing external pillar information.
Defaults to ``'pillar'``
* `id_field`: Field in document containing the minion id.
If blank then we assume the table index matches minion ids
* `field`: Specific field in the document used for pillar data, if blank
then the entire document will be used
* `pillar_key`: The salt-master will nest found external pillars under
this key before merging into the minion pillars. If blank, external
pillars will be merged at top level
'''
host = __opts__['rethinkdb.host']
port = __opts__['rethinkdb.port']
database = __opts__['rethinkdb.database']
username = __opts__['rethinkdb.username']
password = __opts__['rethinkdb.password']
log.debug('Connecting to %s:%s as user \'%s\' for RethinkDB ext_pillar',
host, port, username)
# Connect to the database
conn = rethinkdb.connect(host=host,
port=port,
db=database,
user=username,
password=password)
data = None
try:
if id_field:
log.debug('ext_pillar.rethinkdb: looking up pillar. '
'table: %s, field: %s, minion: %s',
table, id_field, minion_id)
if field:
data = rethinkdb.table(table).filter(
{id_field: minion_id}).pluck(field).run(conn)
else:
data = rethinkdb.table(table).filter(
{id_field: minion_id}).run(conn)
else:
log.debug('ext_pillar.rethinkdb: looking up pillar. '
'table: %s, field: id, minion: %s',
table, minion_id)
if field:
data = rethinkdb.table(table).get(minion_id).pluck(field).run(
conn)
else:
data = rethinkdb.table(table).get(minion_id).run(conn)
finally:
if conn.is_open():
conn.close()
if data.items:
# Return nothing if multiple documents are found for a minion
if len(data.items) > 1:
log.error('ext_pillar.rethinkdb: ambiguous documents found for '
'minion %s', minion_id)
return {}
else:
result = data.items.pop()
if pillar_key:
return {pillar_key: result}
return result
else:
# No document found in the database
log.debug('ext_pillar.rethinkdb: no document found')
return {}
|
Collect minion external pillars from a RethinkDB database
Arguments:
* `table`: The RethinkDB table containing external pillar information.
Defaults to ``'pillar'``
* `id_field`: Field in document containing the minion id.
If blank then we assume the table index matches minion ids
* `field`: Specific field in the document used for pillar data, if blank
then the entire document will be used
* `pillar_key`: The salt-master will nest found external pillars under
this key before merging into the minion pillars. If blank, external
pillars will be merged at top level
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/rethinkdb_pillar.py#L78-L163
| null |
# -*- coding: utf-8 -*-
'''
Provide external pillar data from RethinkDB
.. versionadded:: 2018.3.0
:depends: rethinkdb (on the salt-master)
salt master rethinkdb configuration
===================================
These variables must be configured in your master configuration file.
* ``rethinkdb.host`` - The RethinkDB server. Defaults to ``'salt'``
* ``rethinkdb.port`` - The port the RethinkDB server listens on.
Defaults to ``'28015'``
* ``rethinkdb.database`` - The database to connect to.
Defaults to ``'salt'``
* ``rethinkdb.username`` - The username for connecting to RethinkDB.
Defaults to ``''``
* ``rethinkdb.password`` - The password for connecting to RethinkDB.
Defaults to ``''``
salt-master ext_pillar configuration
====================================
The ext_pillar function arguments are given in single line dictionary notation.
.. code-block:: yaml
ext_pillar:
- rethinkdb: {table: ext_pillar, id_field: minion_id, field: pillar_root, pillar_key: external_pillar}
In the example above the following happens.
* The salt-master will look for external pillars in the 'ext_pillar' table
on the RethinkDB host
* The minion id will be matched against the 'minion_id' field
* Pillars will be retrieved from the nested field 'pillar_root'
* Found pillars will be merged inside a key called 'external_pillar'
Module Documentation
====================
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libraries
import logging
# Import 3rd party libraries
try:
import rethinkdb
HAS_RETHINKDB = True
except ImportError:
HAS_RETHINKDB = False
__virtualname__ = 'rethinkdb'
__opts__ = {
'rethinkdb.host': 'salt',
'rethinkdb.port': '28015',
'rethinkdb.database': 'salt',
'rethinkdb.username': None,
'rethinkdb.password': None
}
def __virtual__():
if not HAS_RETHINKDB:
return False
return True
# Configure logging
log = logging.getLogger(__name__)
|
saltstack/salt
|
salt/cli/support/localrunner.py
|
LocalRunner._proc_function
|
python
|
def _proc_function(self, fun, low, user, tag, jid, daemonize=True):
'''
Same as original _proc_function in AsyncClientMixin,
except it calls "low" without firing a print event.
'''
if daemonize and not salt.utils.platform.is_windows():
salt.log.setup.shutdown_multiprocessing_logging()
salt.utils.process.daemonize()
salt.log.setup.setup_multiprocessing_logging()
low['__jid__'] = jid
low['__user__'] = user
low['__tag__'] = tag
return self.low(fun, low, print_event=False, full_return=False)
|
Same as original _proc_function in AsyncClientMixin,
except it calls "low" without firing a print event.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/localrunner.py#L20-L34
| null |
class LocalRunner(salt.runner.Runner):
'''
Runner class that changes its default behaviour.
'''
|
saltstack/salt
|
salt/modules/puppet.py
|
run
|
python
|
def run(*args, **kwargs):
'''
Execute a puppet run and return a dict with the stderr, stdout,
return code, etc. The first positional argument given is checked as a
subcommand. Following positional arguments should be ordered with arguments
required by the subcommand first, followed by non-keyword arguments.
Tags are specified by a tag keyword and comma separated list of values. --
http://docs.puppetlabs.com/puppet/latest/reference/lang_tags.html
CLI Examples:
.. code-block:: bash
salt '*' puppet.run
salt '*' puppet.run tags=basefiles::edit,apache::server
salt '*' puppet.run agent onetime no-daemonize no-usecacheonfailure no-splay ignorecache
salt '*' puppet.run debug
salt '*' puppet.run apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
puppet = _Puppet()
# new args tuple to filter out agent/apply for _Puppet.arguments()
buildargs = ()
for arg in range(len(args)):
# based on puppet documentation action must come first. making the same
# assertion. need to ensure the list of supported cmds here matches
# those defined in _Puppet.arguments()
if args[arg] in ['agent', 'apply']:
puppet.subcmd = args[arg]
else:
buildargs += (args[arg],)
# args will exist as an empty list even if none have been provided
puppet.arguments(buildargs)
puppet.kwargs.update(salt.utils.args.clean_kwargs(**kwargs))
ret = __salt__['cmd.run_all'](repr(puppet), python_shell=True)
return ret
|
Execute a puppet run and return a dict with the stderr, stdout,
return code, etc. The first positional argument given is checked as a
subcommand. Following positional arguments should be ordered with arguments
required by the subcommand first, followed by non-keyword arguments.
Tags are specified by a tag keyword and comma separated list of values. --
http://docs.puppetlabs.com/puppet/latest/reference/lang_tags.html
CLI Examples:
.. code-block:: bash
salt '*' puppet.run
salt '*' puppet.run tags=basefiles::edit,apache::server
salt '*' puppet.run agent onetime no-daemonize no-usecacheonfailure no-splay ignorecache
salt '*' puppet.run debug
salt '*' puppet.run apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/puppet.py#L138-L175
|
[
"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 arguments(self, args=None):\n '''\n Read in arguments for the current subcommand. These are added to the\n cmd line without '--' appended. Any others are redirected as standard\n options with the double hyphen prefixed.\n '''\n # permits deleting elements rather than using slices\n args = args and list(args) or []\n\n # match against all known/supported subcmds\n if self.subcmd == 'apply':\n # apply subcommand requires a manifest file to execute\n self.subcmd_args = [args[0]]\n del args[0]\n\n if self.subcmd == 'agent':\n # no arguments are required\n args.extend([\n 'test'\n ])\n\n # finally do this after subcmd has been matched for all remaining args\n self.args = args\n"
] |
# -*- coding: utf-8 -*-
'''
Execute puppet routines
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
from distutils import version # pylint: disable=no-name-in-module
import logging
import os
import datetime
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.yaml
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if puppet is installed
'''
unavailable_exes = ', '.join(exe for exe in ('facter', 'puppet')
if salt.utils.path.which(exe) is None)
if unavailable_exes:
return (False,
('The puppet execution module cannot be loaded: '
'{0} unavailable.'.format(unavailable_exes)))
else:
return 'puppet'
def _format_fact(output):
try:
fact, value = output.split(' => ', 1)
value = value.strip()
except ValueError:
fact = None
value = None
return (fact, value)
class _Puppet(object):
'''
Puppet helper class. Used to format command for execution.
'''
def __init__(self):
'''
Setup a puppet instance, based on the premis that default usage is to
run 'puppet agent --test'. Configuration and run states are stored in
the default locations.
'''
self.subcmd = 'agent'
self.subcmd_args = [] # e.g. /a/b/manifest.pp
self.kwargs = {'color': 'false'} # e.g. --tags=apache::server
self.args = [] # e.g. --noop
if salt.utils.platform.is_windows():
self.vardir = 'C:\\ProgramData\\PuppetLabs\\puppet\\var'
self.rundir = 'C:\\ProgramData\\PuppetLabs\\puppet\\run'
self.confdir = 'C:\\ProgramData\\PuppetLabs\\puppet\\etc'
else:
self.puppet_version = __salt__['cmd.run']('puppet --version')
if 'Enterprise' in self.puppet_version:
self.vardir = '/var/opt/lib/pe-puppet'
self.rundir = '/var/opt/run/pe-puppet'
self.confdir = '/etc/puppetlabs/puppet'
elif self.puppet_version != [] and version.StrictVersion(self.puppet_version) >= version.StrictVersion('4.0.0'):
self.vardir = '/opt/puppetlabs/puppet/cache'
self.rundir = '/var/run/puppetlabs'
self.confdir = '/etc/puppetlabs/puppet'
else:
self.vardir = '/var/lib/puppet'
self.rundir = '/var/run/puppet'
self.confdir = '/etc/puppet'
self.disabled_lockfile = self.vardir + '/state/agent_disabled.lock'
self.run_lockfile = self.vardir + '/state/agent_catalog_run.lock'
self.agent_pidfile = self.rundir + '/agent.pid'
self.lastrunfile = self.vardir + '/state/last_run_summary.yaml'
def __repr__(self):
'''
Format the command string to executed using cmd.run_all.
'''
cmd = 'puppet {subcmd} --vardir {vardir} --confdir {confdir}'.format(
**self.__dict__
)
args = ' '.join(self.subcmd_args)
args += ''.join(
[' --{0}'.format(k) for k in self.args] # single spaces
)
args += ''.join([
' --{0} {1}'.format(k, v) for k, v in six.iteritems(self.kwargs)]
)
# Ensure that the puppet call will return 0 in case of exit code 2
if salt.utils.platform.is_windows():
return 'cmd /V:ON /c {0} {1} ^& if !ERRORLEVEL! EQU 2 (EXIT 0) ELSE (EXIT /B)'.format(cmd, args)
return '({0} {1}) || test $? -eq 2'.format(cmd, args)
def arguments(self, args=None):
'''
Read in arguments for the current subcommand. These are added to the
cmd line without '--' appended. Any others are redirected as standard
options with the double hyphen prefixed.
'''
# permits deleting elements rather than using slices
args = args and list(args) or []
# match against all known/supported subcmds
if self.subcmd == 'apply':
# apply subcommand requires a manifest file to execute
self.subcmd_args = [args[0]]
del args[0]
if self.subcmd == 'agent':
# no arguments are required
args.extend([
'test'
])
# finally do this after subcmd has been matched for all remaining args
self.args = args
def noop(*args, **kwargs):
'''
Execute a puppet noop run and return a dict with the stderr, stdout,
return code, etc. Usage is the same as for puppet.run.
CLI Example:
.. code-block:: bash
salt '*' puppet.noop
salt '*' puppet.noop tags=basefiles::edit,apache::server
salt '*' puppet.noop debug
salt '*' puppet.noop apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
args += ('noop',)
return run(*args, **kwargs)
def enable():
'''
.. versionadded:: 2014.7.0
Enable the puppet agent
CLI Example:
.. code-block:: bash
salt '*' puppet.enable
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
try:
os.remove(puppet.disabled_lockfile)
except (IOError, OSError) as exc:
msg = 'Failed to enable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
else:
return True
return False
def disable(message=None):
'''
.. versionadded:: 2014.7.0
Disable the puppet agent
message
.. versionadded:: 2015.5.2
Disable message to send to puppet
CLI Example:
.. code-block:: bash
salt '*' puppet.disable
salt '*' puppet.disable 'Disabled, contact XYZ before enabling'
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return False
else:
with salt.utils.files.fopen(puppet.disabled_lockfile, 'w') as lockfile:
try:
# Puppet chokes when no valid json is found
msg = '{{"disabled_message":"{0}"}}'.format(message) if message is not None else '{}'
lockfile.write(salt.utils.stringutils.to_str(msg))
lockfile.close()
return True
except (IOError, OSError) as exc:
msg = 'Failed to disable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
def status():
'''
.. versionadded:: 2014.7.0
Display puppet agent status
CLI Example:
.. code-block:: bash
salt '*' puppet.status
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return 'Administratively disabled'
if os.path.isfile(puppet.run_lockfile):
try:
with salt.utils.files.fopen(puppet.run_lockfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale lockfile'
else:
return 'Applying a catalog'
if os.path.isfile(puppet.agent_pidfile):
try:
with salt.utils.files.fopen(puppet.agent_pidfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale pidfile'
else:
return 'Idle daemon'
return 'Stopped'
def summary():
'''
.. versionadded:: 2014.7.0
Show a summary of the last puppet agent run
CLI Example:
.. code-block:: bash
salt '*' puppet.summary
'''
puppet = _Puppet()
try:
with salt.utils.files.fopen(puppet.lastrunfile, 'r') as fp_:
report = salt.utils.yaml.safe_load(fp_)
result = {}
if 'time' in report:
try:
result['last_run'] = datetime.datetime.fromtimestamp(
int(report['time']['last_run'])).isoformat()
except (TypeError, ValueError, KeyError):
result['last_run'] = 'invalid or missing timestamp'
result['time'] = {}
for key in ('total', 'config_retrieval'):
if key in report['time']:
result['time'][key] = report['time'][key]
if 'resources' in report:
result['resources'] = report['resources']
except salt.utils.yaml.YAMLError as exc:
raise CommandExecutionError(
'YAML error parsing puppet run summary: {0}'.format(exc)
)
except IOError as exc:
raise CommandExecutionError(
'Unable to read puppet run summary: {0}'.format(exc)
)
return result
def plugin_sync():
'''
Runs a plugin sync between the puppet master and agent
CLI Example:
.. code-block:: bash
salt '*' puppet.plugin_sync
'''
ret = __salt__['cmd.run']('puppet plugin download')
if not ret:
return ''
return ret
def facts(puppet=False):
'''
Run facter and return the results
CLI Example:
.. code-block:: bash
salt '*' puppet.facts
'''
ret = {}
opt_puppet = '--puppet' if puppet else ''
cmd_ret = __salt__['cmd.run_all']('facter {0}'.format(opt_puppet))
if cmd_ret['retcode'] != 0:
raise CommandExecutionError(cmd_ret['stderr'])
output = cmd_ret['stdout']
# Loop over the facter output and properly
# parse it into a nice dictionary for using
# elsewhere
for line in output.splitlines():
if not line:
continue
fact, value = _format_fact(line)
if not fact:
continue
ret[fact] = value
return ret
def fact(name, puppet=False):
'''
Run facter for a specific fact
CLI Example:
.. code-block:: bash
salt '*' puppet.fact kernel
'''
opt_puppet = '--puppet' if puppet else ''
ret = __salt__['cmd.run_all'](
'facter {0} {1}'.format(opt_puppet, name),
python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(ret['stderr'])
if not ret['stdout']:
return ''
return ret['stdout']
|
saltstack/salt
|
salt/modules/puppet.py
|
enable
|
python
|
def enable():
'''
.. versionadded:: 2014.7.0
Enable the puppet agent
CLI Example:
.. code-block:: bash
salt '*' puppet.enable
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
try:
os.remove(puppet.disabled_lockfile)
except (IOError, OSError) as exc:
msg = 'Failed to enable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
else:
return True
return False
|
.. versionadded:: 2014.7.0
Enable the puppet agent
CLI Example:
.. code-block:: bash
salt '*' puppet.enable
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/puppet.py#L196-L219
| null |
# -*- coding: utf-8 -*-
'''
Execute puppet routines
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
from distutils import version # pylint: disable=no-name-in-module
import logging
import os
import datetime
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.yaml
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if puppet is installed
'''
unavailable_exes = ', '.join(exe for exe in ('facter', 'puppet')
if salt.utils.path.which(exe) is None)
if unavailable_exes:
return (False,
('The puppet execution module cannot be loaded: '
'{0} unavailable.'.format(unavailable_exes)))
else:
return 'puppet'
def _format_fact(output):
try:
fact, value = output.split(' => ', 1)
value = value.strip()
except ValueError:
fact = None
value = None
return (fact, value)
class _Puppet(object):
'''
Puppet helper class. Used to format command for execution.
'''
def __init__(self):
'''
Setup a puppet instance, based on the premis that default usage is to
run 'puppet agent --test'. Configuration and run states are stored in
the default locations.
'''
self.subcmd = 'agent'
self.subcmd_args = [] # e.g. /a/b/manifest.pp
self.kwargs = {'color': 'false'} # e.g. --tags=apache::server
self.args = [] # e.g. --noop
if salt.utils.platform.is_windows():
self.vardir = 'C:\\ProgramData\\PuppetLabs\\puppet\\var'
self.rundir = 'C:\\ProgramData\\PuppetLabs\\puppet\\run'
self.confdir = 'C:\\ProgramData\\PuppetLabs\\puppet\\etc'
else:
self.puppet_version = __salt__['cmd.run']('puppet --version')
if 'Enterprise' in self.puppet_version:
self.vardir = '/var/opt/lib/pe-puppet'
self.rundir = '/var/opt/run/pe-puppet'
self.confdir = '/etc/puppetlabs/puppet'
elif self.puppet_version != [] and version.StrictVersion(self.puppet_version) >= version.StrictVersion('4.0.0'):
self.vardir = '/opt/puppetlabs/puppet/cache'
self.rundir = '/var/run/puppetlabs'
self.confdir = '/etc/puppetlabs/puppet'
else:
self.vardir = '/var/lib/puppet'
self.rundir = '/var/run/puppet'
self.confdir = '/etc/puppet'
self.disabled_lockfile = self.vardir + '/state/agent_disabled.lock'
self.run_lockfile = self.vardir + '/state/agent_catalog_run.lock'
self.agent_pidfile = self.rundir + '/agent.pid'
self.lastrunfile = self.vardir + '/state/last_run_summary.yaml'
def __repr__(self):
'''
Format the command string to executed using cmd.run_all.
'''
cmd = 'puppet {subcmd} --vardir {vardir} --confdir {confdir}'.format(
**self.__dict__
)
args = ' '.join(self.subcmd_args)
args += ''.join(
[' --{0}'.format(k) for k in self.args] # single spaces
)
args += ''.join([
' --{0} {1}'.format(k, v) for k, v in six.iteritems(self.kwargs)]
)
# Ensure that the puppet call will return 0 in case of exit code 2
if salt.utils.platform.is_windows():
return 'cmd /V:ON /c {0} {1} ^& if !ERRORLEVEL! EQU 2 (EXIT 0) ELSE (EXIT /B)'.format(cmd, args)
return '({0} {1}) || test $? -eq 2'.format(cmd, args)
def arguments(self, args=None):
'''
Read in arguments for the current subcommand. These are added to the
cmd line without '--' appended. Any others are redirected as standard
options with the double hyphen prefixed.
'''
# permits deleting elements rather than using slices
args = args and list(args) or []
# match against all known/supported subcmds
if self.subcmd == 'apply':
# apply subcommand requires a manifest file to execute
self.subcmd_args = [args[0]]
del args[0]
if self.subcmd == 'agent':
# no arguments are required
args.extend([
'test'
])
# finally do this after subcmd has been matched for all remaining args
self.args = args
def run(*args, **kwargs):
'''
Execute a puppet run and return a dict with the stderr, stdout,
return code, etc. The first positional argument given is checked as a
subcommand. Following positional arguments should be ordered with arguments
required by the subcommand first, followed by non-keyword arguments.
Tags are specified by a tag keyword and comma separated list of values. --
http://docs.puppetlabs.com/puppet/latest/reference/lang_tags.html
CLI Examples:
.. code-block:: bash
salt '*' puppet.run
salt '*' puppet.run tags=basefiles::edit,apache::server
salt '*' puppet.run agent onetime no-daemonize no-usecacheonfailure no-splay ignorecache
salt '*' puppet.run debug
salt '*' puppet.run apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
puppet = _Puppet()
# new args tuple to filter out agent/apply for _Puppet.arguments()
buildargs = ()
for arg in range(len(args)):
# based on puppet documentation action must come first. making the same
# assertion. need to ensure the list of supported cmds here matches
# those defined in _Puppet.arguments()
if args[arg] in ['agent', 'apply']:
puppet.subcmd = args[arg]
else:
buildargs += (args[arg],)
# args will exist as an empty list even if none have been provided
puppet.arguments(buildargs)
puppet.kwargs.update(salt.utils.args.clean_kwargs(**kwargs))
ret = __salt__['cmd.run_all'](repr(puppet), python_shell=True)
return ret
def noop(*args, **kwargs):
'''
Execute a puppet noop run and return a dict with the stderr, stdout,
return code, etc. Usage is the same as for puppet.run.
CLI Example:
.. code-block:: bash
salt '*' puppet.noop
salt '*' puppet.noop tags=basefiles::edit,apache::server
salt '*' puppet.noop debug
salt '*' puppet.noop apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
args += ('noop',)
return run(*args, **kwargs)
def disable(message=None):
'''
.. versionadded:: 2014.7.0
Disable the puppet agent
message
.. versionadded:: 2015.5.2
Disable message to send to puppet
CLI Example:
.. code-block:: bash
salt '*' puppet.disable
salt '*' puppet.disable 'Disabled, contact XYZ before enabling'
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return False
else:
with salt.utils.files.fopen(puppet.disabled_lockfile, 'w') as lockfile:
try:
# Puppet chokes when no valid json is found
msg = '{{"disabled_message":"{0}"}}'.format(message) if message is not None else '{}'
lockfile.write(salt.utils.stringutils.to_str(msg))
lockfile.close()
return True
except (IOError, OSError) as exc:
msg = 'Failed to disable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
def status():
'''
.. versionadded:: 2014.7.0
Display puppet agent status
CLI Example:
.. code-block:: bash
salt '*' puppet.status
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return 'Administratively disabled'
if os.path.isfile(puppet.run_lockfile):
try:
with salt.utils.files.fopen(puppet.run_lockfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale lockfile'
else:
return 'Applying a catalog'
if os.path.isfile(puppet.agent_pidfile):
try:
with salt.utils.files.fopen(puppet.agent_pidfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale pidfile'
else:
return 'Idle daemon'
return 'Stopped'
def summary():
'''
.. versionadded:: 2014.7.0
Show a summary of the last puppet agent run
CLI Example:
.. code-block:: bash
salt '*' puppet.summary
'''
puppet = _Puppet()
try:
with salt.utils.files.fopen(puppet.lastrunfile, 'r') as fp_:
report = salt.utils.yaml.safe_load(fp_)
result = {}
if 'time' in report:
try:
result['last_run'] = datetime.datetime.fromtimestamp(
int(report['time']['last_run'])).isoformat()
except (TypeError, ValueError, KeyError):
result['last_run'] = 'invalid or missing timestamp'
result['time'] = {}
for key in ('total', 'config_retrieval'):
if key in report['time']:
result['time'][key] = report['time'][key]
if 'resources' in report:
result['resources'] = report['resources']
except salt.utils.yaml.YAMLError as exc:
raise CommandExecutionError(
'YAML error parsing puppet run summary: {0}'.format(exc)
)
except IOError as exc:
raise CommandExecutionError(
'Unable to read puppet run summary: {0}'.format(exc)
)
return result
def plugin_sync():
'''
Runs a plugin sync between the puppet master and agent
CLI Example:
.. code-block:: bash
salt '*' puppet.plugin_sync
'''
ret = __salt__['cmd.run']('puppet plugin download')
if not ret:
return ''
return ret
def facts(puppet=False):
'''
Run facter and return the results
CLI Example:
.. code-block:: bash
salt '*' puppet.facts
'''
ret = {}
opt_puppet = '--puppet' if puppet else ''
cmd_ret = __salt__['cmd.run_all']('facter {0}'.format(opt_puppet))
if cmd_ret['retcode'] != 0:
raise CommandExecutionError(cmd_ret['stderr'])
output = cmd_ret['stdout']
# Loop over the facter output and properly
# parse it into a nice dictionary for using
# elsewhere
for line in output.splitlines():
if not line:
continue
fact, value = _format_fact(line)
if not fact:
continue
ret[fact] = value
return ret
def fact(name, puppet=False):
'''
Run facter for a specific fact
CLI Example:
.. code-block:: bash
salt '*' puppet.fact kernel
'''
opt_puppet = '--puppet' if puppet else ''
ret = __salt__['cmd.run_all'](
'facter {0} {1}'.format(opt_puppet, name),
python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(ret['stderr'])
if not ret['stdout']:
return ''
return ret['stdout']
|
saltstack/salt
|
salt/modules/puppet.py
|
disable
|
python
|
def disable(message=None):
'''
.. versionadded:: 2014.7.0
Disable the puppet agent
message
.. versionadded:: 2015.5.2
Disable message to send to puppet
CLI Example:
.. code-block:: bash
salt '*' puppet.disable
salt '*' puppet.disable 'Disabled, contact XYZ before enabling'
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return False
else:
with salt.utils.files.fopen(puppet.disabled_lockfile, 'w') as lockfile:
try:
# Puppet chokes when no valid json is found
msg = '{{"disabled_message":"{0}"}}'.format(message) if message is not None else '{}'
lockfile.write(salt.utils.stringutils.to_str(msg))
lockfile.close()
return True
except (IOError, OSError) as exc:
msg = 'Failed to disable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
|
.. versionadded:: 2014.7.0
Disable the puppet agent
message
.. versionadded:: 2015.5.2
Disable message to send to puppet
CLI Example:
.. code-block:: bash
salt '*' puppet.disable
salt '*' puppet.disable 'Disabled, contact XYZ before enabling'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/puppet.py#L222-L256
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n"
] |
# -*- coding: utf-8 -*-
'''
Execute puppet routines
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
from distutils import version # pylint: disable=no-name-in-module
import logging
import os
import datetime
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.yaml
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if puppet is installed
'''
unavailable_exes = ', '.join(exe for exe in ('facter', 'puppet')
if salt.utils.path.which(exe) is None)
if unavailable_exes:
return (False,
('The puppet execution module cannot be loaded: '
'{0} unavailable.'.format(unavailable_exes)))
else:
return 'puppet'
def _format_fact(output):
try:
fact, value = output.split(' => ', 1)
value = value.strip()
except ValueError:
fact = None
value = None
return (fact, value)
class _Puppet(object):
'''
Puppet helper class. Used to format command for execution.
'''
def __init__(self):
'''
Setup a puppet instance, based on the premis that default usage is to
run 'puppet agent --test'. Configuration and run states are stored in
the default locations.
'''
self.subcmd = 'agent'
self.subcmd_args = [] # e.g. /a/b/manifest.pp
self.kwargs = {'color': 'false'} # e.g. --tags=apache::server
self.args = [] # e.g. --noop
if salt.utils.platform.is_windows():
self.vardir = 'C:\\ProgramData\\PuppetLabs\\puppet\\var'
self.rundir = 'C:\\ProgramData\\PuppetLabs\\puppet\\run'
self.confdir = 'C:\\ProgramData\\PuppetLabs\\puppet\\etc'
else:
self.puppet_version = __salt__['cmd.run']('puppet --version')
if 'Enterprise' in self.puppet_version:
self.vardir = '/var/opt/lib/pe-puppet'
self.rundir = '/var/opt/run/pe-puppet'
self.confdir = '/etc/puppetlabs/puppet'
elif self.puppet_version != [] and version.StrictVersion(self.puppet_version) >= version.StrictVersion('4.0.0'):
self.vardir = '/opt/puppetlabs/puppet/cache'
self.rundir = '/var/run/puppetlabs'
self.confdir = '/etc/puppetlabs/puppet'
else:
self.vardir = '/var/lib/puppet'
self.rundir = '/var/run/puppet'
self.confdir = '/etc/puppet'
self.disabled_lockfile = self.vardir + '/state/agent_disabled.lock'
self.run_lockfile = self.vardir + '/state/agent_catalog_run.lock'
self.agent_pidfile = self.rundir + '/agent.pid'
self.lastrunfile = self.vardir + '/state/last_run_summary.yaml'
def __repr__(self):
'''
Format the command string to executed using cmd.run_all.
'''
cmd = 'puppet {subcmd} --vardir {vardir} --confdir {confdir}'.format(
**self.__dict__
)
args = ' '.join(self.subcmd_args)
args += ''.join(
[' --{0}'.format(k) for k in self.args] # single spaces
)
args += ''.join([
' --{0} {1}'.format(k, v) for k, v in six.iteritems(self.kwargs)]
)
# Ensure that the puppet call will return 0 in case of exit code 2
if salt.utils.platform.is_windows():
return 'cmd /V:ON /c {0} {1} ^& if !ERRORLEVEL! EQU 2 (EXIT 0) ELSE (EXIT /B)'.format(cmd, args)
return '({0} {1}) || test $? -eq 2'.format(cmd, args)
def arguments(self, args=None):
'''
Read in arguments for the current subcommand. These are added to the
cmd line without '--' appended. Any others are redirected as standard
options with the double hyphen prefixed.
'''
# permits deleting elements rather than using slices
args = args and list(args) or []
# match against all known/supported subcmds
if self.subcmd == 'apply':
# apply subcommand requires a manifest file to execute
self.subcmd_args = [args[0]]
del args[0]
if self.subcmd == 'agent':
# no arguments are required
args.extend([
'test'
])
# finally do this after subcmd has been matched for all remaining args
self.args = args
def run(*args, **kwargs):
'''
Execute a puppet run and return a dict with the stderr, stdout,
return code, etc. The first positional argument given is checked as a
subcommand. Following positional arguments should be ordered with arguments
required by the subcommand first, followed by non-keyword arguments.
Tags are specified by a tag keyword and comma separated list of values. --
http://docs.puppetlabs.com/puppet/latest/reference/lang_tags.html
CLI Examples:
.. code-block:: bash
salt '*' puppet.run
salt '*' puppet.run tags=basefiles::edit,apache::server
salt '*' puppet.run agent onetime no-daemonize no-usecacheonfailure no-splay ignorecache
salt '*' puppet.run debug
salt '*' puppet.run apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
puppet = _Puppet()
# new args tuple to filter out agent/apply for _Puppet.arguments()
buildargs = ()
for arg in range(len(args)):
# based on puppet documentation action must come first. making the same
# assertion. need to ensure the list of supported cmds here matches
# those defined in _Puppet.arguments()
if args[arg] in ['agent', 'apply']:
puppet.subcmd = args[arg]
else:
buildargs += (args[arg],)
# args will exist as an empty list even if none have been provided
puppet.arguments(buildargs)
puppet.kwargs.update(salt.utils.args.clean_kwargs(**kwargs))
ret = __salt__['cmd.run_all'](repr(puppet), python_shell=True)
return ret
def noop(*args, **kwargs):
'''
Execute a puppet noop run and return a dict with the stderr, stdout,
return code, etc. Usage is the same as for puppet.run.
CLI Example:
.. code-block:: bash
salt '*' puppet.noop
salt '*' puppet.noop tags=basefiles::edit,apache::server
salt '*' puppet.noop debug
salt '*' puppet.noop apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
args += ('noop',)
return run(*args, **kwargs)
def enable():
'''
.. versionadded:: 2014.7.0
Enable the puppet agent
CLI Example:
.. code-block:: bash
salt '*' puppet.enable
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
try:
os.remove(puppet.disabled_lockfile)
except (IOError, OSError) as exc:
msg = 'Failed to enable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
else:
return True
return False
def status():
'''
.. versionadded:: 2014.7.0
Display puppet agent status
CLI Example:
.. code-block:: bash
salt '*' puppet.status
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return 'Administratively disabled'
if os.path.isfile(puppet.run_lockfile):
try:
with salt.utils.files.fopen(puppet.run_lockfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale lockfile'
else:
return 'Applying a catalog'
if os.path.isfile(puppet.agent_pidfile):
try:
with salt.utils.files.fopen(puppet.agent_pidfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale pidfile'
else:
return 'Idle daemon'
return 'Stopped'
def summary():
'''
.. versionadded:: 2014.7.0
Show a summary of the last puppet agent run
CLI Example:
.. code-block:: bash
salt '*' puppet.summary
'''
puppet = _Puppet()
try:
with salt.utils.files.fopen(puppet.lastrunfile, 'r') as fp_:
report = salt.utils.yaml.safe_load(fp_)
result = {}
if 'time' in report:
try:
result['last_run'] = datetime.datetime.fromtimestamp(
int(report['time']['last_run'])).isoformat()
except (TypeError, ValueError, KeyError):
result['last_run'] = 'invalid or missing timestamp'
result['time'] = {}
for key in ('total', 'config_retrieval'):
if key in report['time']:
result['time'][key] = report['time'][key]
if 'resources' in report:
result['resources'] = report['resources']
except salt.utils.yaml.YAMLError as exc:
raise CommandExecutionError(
'YAML error parsing puppet run summary: {0}'.format(exc)
)
except IOError as exc:
raise CommandExecutionError(
'Unable to read puppet run summary: {0}'.format(exc)
)
return result
def plugin_sync():
'''
Runs a plugin sync between the puppet master and agent
CLI Example:
.. code-block:: bash
salt '*' puppet.plugin_sync
'''
ret = __salt__['cmd.run']('puppet plugin download')
if not ret:
return ''
return ret
def facts(puppet=False):
'''
Run facter and return the results
CLI Example:
.. code-block:: bash
salt '*' puppet.facts
'''
ret = {}
opt_puppet = '--puppet' if puppet else ''
cmd_ret = __salt__['cmd.run_all']('facter {0}'.format(opt_puppet))
if cmd_ret['retcode'] != 0:
raise CommandExecutionError(cmd_ret['stderr'])
output = cmd_ret['stdout']
# Loop over the facter output and properly
# parse it into a nice dictionary for using
# elsewhere
for line in output.splitlines():
if not line:
continue
fact, value = _format_fact(line)
if not fact:
continue
ret[fact] = value
return ret
def fact(name, puppet=False):
'''
Run facter for a specific fact
CLI Example:
.. code-block:: bash
salt '*' puppet.fact kernel
'''
opt_puppet = '--puppet' if puppet else ''
ret = __salt__['cmd.run_all'](
'facter {0} {1}'.format(opt_puppet, name),
python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(ret['stderr'])
if not ret['stdout']:
return ''
return ret['stdout']
|
saltstack/salt
|
salt/modules/puppet.py
|
status
|
python
|
def status():
'''
.. versionadded:: 2014.7.0
Display puppet agent status
CLI Example:
.. code-block:: bash
salt '*' puppet.status
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return 'Administratively disabled'
if os.path.isfile(puppet.run_lockfile):
try:
with salt.utils.files.fopen(puppet.run_lockfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale lockfile'
else:
return 'Applying a catalog'
if os.path.isfile(puppet.agent_pidfile):
try:
with salt.utils.files.fopen(puppet.agent_pidfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale pidfile'
else:
return 'Idle daemon'
return 'Stopped'
|
.. versionadded:: 2014.7.0
Display puppet agent status
CLI Example:
.. code-block:: bash
salt '*' puppet.status
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/puppet.py#L259-L296
| null |
# -*- coding: utf-8 -*-
'''
Execute puppet routines
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
from distutils import version # pylint: disable=no-name-in-module
import logging
import os
import datetime
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.yaml
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if puppet is installed
'''
unavailable_exes = ', '.join(exe for exe in ('facter', 'puppet')
if salt.utils.path.which(exe) is None)
if unavailable_exes:
return (False,
('The puppet execution module cannot be loaded: '
'{0} unavailable.'.format(unavailable_exes)))
else:
return 'puppet'
def _format_fact(output):
try:
fact, value = output.split(' => ', 1)
value = value.strip()
except ValueError:
fact = None
value = None
return (fact, value)
class _Puppet(object):
'''
Puppet helper class. Used to format command for execution.
'''
def __init__(self):
'''
Setup a puppet instance, based on the premis that default usage is to
run 'puppet agent --test'. Configuration and run states are stored in
the default locations.
'''
self.subcmd = 'agent'
self.subcmd_args = [] # e.g. /a/b/manifest.pp
self.kwargs = {'color': 'false'} # e.g. --tags=apache::server
self.args = [] # e.g. --noop
if salt.utils.platform.is_windows():
self.vardir = 'C:\\ProgramData\\PuppetLabs\\puppet\\var'
self.rundir = 'C:\\ProgramData\\PuppetLabs\\puppet\\run'
self.confdir = 'C:\\ProgramData\\PuppetLabs\\puppet\\etc'
else:
self.puppet_version = __salt__['cmd.run']('puppet --version')
if 'Enterprise' in self.puppet_version:
self.vardir = '/var/opt/lib/pe-puppet'
self.rundir = '/var/opt/run/pe-puppet'
self.confdir = '/etc/puppetlabs/puppet'
elif self.puppet_version != [] and version.StrictVersion(self.puppet_version) >= version.StrictVersion('4.0.0'):
self.vardir = '/opt/puppetlabs/puppet/cache'
self.rundir = '/var/run/puppetlabs'
self.confdir = '/etc/puppetlabs/puppet'
else:
self.vardir = '/var/lib/puppet'
self.rundir = '/var/run/puppet'
self.confdir = '/etc/puppet'
self.disabled_lockfile = self.vardir + '/state/agent_disabled.lock'
self.run_lockfile = self.vardir + '/state/agent_catalog_run.lock'
self.agent_pidfile = self.rundir + '/agent.pid'
self.lastrunfile = self.vardir + '/state/last_run_summary.yaml'
def __repr__(self):
'''
Format the command string to executed using cmd.run_all.
'''
cmd = 'puppet {subcmd} --vardir {vardir} --confdir {confdir}'.format(
**self.__dict__
)
args = ' '.join(self.subcmd_args)
args += ''.join(
[' --{0}'.format(k) for k in self.args] # single spaces
)
args += ''.join([
' --{0} {1}'.format(k, v) for k, v in six.iteritems(self.kwargs)]
)
# Ensure that the puppet call will return 0 in case of exit code 2
if salt.utils.platform.is_windows():
return 'cmd /V:ON /c {0} {1} ^& if !ERRORLEVEL! EQU 2 (EXIT 0) ELSE (EXIT /B)'.format(cmd, args)
return '({0} {1}) || test $? -eq 2'.format(cmd, args)
def arguments(self, args=None):
'''
Read in arguments for the current subcommand. These are added to the
cmd line without '--' appended. Any others are redirected as standard
options with the double hyphen prefixed.
'''
# permits deleting elements rather than using slices
args = args and list(args) or []
# match against all known/supported subcmds
if self.subcmd == 'apply':
# apply subcommand requires a manifest file to execute
self.subcmd_args = [args[0]]
del args[0]
if self.subcmd == 'agent':
# no arguments are required
args.extend([
'test'
])
# finally do this after subcmd has been matched for all remaining args
self.args = args
def run(*args, **kwargs):
'''
Execute a puppet run and return a dict with the stderr, stdout,
return code, etc. The first positional argument given is checked as a
subcommand. Following positional arguments should be ordered with arguments
required by the subcommand first, followed by non-keyword arguments.
Tags are specified by a tag keyword and comma separated list of values. --
http://docs.puppetlabs.com/puppet/latest/reference/lang_tags.html
CLI Examples:
.. code-block:: bash
salt '*' puppet.run
salt '*' puppet.run tags=basefiles::edit,apache::server
salt '*' puppet.run agent onetime no-daemonize no-usecacheonfailure no-splay ignorecache
salt '*' puppet.run debug
salt '*' puppet.run apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
puppet = _Puppet()
# new args tuple to filter out agent/apply for _Puppet.arguments()
buildargs = ()
for arg in range(len(args)):
# based on puppet documentation action must come first. making the same
# assertion. need to ensure the list of supported cmds here matches
# those defined in _Puppet.arguments()
if args[arg] in ['agent', 'apply']:
puppet.subcmd = args[arg]
else:
buildargs += (args[arg],)
# args will exist as an empty list even if none have been provided
puppet.arguments(buildargs)
puppet.kwargs.update(salt.utils.args.clean_kwargs(**kwargs))
ret = __salt__['cmd.run_all'](repr(puppet), python_shell=True)
return ret
def noop(*args, **kwargs):
'''
Execute a puppet noop run and return a dict with the stderr, stdout,
return code, etc. Usage is the same as for puppet.run.
CLI Example:
.. code-block:: bash
salt '*' puppet.noop
salt '*' puppet.noop tags=basefiles::edit,apache::server
salt '*' puppet.noop debug
salt '*' puppet.noop apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
args += ('noop',)
return run(*args, **kwargs)
def enable():
'''
.. versionadded:: 2014.7.0
Enable the puppet agent
CLI Example:
.. code-block:: bash
salt '*' puppet.enable
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
try:
os.remove(puppet.disabled_lockfile)
except (IOError, OSError) as exc:
msg = 'Failed to enable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
else:
return True
return False
def disable(message=None):
'''
.. versionadded:: 2014.7.0
Disable the puppet agent
message
.. versionadded:: 2015.5.2
Disable message to send to puppet
CLI Example:
.. code-block:: bash
salt '*' puppet.disable
salt '*' puppet.disable 'Disabled, contact XYZ before enabling'
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return False
else:
with salt.utils.files.fopen(puppet.disabled_lockfile, 'w') as lockfile:
try:
# Puppet chokes when no valid json is found
msg = '{{"disabled_message":"{0}"}}'.format(message) if message is not None else '{}'
lockfile.write(salt.utils.stringutils.to_str(msg))
lockfile.close()
return True
except (IOError, OSError) as exc:
msg = 'Failed to disable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
def summary():
'''
.. versionadded:: 2014.7.0
Show a summary of the last puppet agent run
CLI Example:
.. code-block:: bash
salt '*' puppet.summary
'''
puppet = _Puppet()
try:
with salt.utils.files.fopen(puppet.lastrunfile, 'r') as fp_:
report = salt.utils.yaml.safe_load(fp_)
result = {}
if 'time' in report:
try:
result['last_run'] = datetime.datetime.fromtimestamp(
int(report['time']['last_run'])).isoformat()
except (TypeError, ValueError, KeyError):
result['last_run'] = 'invalid or missing timestamp'
result['time'] = {}
for key in ('total', 'config_retrieval'):
if key in report['time']:
result['time'][key] = report['time'][key]
if 'resources' in report:
result['resources'] = report['resources']
except salt.utils.yaml.YAMLError as exc:
raise CommandExecutionError(
'YAML error parsing puppet run summary: {0}'.format(exc)
)
except IOError as exc:
raise CommandExecutionError(
'Unable to read puppet run summary: {0}'.format(exc)
)
return result
def plugin_sync():
'''
Runs a plugin sync between the puppet master and agent
CLI Example:
.. code-block:: bash
salt '*' puppet.plugin_sync
'''
ret = __salt__['cmd.run']('puppet plugin download')
if not ret:
return ''
return ret
def facts(puppet=False):
'''
Run facter and return the results
CLI Example:
.. code-block:: bash
salt '*' puppet.facts
'''
ret = {}
opt_puppet = '--puppet' if puppet else ''
cmd_ret = __salt__['cmd.run_all']('facter {0}'.format(opt_puppet))
if cmd_ret['retcode'] != 0:
raise CommandExecutionError(cmd_ret['stderr'])
output = cmd_ret['stdout']
# Loop over the facter output and properly
# parse it into a nice dictionary for using
# elsewhere
for line in output.splitlines():
if not line:
continue
fact, value = _format_fact(line)
if not fact:
continue
ret[fact] = value
return ret
def fact(name, puppet=False):
'''
Run facter for a specific fact
CLI Example:
.. code-block:: bash
salt '*' puppet.fact kernel
'''
opt_puppet = '--puppet' if puppet else ''
ret = __salt__['cmd.run_all'](
'facter {0} {1}'.format(opt_puppet, name),
python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(ret['stderr'])
if not ret['stdout']:
return ''
return ret['stdout']
|
saltstack/salt
|
salt/modules/puppet.py
|
summary
|
python
|
def summary():
'''
.. versionadded:: 2014.7.0
Show a summary of the last puppet agent run
CLI Example:
.. code-block:: bash
salt '*' puppet.summary
'''
puppet = _Puppet()
try:
with salt.utils.files.fopen(puppet.lastrunfile, 'r') as fp_:
report = salt.utils.yaml.safe_load(fp_)
result = {}
if 'time' in report:
try:
result['last_run'] = datetime.datetime.fromtimestamp(
int(report['time']['last_run'])).isoformat()
except (TypeError, ValueError, KeyError):
result['last_run'] = 'invalid or missing timestamp'
result['time'] = {}
for key in ('total', 'config_retrieval'):
if key in report['time']:
result['time'][key] = report['time'][key]
if 'resources' in report:
result['resources'] = report['resources']
except salt.utils.yaml.YAMLError as exc:
raise CommandExecutionError(
'YAML error parsing puppet run summary: {0}'.format(exc)
)
except IOError as exc:
raise CommandExecutionError(
'Unable to read puppet run summary: {0}'.format(exc)
)
return result
|
.. versionadded:: 2014.7.0
Show a summary of the last puppet agent run
CLI Example:
.. code-block:: bash
salt '*' puppet.summary
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/puppet.py#L299-L343
|
[
"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"
] |
# -*- coding: utf-8 -*-
'''
Execute puppet routines
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
from distutils import version # pylint: disable=no-name-in-module
import logging
import os
import datetime
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.yaml
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if puppet is installed
'''
unavailable_exes = ', '.join(exe for exe in ('facter', 'puppet')
if salt.utils.path.which(exe) is None)
if unavailable_exes:
return (False,
('The puppet execution module cannot be loaded: '
'{0} unavailable.'.format(unavailable_exes)))
else:
return 'puppet'
def _format_fact(output):
try:
fact, value = output.split(' => ', 1)
value = value.strip()
except ValueError:
fact = None
value = None
return (fact, value)
class _Puppet(object):
'''
Puppet helper class. Used to format command for execution.
'''
def __init__(self):
'''
Setup a puppet instance, based on the premis that default usage is to
run 'puppet agent --test'. Configuration and run states are stored in
the default locations.
'''
self.subcmd = 'agent'
self.subcmd_args = [] # e.g. /a/b/manifest.pp
self.kwargs = {'color': 'false'} # e.g. --tags=apache::server
self.args = [] # e.g. --noop
if salt.utils.platform.is_windows():
self.vardir = 'C:\\ProgramData\\PuppetLabs\\puppet\\var'
self.rundir = 'C:\\ProgramData\\PuppetLabs\\puppet\\run'
self.confdir = 'C:\\ProgramData\\PuppetLabs\\puppet\\etc'
else:
self.puppet_version = __salt__['cmd.run']('puppet --version')
if 'Enterprise' in self.puppet_version:
self.vardir = '/var/opt/lib/pe-puppet'
self.rundir = '/var/opt/run/pe-puppet'
self.confdir = '/etc/puppetlabs/puppet'
elif self.puppet_version != [] and version.StrictVersion(self.puppet_version) >= version.StrictVersion('4.0.0'):
self.vardir = '/opt/puppetlabs/puppet/cache'
self.rundir = '/var/run/puppetlabs'
self.confdir = '/etc/puppetlabs/puppet'
else:
self.vardir = '/var/lib/puppet'
self.rundir = '/var/run/puppet'
self.confdir = '/etc/puppet'
self.disabled_lockfile = self.vardir + '/state/agent_disabled.lock'
self.run_lockfile = self.vardir + '/state/agent_catalog_run.lock'
self.agent_pidfile = self.rundir + '/agent.pid'
self.lastrunfile = self.vardir + '/state/last_run_summary.yaml'
def __repr__(self):
'''
Format the command string to executed using cmd.run_all.
'''
cmd = 'puppet {subcmd} --vardir {vardir} --confdir {confdir}'.format(
**self.__dict__
)
args = ' '.join(self.subcmd_args)
args += ''.join(
[' --{0}'.format(k) for k in self.args] # single spaces
)
args += ''.join([
' --{0} {1}'.format(k, v) for k, v in six.iteritems(self.kwargs)]
)
# Ensure that the puppet call will return 0 in case of exit code 2
if salt.utils.platform.is_windows():
return 'cmd /V:ON /c {0} {1} ^& if !ERRORLEVEL! EQU 2 (EXIT 0) ELSE (EXIT /B)'.format(cmd, args)
return '({0} {1}) || test $? -eq 2'.format(cmd, args)
def arguments(self, args=None):
'''
Read in arguments for the current subcommand. These are added to the
cmd line without '--' appended. Any others are redirected as standard
options with the double hyphen prefixed.
'''
# permits deleting elements rather than using slices
args = args and list(args) or []
# match against all known/supported subcmds
if self.subcmd == 'apply':
# apply subcommand requires a manifest file to execute
self.subcmd_args = [args[0]]
del args[0]
if self.subcmd == 'agent':
# no arguments are required
args.extend([
'test'
])
# finally do this after subcmd has been matched for all remaining args
self.args = args
def run(*args, **kwargs):
'''
Execute a puppet run and return a dict with the stderr, stdout,
return code, etc. The first positional argument given is checked as a
subcommand. Following positional arguments should be ordered with arguments
required by the subcommand first, followed by non-keyword arguments.
Tags are specified by a tag keyword and comma separated list of values. --
http://docs.puppetlabs.com/puppet/latest/reference/lang_tags.html
CLI Examples:
.. code-block:: bash
salt '*' puppet.run
salt '*' puppet.run tags=basefiles::edit,apache::server
salt '*' puppet.run agent onetime no-daemonize no-usecacheonfailure no-splay ignorecache
salt '*' puppet.run debug
salt '*' puppet.run apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
puppet = _Puppet()
# new args tuple to filter out agent/apply for _Puppet.arguments()
buildargs = ()
for arg in range(len(args)):
# based on puppet documentation action must come first. making the same
# assertion. need to ensure the list of supported cmds here matches
# those defined in _Puppet.arguments()
if args[arg] in ['agent', 'apply']:
puppet.subcmd = args[arg]
else:
buildargs += (args[arg],)
# args will exist as an empty list even if none have been provided
puppet.arguments(buildargs)
puppet.kwargs.update(salt.utils.args.clean_kwargs(**kwargs))
ret = __salt__['cmd.run_all'](repr(puppet), python_shell=True)
return ret
def noop(*args, **kwargs):
'''
Execute a puppet noop run and return a dict with the stderr, stdout,
return code, etc. Usage is the same as for puppet.run.
CLI Example:
.. code-block:: bash
salt '*' puppet.noop
salt '*' puppet.noop tags=basefiles::edit,apache::server
salt '*' puppet.noop debug
salt '*' puppet.noop apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
args += ('noop',)
return run(*args, **kwargs)
def enable():
'''
.. versionadded:: 2014.7.0
Enable the puppet agent
CLI Example:
.. code-block:: bash
salt '*' puppet.enable
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
try:
os.remove(puppet.disabled_lockfile)
except (IOError, OSError) as exc:
msg = 'Failed to enable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
else:
return True
return False
def disable(message=None):
'''
.. versionadded:: 2014.7.0
Disable the puppet agent
message
.. versionadded:: 2015.5.2
Disable message to send to puppet
CLI Example:
.. code-block:: bash
salt '*' puppet.disable
salt '*' puppet.disable 'Disabled, contact XYZ before enabling'
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return False
else:
with salt.utils.files.fopen(puppet.disabled_lockfile, 'w') as lockfile:
try:
# Puppet chokes when no valid json is found
msg = '{{"disabled_message":"{0}"}}'.format(message) if message is not None else '{}'
lockfile.write(salt.utils.stringutils.to_str(msg))
lockfile.close()
return True
except (IOError, OSError) as exc:
msg = 'Failed to disable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
def status():
'''
.. versionadded:: 2014.7.0
Display puppet agent status
CLI Example:
.. code-block:: bash
salt '*' puppet.status
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return 'Administratively disabled'
if os.path.isfile(puppet.run_lockfile):
try:
with salt.utils.files.fopen(puppet.run_lockfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale lockfile'
else:
return 'Applying a catalog'
if os.path.isfile(puppet.agent_pidfile):
try:
with salt.utils.files.fopen(puppet.agent_pidfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale pidfile'
else:
return 'Idle daemon'
return 'Stopped'
def plugin_sync():
'''
Runs a plugin sync between the puppet master and agent
CLI Example:
.. code-block:: bash
salt '*' puppet.plugin_sync
'''
ret = __salt__['cmd.run']('puppet plugin download')
if not ret:
return ''
return ret
def facts(puppet=False):
'''
Run facter and return the results
CLI Example:
.. code-block:: bash
salt '*' puppet.facts
'''
ret = {}
opt_puppet = '--puppet' if puppet else ''
cmd_ret = __salt__['cmd.run_all']('facter {0}'.format(opt_puppet))
if cmd_ret['retcode'] != 0:
raise CommandExecutionError(cmd_ret['stderr'])
output = cmd_ret['stdout']
# Loop over the facter output and properly
# parse it into a nice dictionary for using
# elsewhere
for line in output.splitlines():
if not line:
continue
fact, value = _format_fact(line)
if not fact:
continue
ret[fact] = value
return ret
def fact(name, puppet=False):
'''
Run facter for a specific fact
CLI Example:
.. code-block:: bash
salt '*' puppet.fact kernel
'''
opt_puppet = '--puppet' if puppet else ''
ret = __salt__['cmd.run_all'](
'facter {0} {1}'.format(opt_puppet, name),
python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(ret['stderr'])
if not ret['stdout']:
return ''
return ret['stdout']
|
saltstack/salt
|
salt/modules/puppet.py
|
facts
|
python
|
def facts(puppet=False):
'''
Run facter and return the results
CLI Example:
.. code-block:: bash
salt '*' puppet.facts
'''
ret = {}
opt_puppet = '--puppet' if puppet else ''
cmd_ret = __salt__['cmd.run_all']('facter {0}'.format(opt_puppet))
if cmd_ret['retcode'] != 0:
raise CommandExecutionError(cmd_ret['stderr'])
output = cmd_ret['stdout']
# Loop over the facter output and properly
# parse it into a nice dictionary for using
# elsewhere
for line in output.splitlines():
if not line:
continue
fact, value = _format_fact(line)
if not fact:
continue
ret[fact] = value
return ret
|
Run facter and return the results
CLI Example:
.. code-block:: bash
salt '*' puppet.facts
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/puppet.py#L363-L392
|
[
"def _format_fact(output):\n try:\n fact, value = output.split(' => ', 1)\n value = value.strip()\n except ValueError:\n fact = None\n value = None\n return (fact, value)\n"
] |
# -*- coding: utf-8 -*-
'''
Execute puppet routines
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
from distutils import version # pylint: disable=no-name-in-module
import logging
import os
import datetime
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.yaml
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if puppet is installed
'''
unavailable_exes = ', '.join(exe for exe in ('facter', 'puppet')
if salt.utils.path.which(exe) is None)
if unavailable_exes:
return (False,
('The puppet execution module cannot be loaded: '
'{0} unavailable.'.format(unavailable_exes)))
else:
return 'puppet'
def _format_fact(output):
try:
fact, value = output.split(' => ', 1)
value = value.strip()
except ValueError:
fact = None
value = None
return (fact, value)
class _Puppet(object):
'''
Puppet helper class. Used to format command for execution.
'''
def __init__(self):
'''
Setup a puppet instance, based on the premis that default usage is to
run 'puppet agent --test'. Configuration and run states are stored in
the default locations.
'''
self.subcmd = 'agent'
self.subcmd_args = [] # e.g. /a/b/manifest.pp
self.kwargs = {'color': 'false'} # e.g. --tags=apache::server
self.args = [] # e.g. --noop
if salt.utils.platform.is_windows():
self.vardir = 'C:\\ProgramData\\PuppetLabs\\puppet\\var'
self.rundir = 'C:\\ProgramData\\PuppetLabs\\puppet\\run'
self.confdir = 'C:\\ProgramData\\PuppetLabs\\puppet\\etc'
else:
self.puppet_version = __salt__['cmd.run']('puppet --version')
if 'Enterprise' in self.puppet_version:
self.vardir = '/var/opt/lib/pe-puppet'
self.rundir = '/var/opt/run/pe-puppet'
self.confdir = '/etc/puppetlabs/puppet'
elif self.puppet_version != [] and version.StrictVersion(self.puppet_version) >= version.StrictVersion('4.0.0'):
self.vardir = '/opt/puppetlabs/puppet/cache'
self.rundir = '/var/run/puppetlabs'
self.confdir = '/etc/puppetlabs/puppet'
else:
self.vardir = '/var/lib/puppet'
self.rundir = '/var/run/puppet'
self.confdir = '/etc/puppet'
self.disabled_lockfile = self.vardir + '/state/agent_disabled.lock'
self.run_lockfile = self.vardir + '/state/agent_catalog_run.lock'
self.agent_pidfile = self.rundir + '/agent.pid'
self.lastrunfile = self.vardir + '/state/last_run_summary.yaml'
def __repr__(self):
'''
Format the command string to executed using cmd.run_all.
'''
cmd = 'puppet {subcmd} --vardir {vardir} --confdir {confdir}'.format(
**self.__dict__
)
args = ' '.join(self.subcmd_args)
args += ''.join(
[' --{0}'.format(k) for k in self.args] # single spaces
)
args += ''.join([
' --{0} {1}'.format(k, v) for k, v in six.iteritems(self.kwargs)]
)
# Ensure that the puppet call will return 0 in case of exit code 2
if salt.utils.platform.is_windows():
return 'cmd /V:ON /c {0} {1} ^& if !ERRORLEVEL! EQU 2 (EXIT 0) ELSE (EXIT /B)'.format(cmd, args)
return '({0} {1}) || test $? -eq 2'.format(cmd, args)
def arguments(self, args=None):
'''
Read in arguments for the current subcommand. These are added to the
cmd line without '--' appended. Any others are redirected as standard
options with the double hyphen prefixed.
'''
# permits deleting elements rather than using slices
args = args and list(args) or []
# match against all known/supported subcmds
if self.subcmd == 'apply':
# apply subcommand requires a manifest file to execute
self.subcmd_args = [args[0]]
del args[0]
if self.subcmd == 'agent':
# no arguments are required
args.extend([
'test'
])
# finally do this after subcmd has been matched for all remaining args
self.args = args
def run(*args, **kwargs):
'''
Execute a puppet run and return a dict with the stderr, stdout,
return code, etc. The first positional argument given is checked as a
subcommand. Following positional arguments should be ordered with arguments
required by the subcommand first, followed by non-keyword arguments.
Tags are specified by a tag keyword and comma separated list of values. --
http://docs.puppetlabs.com/puppet/latest/reference/lang_tags.html
CLI Examples:
.. code-block:: bash
salt '*' puppet.run
salt '*' puppet.run tags=basefiles::edit,apache::server
salt '*' puppet.run agent onetime no-daemonize no-usecacheonfailure no-splay ignorecache
salt '*' puppet.run debug
salt '*' puppet.run apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
puppet = _Puppet()
# new args tuple to filter out agent/apply for _Puppet.arguments()
buildargs = ()
for arg in range(len(args)):
# based on puppet documentation action must come first. making the same
# assertion. need to ensure the list of supported cmds here matches
# those defined in _Puppet.arguments()
if args[arg] in ['agent', 'apply']:
puppet.subcmd = args[arg]
else:
buildargs += (args[arg],)
# args will exist as an empty list even if none have been provided
puppet.arguments(buildargs)
puppet.kwargs.update(salt.utils.args.clean_kwargs(**kwargs))
ret = __salt__['cmd.run_all'](repr(puppet), python_shell=True)
return ret
def noop(*args, **kwargs):
'''
Execute a puppet noop run and return a dict with the stderr, stdout,
return code, etc. Usage is the same as for puppet.run.
CLI Example:
.. code-block:: bash
salt '*' puppet.noop
salt '*' puppet.noop tags=basefiles::edit,apache::server
salt '*' puppet.noop debug
salt '*' puppet.noop apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
args += ('noop',)
return run(*args, **kwargs)
def enable():
'''
.. versionadded:: 2014.7.0
Enable the puppet agent
CLI Example:
.. code-block:: bash
salt '*' puppet.enable
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
try:
os.remove(puppet.disabled_lockfile)
except (IOError, OSError) as exc:
msg = 'Failed to enable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
else:
return True
return False
def disable(message=None):
'''
.. versionadded:: 2014.7.0
Disable the puppet agent
message
.. versionadded:: 2015.5.2
Disable message to send to puppet
CLI Example:
.. code-block:: bash
salt '*' puppet.disable
salt '*' puppet.disable 'Disabled, contact XYZ before enabling'
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return False
else:
with salt.utils.files.fopen(puppet.disabled_lockfile, 'w') as lockfile:
try:
# Puppet chokes when no valid json is found
msg = '{{"disabled_message":"{0}"}}'.format(message) if message is not None else '{}'
lockfile.write(salt.utils.stringutils.to_str(msg))
lockfile.close()
return True
except (IOError, OSError) as exc:
msg = 'Failed to disable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
def status():
'''
.. versionadded:: 2014.7.0
Display puppet agent status
CLI Example:
.. code-block:: bash
salt '*' puppet.status
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return 'Administratively disabled'
if os.path.isfile(puppet.run_lockfile):
try:
with salt.utils.files.fopen(puppet.run_lockfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale lockfile'
else:
return 'Applying a catalog'
if os.path.isfile(puppet.agent_pidfile):
try:
with salt.utils.files.fopen(puppet.agent_pidfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale pidfile'
else:
return 'Idle daemon'
return 'Stopped'
def summary():
'''
.. versionadded:: 2014.7.0
Show a summary of the last puppet agent run
CLI Example:
.. code-block:: bash
salt '*' puppet.summary
'''
puppet = _Puppet()
try:
with salt.utils.files.fopen(puppet.lastrunfile, 'r') as fp_:
report = salt.utils.yaml.safe_load(fp_)
result = {}
if 'time' in report:
try:
result['last_run'] = datetime.datetime.fromtimestamp(
int(report['time']['last_run'])).isoformat()
except (TypeError, ValueError, KeyError):
result['last_run'] = 'invalid or missing timestamp'
result['time'] = {}
for key in ('total', 'config_retrieval'):
if key in report['time']:
result['time'][key] = report['time'][key]
if 'resources' in report:
result['resources'] = report['resources']
except salt.utils.yaml.YAMLError as exc:
raise CommandExecutionError(
'YAML error parsing puppet run summary: {0}'.format(exc)
)
except IOError as exc:
raise CommandExecutionError(
'Unable to read puppet run summary: {0}'.format(exc)
)
return result
def plugin_sync():
'''
Runs a plugin sync between the puppet master and agent
CLI Example:
.. code-block:: bash
salt '*' puppet.plugin_sync
'''
ret = __salt__['cmd.run']('puppet plugin download')
if not ret:
return ''
return ret
def fact(name, puppet=False):
'''
Run facter for a specific fact
CLI Example:
.. code-block:: bash
salt '*' puppet.fact kernel
'''
opt_puppet = '--puppet' if puppet else ''
ret = __salt__['cmd.run_all'](
'facter {0} {1}'.format(opt_puppet, name),
python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(ret['stderr'])
if not ret['stdout']:
return ''
return ret['stdout']
|
saltstack/salt
|
salt/modules/puppet.py
|
fact
|
python
|
def fact(name, puppet=False):
'''
Run facter for a specific fact
CLI Example:
.. code-block:: bash
salt '*' puppet.fact kernel
'''
opt_puppet = '--puppet' if puppet else ''
ret = __salt__['cmd.run_all'](
'facter {0} {1}'.format(opt_puppet, name),
python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(ret['stderr'])
if not ret['stdout']:
return ''
return ret['stdout']
|
Run facter for a specific fact
CLI Example:
.. code-block:: bash
salt '*' puppet.fact kernel
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/puppet.py#L395-L415
| null |
# -*- coding: utf-8 -*-
'''
Execute puppet routines
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
from distutils import version # pylint: disable=no-name-in-module
import logging
import os
import datetime
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.yaml
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if puppet is installed
'''
unavailable_exes = ', '.join(exe for exe in ('facter', 'puppet')
if salt.utils.path.which(exe) is None)
if unavailable_exes:
return (False,
('The puppet execution module cannot be loaded: '
'{0} unavailable.'.format(unavailable_exes)))
else:
return 'puppet'
def _format_fact(output):
try:
fact, value = output.split(' => ', 1)
value = value.strip()
except ValueError:
fact = None
value = None
return (fact, value)
class _Puppet(object):
'''
Puppet helper class. Used to format command for execution.
'''
def __init__(self):
'''
Setup a puppet instance, based on the premis that default usage is to
run 'puppet agent --test'. Configuration and run states are stored in
the default locations.
'''
self.subcmd = 'agent'
self.subcmd_args = [] # e.g. /a/b/manifest.pp
self.kwargs = {'color': 'false'} # e.g. --tags=apache::server
self.args = [] # e.g. --noop
if salt.utils.platform.is_windows():
self.vardir = 'C:\\ProgramData\\PuppetLabs\\puppet\\var'
self.rundir = 'C:\\ProgramData\\PuppetLabs\\puppet\\run'
self.confdir = 'C:\\ProgramData\\PuppetLabs\\puppet\\etc'
else:
self.puppet_version = __salt__['cmd.run']('puppet --version')
if 'Enterprise' in self.puppet_version:
self.vardir = '/var/opt/lib/pe-puppet'
self.rundir = '/var/opt/run/pe-puppet'
self.confdir = '/etc/puppetlabs/puppet'
elif self.puppet_version != [] and version.StrictVersion(self.puppet_version) >= version.StrictVersion('4.0.0'):
self.vardir = '/opt/puppetlabs/puppet/cache'
self.rundir = '/var/run/puppetlabs'
self.confdir = '/etc/puppetlabs/puppet'
else:
self.vardir = '/var/lib/puppet'
self.rundir = '/var/run/puppet'
self.confdir = '/etc/puppet'
self.disabled_lockfile = self.vardir + '/state/agent_disabled.lock'
self.run_lockfile = self.vardir + '/state/agent_catalog_run.lock'
self.agent_pidfile = self.rundir + '/agent.pid'
self.lastrunfile = self.vardir + '/state/last_run_summary.yaml'
def __repr__(self):
'''
Format the command string to executed using cmd.run_all.
'''
cmd = 'puppet {subcmd} --vardir {vardir} --confdir {confdir}'.format(
**self.__dict__
)
args = ' '.join(self.subcmd_args)
args += ''.join(
[' --{0}'.format(k) for k in self.args] # single spaces
)
args += ''.join([
' --{0} {1}'.format(k, v) for k, v in six.iteritems(self.kwargs)]
)
# Ensure that the puppet call will return 0 in case of exit code 2
if salt.utils.platform.is_windows():
return 'cmd /V:ON /c {0} {1} ^& if !ERRORLEVEL! EQU 2 (EXIT 0) ELSE (EXIT /B)'.format(cmd, args)
return '({0} {1}) || test $? -eq 2'.format(cmd, args)
def arguments(self, args=None):
'''
Read in arguments for the current subcommand. These are added to the
cmd line without '--' appended. Any others are redirected as standard
options with the double hyphen prefixed.
'''
# permits deleting elements rather than using slices
args = args and list(args) or []
# match against all known/supported subcmds
if self.subcmd == 'apply':
# apply subcommand requires a manifest file to execute
self.subcmd_args = [args[0]]
del args[0]
if self.subcmd == 'agent':
# no arguments are required
args.extend([
'test'
])
# finally do this after subcmd has been matched for all remaining args
self.args = args
def run(*args, **kwargs):
'''
Execute a puppet run and return a dict with the stderr, stdout,
return code, etc. The first positional argument given is checked as a
subcommand. Following positional arguments should be ordered with arguments
required by the subcommand first, followed by non-keyword arguments.
Tags are specified by a tag keyword and comma separated list of values. --
http://docs.puppetlabs.com/puppet/latest/reference/lang_tags.html
CLI Examples:
.. code-block:: bash
salt '*' puppet.run
salt '*' puppet.run tags=basefiles::edit,apache::server
salt '*' puppet.run agent onetime no-daemonize no-usecacheonfailure no-splay ignorecache
salt '*' puppet.run debug
salt '*' puppet.run apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
puppet = _Puppet()
# new args tuple to filter out agent/apply for _Puppet.arguments()
buildargs = ()
for arg in range(len(args)):
# based on puppet documentation action must come first. making the same
# assertion. need to ensure the list of supported cmds here matches
# those defined in _Puppet.arguments()
if args[arg] in ['agent', 'apply']:
puppet.subcmd = args[arg]
else:
buildargs += (args[arg],)
# args will exist as an empty list even if none have been provided
puppet.arguments(buildargs)
puppet.kwargs.update(salt.utils.args.clean_kwargs(**kwargs))
ret = __salt__['cmd.run_all'](repr(puppet), python_shell=True)
return ret
def noop(*args, **kwargs):
'''
Execute a puppet noop run and return a dict with the stderr, stdout,
return code, etc. Usage is the same as for puppet.run.
CLI Example:
.. code-block:: bash
salt '*' puppet.noop
salt '*' puppet.noop tags=basefiles::edit,apache::server
salt '*' puppet.noop debug
salt '*' puppet.noop apply /a/b/manifest.pp modulepath=/a/b/modules tags=basefiles::edit,apache::server
'''
args += ('noop',)
return run(*args, **kwargs)
def enable():
'''
.. versionadded:: 2014.7.0
Enable the puppet agent
CLI Example:
.. code-block:: bash
salt '*' puppet.enable
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
try:
os.remove(puppet.disabled_lockfile)
except (IOError, OSError) as exc:
msg = 'Failed to enable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
else:
return True
return False
def disable(message=None):
'''
.. versionadded:: 2014.7.0
Disable the puppet agent
message
.. versionadded:: 2015.5.2
Disable message to send to puppet
CLI Example:
.. code-block:: bash
salt '*' puppet.disable
salt '*' puppet.disable 'Disabled, contact XYZ before enabling'
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return False
else:
with salt.utils.files.fopen(puppet.disabled_lockfile, 'w') as lockfile:
try:
# Puppet chokes when no valid json is found
msg = '{{"disabled_message":"{0}"}}'.format(message) if message is not None else '{}'
lockfile.write(salt.utils.stringutils.to_str(msg))
lockfile.close()
return True
except (IOError, OSError) as exc:
msg = 'Failed to disable: {0}'.format(exc)
log.error(msg)
raise CommandExecutionError(msg)
def status():
'''
.. versionadded:: 2014.7.0
Display puppet agent status
CLI Example:
.. code-block:: bash
salt '*' puppet.status
'''
puppet = _Puppet()
if os.path.isfile(puppet.disabled_lockfile):
return 'Administratively disabled'
if os.path.isfile(puppet.run_lockfile):
try:
with salt.utils.files.fopen(puppet.run_lockfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale lockfile'
else:
return 'Applying a catalog'
if os.path.isfile(puppet.agent_pidfile):
try:
with salt.utils.files.fopen(puppet.agent_pidfile, 'r') as fp_:
pid = int(salt.utils.stringutils.to_unicode(fp_.read()))
os.kill(pid, 0) # raise an OSError if process doesn't exist
except (OSError, ValueError):
return 'Stale pidfile'
else:
return 'Idle daemon'
return 'Stopped'
def summary():
'''
.. versionadded:: 2014.7.0
Show a summary of the last puppet agent run
CLI Example:
.. code-block:: bash
salt '*' puppet.summary
'''
puppet = _Puppet()
try:
with salt.utils.files.fopen(puppet.lastrunfile, 'r') as fp_:
report = salt.utils.yaml.safe_load(fp_)
result = {}
if 'time' in report:
try:
result['last_run'] = datetime.datetime.fromtimestamp(
int(report['time']['last_run'])).isoformat()
except (TypeError, ValueError, KeyError):
result['last_run'] = 'invalid or missing timestamp'
result['time'] = {}
for key in ('total', 'config_retrieval'):
if key in report['time']:
result['time'][key] = report['time'][key]
if 'resources' in report:
result['resources'] = report['resources']
except salt.utils.yaml.YAMLError as exc:
raise CommandExecutionError(
'YAML error parsing puppet run summary: {0}'.format(exc)
)
except IOError as exc:
raise CommandExecutionError(
'Unable to read puppet run summary: {0}'.format(exc)
)
return result
def plugin_sync():
'''
Runs a plugin sync between the puppet master and agent
CLI Example:
.. code-block:: bash
salt '*' puppet.plugin_sync
'''
ret = __salt__['cmd.run']('puppet plugin download')
if not ret:
return ''
return ret
def facts(puppet=False):
'''
Run facter and return the results
CLI Example:
.. code-block:: bash
salt '*' puppet.facts
'''
ret = {}
opt_puppet = '--puppet' if puppet else ''
cmd_ret = __salt__['cmd.run_all']('facter {0}'.format(opt_puppet))
if cmd_ret['retcode'] != 0:
raise CommandExecutionError(cmd_ret['stderr'])
output = cmd_ret['stdout']
# Loop over the facter output and properly
# parse it into a nice dictionary for using
# elsewhere
for line in output.splitlines():
if not line:
continue
fact, value = _format_fact(line)
if not fact:
continue
ret[fact] = value
return ret
|
saltstack/salt
|
salt/modules/puppet.py
|
_Puppet.arguments
|
python
|
def arguments(self, args=None):
'''
Read in arguments for the current subcommand. These are added to the
cmd line without '--' appended. Any others are redirected as standard
options with the double hyphen prefixed.
'''
# permits deleting elements rather than using slices
args = args and list(args) or []
# match against all known/supported subcmds
if self.subcmd == 'apply':
# apply subcommand requires a manifest file to execute
self.subcmd_args = [args[0]]
del args[0]
if self.subcmd == 'agent':
# no arguments are required
args.extend([
'test'
])
# finally do this after subcmd has been matched for all remaining args
self.args = args
|
Read in arguments for the current subcommand. These are added to the
cmd line without '--' appended. Any others are redirected as standard
options with the double hyphen prefixed.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/puppet.py#L113-L135
| null |
class _Puppet(object):
'''
Puppet helper class. Used to format command for execution.
'''
def __init__(self):
'''
Setup a puppet instance, based on the premis that default usage is to
run 'puppet agent --test'. Configuration and run states are stored in
the default locations.
'''
self.subcmd = 'agent'
self.subcmd_args = [] # e.g. /a/b/manifest.pp
self.kwargs = {'color': 'false'} # e.g. --tags=apache::server
self.args = [] # e.g. --noop
if salt.utils.platform.is_windows():
self.vardir = 'C:\\ProgramData\\PuppetLabs\\puppet\\var'
self.rundir = 'C:\\ProgramData\\PuppetLabs\\puppet\\run'
self.confdir = 'C:\\ProgramData\\PuppetLabs\\puppet\\etc'
else:
self.puppet_version = __salt__['cmd.run']('puppet --version')
if 'Enterprise' in self.puppet_version:
self.vardir = '/var/opt/lib/pe-puppet'
self.rundir = '/var/opt/run/pe-puppet'
self.confdir = '/etc/puppetlabs/puppet'
elif self.puppet_version != [] and version.StrictVersion(self.puppet_version) >= version.StrictVersion('4.0.0'):
self.vardir = '/opt/puppetlabs/puppet/cache'
self.rundir = '/var/run/puppetlabs'
self.confdir = '/etc/puppetlabs/puppet'
else:
self.vardir = '/var/lib/puppet'
self.rundir = '/var/run/puppet'
self.confdir = '/etc/puppet'
self.disabled_lockfile = self.vardir + '/state/agent_disabled.lock'
self.run_lockfile = self.vardir + '/state/agent_catalog_run.lock'
self.agent_pidfile = self.rundir + '/agent.pid'
self.lastrunfile = self.vardir + '/state/last_run_summary.yaml'
def __repr__(self):
'''
Format the command string to executed using cmd.run_all.
'''
cmd = 'puppet {subcmd} --vardir {vardir} --confdir {confdir}'.format(
**self.__dict__
)
args = ' '.join(self.subcmd_args)
args += ''.join(
[' --{0}'.format(k) for k in self.args] # single spaces
)
args += ''.join([
' --{0} {1}'.format(k, v) for k, v in six.iteritems(self.kwargs)]
)
# Ensure that the puppet call will return 0 in case of exit code 2
if salt.utils.platform.is_windows():
return 'cmd /V:ON /c {0} {1} ^& if !ERRORLEVEL! EQU 2 (EXIT 0) ELSE (EXIT /B)'.format(cmd, args)
return '({0} {1}) || test $? -eq 2'.format(cmd, args)
|
saltstack/salt
|
salt/states/boto_iam.py
|
keys_present
|
python
|
def keys_present(name, number, save_dir, region=None, key=None, keyid=None, profile=None,
save_format="{2}\n{0}\n{3}\n{1}\n"):
'''
.. versionadded:: 2015.8.0
Ensure the IAM access keys are present.
name (string)
The name of the new user.
number (int)
Number of keys that user should have.
save_dir (string)
The directory that the key/keys will be saved. Keys are saved to a file named according
to the username privided.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
save_format (dict)
Save format is repeated for each key. Default format is
"{2}\\n{0}\\n{3}\\n{1}\\n", where {0} and {1} are placeholders for new
key_id and key respectively, whereas {2} and {3} are "key_id-{number}"
and 'key-{number}' strings kept for compatibility.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](name, region, key, keyid, profile):
ret['result'] = False
ret['comment'] = 'IAM User {0} does not exist.'.format(name)
return ret
if not isinstance(number, int):
ret['comment'] = 'The number of keys must be an integer.'
ret['result'] = False
return ret
if not os.path.isdir(save_dir):
ret['comment'] = 'The directory {0} does not exist.'.format(save_dir)
ret['result'] = False
return ret
keys = __salt__['boto_iam.get_all_access_keys'](user_name=name, region=region, key=key,
keyid=keyid, profile=profile)
if isinstance(keys, six.string_types):
log.debug('keys are : false %s', keys)
error, message = _get_error(keys)
ret['comment'] = 'Could not get keys.\n{0}\n{1}'.format(error, message)
ret['result'] = False
return ret
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
log.debug('Keys are : %s.', keys)
if len(keys) >= number:
ret['comment'] = 'The number of keys exist for user {0}'.format(name)
ret['result'] = True
return ret
if __opts__['test']:
ret['comment'] = 'Access key is set to be created for {0}.'.format(name)
ret['result'] = None
return ret
new_keys = {}
for i in range(number-len(keys)):
created = __salt__['boto_iam.create_access_key'](name, region, key, keyid, profile)
if isinstance(created, six.string_types):
error, message = _get_error(created)
ret['comment'] = 'Could not create keys.\n{0}\n{1}'.format(error, message)
ret['result'] = False
return ret
log.debug('Created is : %s', created)
response = 'create_access_key_response'
result = 'create_access_key_result'
new_keys[six.text_type(i)] = {}
new_keys[six.text_type(i)]['key_id'] = created[response][result]['access_key']['access_key_id']
new_keys[six.text_type(i)]['secret_key'] = created[response][result]['access_key']['secret_access_key']
try:
with salt.utils.files.fopen('{0}/{1}'.format(save_dir, name), 'a') as _wrf:
for key_num, key in new_keys.items():
key_id = key['key_id']
secret_key = key['secret_key']
_wrf.write(salt.utils.stringutils.to_str(
save_format.format(
key_id,
secret_key,
'key_id-{0}'.format(key_num),
'key-{0}'.format(key_num)
)
))
ret['comment'] = 'Keys have been written to file {0}/{1}.'.format(save_dir, name)
ret['result'] = True
ret['changes'] = new_keys
return ret
except IOError:
ret['comment'] = 'Could not write to file {0}/{1}.'.format(save_dir, name)
ret['result'] = False
return ret
|
.. versionadded:: 2015.8.0
Ensure the IAM access keys are present.
name (string)
The name of the new user.
number (int)
Number of keys that user should have.
save_dir (string)
The directory that the key/keys will be saved. Keys are saved to a file named according
to the username privided.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
save_format (dict)
Save format is repeated for each key. Default format is
"{2}\\n{0}\\n{3}\\n{1}\\n", where {0} and {1} are placeholders for new
key_id and key respectively, whereas {2} and {3} are "key_id-{number}"
and 'key-{number}' strings kept for compatibility.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iam.py#L313-L414
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def _get_error(error):\n # Converts boto exception to string that can be used to output error.\n error = '\\n'.join(error.split('\\n')[1:])\n error = ET.fromstring(error)\n code = error[0][1].text\n message = error[0][2].text\n return code, message\n"
] |
# -*- coding: utf-8 -*-
'''
Manage IAM objects
==================
.. versionadded:: 2015.8.0
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit IAM credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
delete-user:
boto_iam.user_absent:
- name: myuser
- delete_keys: true
.. code-block:: yaml
delete-keys:
boto_iam.keys_absent:
- access_keys:
- 'AKIAJHTMIQ2ASDFLASDF'
- 'PQIAJHTMIQ2ASRTLASFR'
- user_name: myuser
.. code-block:: yaml
create-user:
boto_iam.user_present:
- name: myuser
- policies:
mypolicy: |
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"}]
}
- password: NewPassword$$1
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
create-group:
boto_iam.group_present:
- name: mygroup
- users:
- myuser
- myuser1
- policies:
mypolicy: |
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"}]
}
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
.. code-block:: yaml
change-policy:
boto_iam.account_policy:
- change_password: True
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
.. code-block:: yaml
create server certificate:
boto_iam.server_cert_present:
- name: mycert
- public_key: salt://base/mycert.crt
- private_key: salt://base/mycert.key
- cert_chain: salt://base/mycert_chain.crt
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
delete server certificate:
boto_iam.server_cert_absent:
- name: mycert
.. code-block:: yaml
create keys for user:
boto_iam.keys_present:
- name: myusername
- number: 2
- save_dir: /root
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
create policy:
boto_iam.policy_present:
- name: myname
- policy_document: '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}'
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
add-saml-provider:
boto_iam.saml_provider_present:
- name: my_saml_provider
- saml_metadata_document: salt://base/files/provider.xml
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
# Import Salt Libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.odict as odict
import salt.utils.dictupdate as dictupdate
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
# Import 3rd party libs
try:
from salt._compat import ElementTree as ET
HAS_ELEMENT_TREE = True
except ImportError:
HAS_ELEMENT_TREE = False
log = logging.getLogger(__name__)
__virtualname__ = 'boto_iam'
if six.PY2:
def _byteify(thing):
# Note that we intentionally don't treat odicts here - they won't
# compare equal in many circumstances where AWS treats them the same...
if isinstance(thing, dict):
return dict([(_byteify(k), _byteify(v)) for k, v in six.iteritems(thing)])
elif isinstance(thing, list):
return [_byteify(m) for m in thing]
elif isinstance(thing, six.text_type): # pylint: disable=W1699
return thing.encode('utf-8')
else:
return thing
else: # six.PY3
def _byteify(text):
return text
def __virtual__():
'''
Only load if elementtree xml library and boto are available.
'''
if not HAS_ELEMENT_TREE:
return (False, 'Cannot load {0} state: ElementTree library unavailable'.format(__virtualname__))
if 'boto_iam.get_user' in __salt__:
return True
else:
return (False, 'Cannot load {0} state: boto_iam module unavailable'.format(__virtualname__))
def user_absent(name, delete_keys=True, delete_mfa_devices=True, delete_profile=True, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user is absent. User cannot be deleted if it has keys.
name (string)
The name of the new user.
delete_keys (bool)
Delete all keys from user.
delete_mfa_devices (bool)
Delete all mfa devices from user.
.. versionadded:: 2016.3.0
delete_profile (bool)
Delete profile from user.
.. versionadded:: 2016.3.0
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](name, region, key, keyid, profile):
ret['result'] = True
ret['comment'] = 'IAM User {0} does not exist.'.format(name)
return ret
# delete the user's access keys
if delete_keys:
keys = __salt__['boto_iam.get_all_access_keys'](user_name=name, region=region, key=key,
keyid=keyid, profile=profile)
log.debug('Keys for user %s are %s.', name, keys)
if isinstance(keys, dict):
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
for k in keys:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'Key {0} is set to be deleted.'.format(k['access_key_id'])])
ret['result'] = None
else:
if _delete_key(ret, k['access_key_id'], name, region, key, keyid, profile):
ret['comment'] = ' '.join([ret['comment'], 'Key {0} has been deleted.'.format(k['access_key_id'])])
ret['changes'][k['access_key_id']] = 'deleted'
# delete the user's MFA tokens
if delete_mfa_devices:
devices = __salt__['boto_iam.get_all_mfa_devices'](user_name=name, region=region, key=key, keyid=keyid, profile=profile)
if devices:
for d in devices:
serial = d['serial_number']
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} MFA device {1} is set to be deactivated.'.format(name, serial)])
ret['result'] = None
else:
mfa_deactivated = __salt__['boto_iam.deactivate_mfa_device'](user_name=name, serial=serial, region=region, key=key, keyid=keyid, profile=profile)
if mfa_deactivated:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} MFA device {1} is deactivated.'.format(name, serial)])
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'Virtual MFA device {0} is set to be deleted.'.format(serial)])
ret['result'] = None
else:
mfa_deleted = __salt__['boto_iam.delete_virtual_mfa_device'](serial=serial, region=region, key=key, keyid=keyid, profile=profile)
if mfa_deleted:
ret['comment'] = ' '.join([ret['comment'], 'Virtual MFA device {0} is deleted.'.format(serial)])
# delete the user's login profile
if delete_profile:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} login profile is set to be deleted.'.format(name)])
ret['result'] = None
else:
profile_deleted = __salt__['boto_iam.delete_login_profile'](name, region, key, keyid, profile)
if profile_deleted:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} login profile is deleted.'.format(name)])
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} managed policies are set to be detached.'.format(name)])
ret['result'] = None
else:
_ret = _user_policies_detached(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} inline policies are set to be deleted.'.format(name)])
ret['result'] = None
else:
_ret = _user_policies_deleted(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
# finally, actually delete the user
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} is set to be deleted.'.format(name)])
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_user'](name, region, key, keyid, profile)
if deleted is True:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} is deleted.'.format(name)])
ret['result'] = True
ret['changes']['deleted'] = name
return ret
ret['comment'] = 'IAM user {0} could not be deleted.\n {1}'.format(name, deleted)
ret['result'] = False
return ret
def keys_absent(access_keys, user_name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user access_key_id is absent.
access_key_id (list)
A list of access key ids
user_name (string)
The username of the user
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': access_keys, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](user_name, region, key, keyid, profile):
ret['result'] = False
ret['comment'] = 'IAM User {0} does not exist.'.format(user_name)
return ret
for k in access_keys:
ret = _delete_key(ret, k, user_name, region, key, keyid, profile)
return ret
def _delete_key(ret, access_key_id, user_name, region=None, key=None, keyid=None, profile=None):
keys = __salt__['boto_iam.get_all_access_keys'](user_name=user_name, region=region, key=key,
keyid=keyid, profile=profile)
log.debug('Keys for user %s are : %s.', keys, user_name)
if isinstance(keys, six.string_types):
log.debug('Keys %s are a string. Something went wrong.', keys)
ret['comment'] = ' '.join([ret['comment'], 'Key {0} could not be deleted.'.format(access_key_id)])
return ret
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
for k in keys:
log.debug('Key is: %s and is compared with: %s', k['access_key_id'], access_key_id)
if six.text_type(k['access_key_id']) == six.text_type(access_key_id):
if __opts__['test']:
ret['comment'] = 'Access key {0} is set to be deleted.'.format(access_key_id)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_access_key'](access_key_id, user_name, region, key,
keyid, profile)
if deleted:
ret['comment'] = ' '.join([ret['comment'], 'Key {0} has been deleted.'.format(access_key_id)])
ret['changes'][access_key_id] = 'deleted'
return ret
ret['comment'] = ' '.join([ret['comment'], 'Key {0} could not be deleted.'.format(access_key_id)])
return ret
ret['comment'] = ' '.join([ret['comment'], 'Key {0} does not exist.'.format(k)])
return ret
def user_present(name, policies=None, policies_from_pillars=None, managed_policies=None, password=None, path=None,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user is present
name (string)
The name of the new user.
policies (dict)
A dict of IAM group policy documents.
policies_from_pillars (list)
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies (list)
A list of managed policy names or ARNs that should be attached to this
user.
password (string)
The password for the new user. Must comply with account policy.
path (string)
The path of the user. Default is '/'.
.. versionadded:: 2015.8.2
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
exists = __salt__['boto_iam.get_user'](name, region, key, keyid, profile)
if not exists:
if __opts__['test']:
ret['comment'] = 'IAM user {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_user'](name, path, region, key, keyid, profile)
if created:
ret['changes']['user'] = created
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been created.'.format(name)])
if password:
ret = _case_password(ret, name, password, region, key, keyid, profile)
_ret = _user_policies_present(name, _policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
else:
ret['comment'] = ' '.join([ret['comment'], 'User {0} is present.'.format(name)])
if password:
ret = _case_password(ret, name, password, region, key, keyid, profile)
_ret = _user_policies_present(name, _policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
_ret = _user_policies_attached(name, managed_policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
return ret
def _user_policies_present(name, policies=None, region=None, key=None, keyid=None, profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_create = {}
policies_to_delete = []
for policy_name, policy in six.iteritems(policies):
if isinstance(policy, six.string_types):
dict_policy = _byteify(salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict))
else:
dict_policy = _byteify(policy)
_policy = _byteify(__salt__['boto_iam.get_user_policy'](name, policy_name, region, key, keyid, profile))
if _policy != dict_policy:
log.debug("Policy mismatch:\n%s\n%s", _policy, dict_policy)
policies_to_create[policy_name] = policy
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
for policy_name in _list:
if policy_name not in policies:
policies_to_delete.append(policy_name)
if policies_to_create or policies_to_delete:
_to_modify = list(policies_to_delete)
_to_modify.extend(policies_to_create)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on user {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'policies': _list}
for policy_name, policy in six.iteritems(policies_to_create):
policy_set = __salt__['boto_iam.put_user_policy'](
name, policy_name, policy, region, key, keyid, profile
)
if not policy_set:
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} for user {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_delete:
policy_unset = __salt__['boto_iam.delete_user_policy'](
name, policy_name, region, key, keyid, profile
)
if not policy_unset:
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to user {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['comment'] = '{0} policies modified on user {1}.'.format(', '.join(_list), name)
return ret
def _user_policies_attached(
name,
managed_policies=None,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_attach = []
policies_to_detach = []
for policy in managed_policies or []:
entities = __salt__['boto_iam.list_entities_for_policy'](policy,
entity_filter='User',
region=region, key=key, keyid=keyid,
profile=profile)
found = False
for userdict in entities.get('policy_users', []):
if name == userdict.get('user_name'):
found = True
break
if not found:
policies_to_attach.append(policy)
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key, keyid=keyid,
profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
for policy_data in _list:
if policy_data.get('policy_name') not in managed_policies \
and policy_data.get('policy_arn') not in managed_policies:
policies_to_detach.append(policy_data.get('policy_arn'))
if policies_to_attach or policies_to_detach:
_to_modify = list(policies_to_detach)
_to_modify.extend(policies_to_attach)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on user {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_name in policies_to_attach:
policy_set = __salt__['boto_iam.attach_user_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_set:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to user {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_detach:
policy_unset = __salt__['boto_iam.detach_user_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to remove policy {0} from user {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
log.debug(newpolicies)
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies modified on user {1}.'.format(', '.join(newpolicies), name)
return ret
def _user_policies_detached(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
_list = __salt__['boto_iam.list_attached_user_policies'](user_name=name,
region=region, key=key, keyid=keyid, profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
if not _list:
ret['comment'] = 'No attached policies in user {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be detached from user {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_arn in oldpolicies:
policy_unset = __salt__['boto_iam.detach_user_policy'](policy_arn,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from user {1}'.format(policy_arn, name)
return ret
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies detached from user {1}.'.format(', '.join(oldpolicies), name)
return ret
def _user_policies_deleted(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
oldpolicies = __salt__['boto_iam.get_all_user_policies'](user_name=name,
region=region, key=key, keyid=keyid, profile=profile)
if not oldpolicies:
ret['comment'] = 'No inline policies in user {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be deleted from user {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'inline_policies': oldpolicies}
for policy_name in oldpolicies:
policy_deleted = __salt__['boto_iam.delete_user_policy'](name,
policy_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_deleted:
newpolicies = __salt__['boto_iam.get_all_user_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from user {1}'.format(policy_name, name)
return ret
newpolicies = __salt__['boto_iam.get_all_user_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['comment'] = '{0} policies deleted from user {1}.'.format(', '.join(oldpolicies), name)
return ret
def _case_password(ret, name, password, region=None, key=None, keyid=None, profile=None):
if __opts__['test']:
ret['comment'] = 'Login policy for {0} is set to be changed.'.format(name)
ret['result'] = None
return ret
login = __salt__['boto_iam.create_login_profile'](name, password, region, key, keyid, profile)
log.debug('Login is : %s.', login)
if login:
if 'Conflict' in login:
ret['comment'] = ' '.join([ret['comment'], 'Login profile for user {0} exists.'.format(name)])
else:
ret['comment'] = ' '.join([ret['comment'], 'Password has been added to User {0}.'.format(name)])
ret['changes']['password'] = 'REDACTED'
else:
ret['result'] = False
ret['comment'] = ' '.join([ret['comment'], 'Password for user {0} could not be set.\nPlease check your password policy.'.format(name)])
return ret
def group_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM group is absent.
name (string)
The name of the group.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_group'](name, region, key, keyid, profile):
ret['result'] = True
ret['comment'] = 'IAM Group {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} managed policies are set to be detached.'.format(name)])
ret['result'] = None
else:
_ret = _group_policies_detached(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} inline policies are set to be deleted.'.format(name)])
ret['result'] = None
else:
_ret = _group_policies_deleted(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} users are set to be removed.'.format(name)])
existing_users = __salt__['boto_iam.get_group_members'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
_ret = _case_group(ret, [], name, existing_users, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
# finally, actually delete the group
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} is set to be deleted.'.format(name)])
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_group'](name, region, key, keyid, profile)
if deleted is True:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} is deleted.'.format(name)])
ret['result'] = True
ret['changes']['deleted'] = name
return ret
ret['comment'] = 'IAM group {0} could not be deleted.\n {1}'.format(name, deleted)
ret['result'] = False
return ret
def group_present(name, policies=None, policies_from_pillars=None, managed_policies=None, users=None, path='/', region=None, key=None, keyid=None, profile=None, delete_policies=True):
'''
.. versionadded:: 2015.8.0
Ensure the IAM group is present
name (string)
The name of the new group.
path (string)
The path for the group, defaults to '/'
policies (dict)
A dict of IAM group policy documents.
policies_from_pillars (list)
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies (list)
A list of policy names or ARNs that should be attached to this group.
users (list)
A list of users to be added to the group.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
delete_policies (boolean)
Delete or detach existing policies that are not in the given list of policies.
Default value is ``True``. If ``False`` is specified, existing policies
will not be deleted or detached allowing manual modifications on the IAM group
to be persistent.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
exists = __salt__['boto_iam.get_group'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
if not exists:
if __opts__['test']:
ret['comment'] = 'IAM group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_group'](group_name=name, path=path, region=region, key=key, keyid=keyid, profile=profile)
if not created:
ret['comment'] = 'Failed to create IAM group {0}.'.format(name)
ret['result'] = False
return ret
ret['changes']['group'] = created
ret['comment'] = ' '.join([ret['comment'], 'Group {0} has been created.'.format(name)])
else:
ret['comment'] = ' '.join([ret['comment'], 'Group {0} is present.'.format(name)])
# Group exists, ensure group policies and users are set.
_ret = _group_policies_present(
name, _policies, region, key, keyid, profile, delete_policies
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
_ret = _group_policies_attached(name, managed_policies, region, key, keyid, profile, delete_policies)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
if users is not None:
log.debug('Users are : %s.', users)
existing_users = __salt__['boto_iam.get_group_members'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
ret = _case_group(ret, users, name, existing_users, region, key, keyid, profile)
return ret
def _case_group(ret, users, group_name, existing_users, region, key, keyid, profile):
_users = []
for user in existing_users:
_users.append(user['user_name'])
log.debug('upstream users are %s', _users)
for user in users:
log.debug('users are %s', user)
if user in _users:
log.debug('user exists')
ret['comment'] = ' '.join([ret['comment'], 'User {0} is already a member of group {1}.'.format(user, group_name)])
continue
else:
log.debug('user is set to be added %s', user)
if __opts__['test']:
ret['comment'] = 'User {0} is set to be added to group {1}.'.format(user, group_name)
ret['result'] = None
else:
__salt__['boto_iam.add_user_to_group'](user, group_name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been added to group {1}.'.format(user, group_name)])
ret['changes'][user] = group_name
for user in _users:
if user not in users:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'User {0} is set to be removed from group {1}.'.format(user, group_name)])
ret['result'] = None
else:
__salt__['boto_iam.remove_user_from_group'](group_name=group_name, user_name=user, region=region,
key=key, keyid=keyid, profile=profile)
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been removed from group {1}.'.format(user, group_name)])
ret['changes'][user] = 'Removed from group {0}.'.format(group_name)
return ret
def _group_policies_present(
name,
policies=None,
region=None,
key=None,
keyid=None,
profile=None,
delete_policies=True):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_create = {}
policies_to_delete = []
for policy_name, policy in six.iteritems(policies):
if isinstance(policy, six.string_types):
dict_policy = _byteify(salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict))
else:
dict_policy = _byteify(policy)
_policy = _byteify(__salt__['boto_iam.get_group_policy'](name, policy_name, region, key, keyid, profile))
if _policy != dict_policy:
log.debug("Policy mismatch:\n%s\n%s", _policy, dict_policy)
policies_to_create[policy_name] = policy
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
for policy_name in _list:
if delete_policies and policy_name not in policies:
policies_to_delete.append(policy_name)
if policies_to_create or policies_to_delete:
_to_modify = list(policies_to_delete)
_to_modify.extend(policies_to_create)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on group {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'policies': _list}
for policy_name, policy in six.iteritems(policies_to_create):
policy_set = __salt__['boto_iam.put_group_policy'](
name, policy_name, policy, region, key, keyid, profile
)
if not policy_set:
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_delete:
policy_unset = __salt__['boto_iam.delete_group_policy'](
name, policy_name, region, key, keyid, profile
)
if not policy_unset:
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['comment'] = '{0} policies modified on group {1}.'.format(', '.join(_list), name)
return ret
def _group_policies_attached(
name,
managed_policies=None,
region=None,
key=None,
keyid=None,
profile=None,
detach_policies=True):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_attach = []
policies_to_detach = []
for policy in managed_policies or []:
entities = __salt__['boto_iam.list_entities_for_policy'](policy,
entity_filter='Group',
region=region, key=key, keyid=keyid,
profile=profile)
found = False
for groupdict in entities.get('policy_groups', []):
if name == groupdict.get('group_name'):
found = True
break
if not found:
policies_to_attach.append(policy)
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key, keyid=keyid,
profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
for policy_data in _list:
if detach_policies \
and policy_data.get('policy_name') not in managed_policies \
and policy_data.get('policy_arn') not in managed_policies:
policies_to_detach.append(policy_data.get('policy_arn'))
if policies_to_attach or policies_to_detach:
_to_modify = list(policies_to_detach)
_to_modify.extend(policies_to_attach)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on group {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_name in policies_to_attach:
policy_set = __salt__['boto_iam.attach_group_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_set:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_detach:
policy_unset = __salt__['boto_iam.detach_group_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to remove policy {0} from group {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
log.debug(newpolicies)
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies modified on group {1}.'.format(', '.join(newpolicies), name)
return ret
def _group_policies_detached(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
_list = __salt__['boto_iam.list_attached_group_policies'](group_name=name,
region=region, key=key, keyid=keyid, profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
if not _list:
ret['comment'] = 'No attached policies in group {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be detached from group {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_arn in oldpolicies:
policy_unset = __salt__['boto_iam.detach_group_policy'](policy_arn,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from group {1}'.format(policy_arn, name)
return ret
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies detached from group {1}.'.format(', '.join(newpolicies), name)
return ret
def _group_policies_deleted(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
oldpolicies = __salt__['boto_iam.get_all_group_policies'](group_name=name,
region=region, key=key, keyid=keyid, profile=profile)
if not oldpolicies:
ret['comment'] = 'No inline policies in group {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be deleted from group {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'inline_policies': oldpolicies}
for policy_name in oldpolicies:
policy_deleted = __salt__['boto_iam.delete_group_policy'](name,
policy_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_deleted:
newpolicies = __salt__['boto_iam.get_all_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from group {1}'.format(policy_name, name)
return ret
newpolicies = __salt__['boto_iam.get_all_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['comment'] = '{0} policies deleted from group {1}.'.format(', '.join(oldpolicies), name)
return ret
def account_policy(name=None, allow_users_to_change_password=None,
hard_expiry=None, max_password_age=None,
minimum_password_length=None, password_reuse_prevention=None,
require_lowercase_characters=None, require_numbers=None,
require_symbols=None, require_uppercase_characters=None,
region=None, key=None, keyid=None, profile=None):
'''
Change account policy.
.. versionadded:: 2015.8.0
name (string)
The name of the account policy
allow_users_to_change_password (bool)
Allows all IAM users in your account to
use the AWS Management Console to change their own passwords.
hard_expiry (bool)
Prevents IAM users from setting a new password after their
password has expired.
max_password_age (int)
The number of days that an IAM user password is valid.
minimum_password_length (int)
The minimum number of characters allowed in an IAM user password.
password_reuse_prevention (int)
Specifies the number of previous passwords
that IAM users are prevented from reusing.
require_lowercase_characters (bool)
Specifies whether IAM user passwords
must contain at least one lowercase character from the ISO basic Latin alphabet (a to z).
require_numbers (bool)
Specifies whether IAM user passwords must contain at
least one numeric character (0 to 9).
require_symbols (bool)
Specifies whether IAM user passwords must contain at
least one of the following non-alphanumeric characters: ! @ # $ % ^ & * ( ) _ + - = [ ] { } | '
require_uppercase_characters (bool)
Specifies whether IAM user passwords must
contain at least one uppercase character from the ISO basic Latin alphabet (A to Z).
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
'''
config = locals()
ret = {'name': 'Account Policy', 'result': True, 'comment': '', 'changes': {}}
info = __salt__['boto_iam.get_account_policy'](region, key, keyid, profile)
if not info:
ret['comment'] = 'Account policy is not Enabled.'
ret['result'] = False
return ret
for key, value in config.items():
if key in ('region', 'key', 'keyid', 'profile', 'name'):
continue
if value is not None and six.text_type(info[key]) != six.text_type(value).lower():
ret['comment'] = ' '.join([ret['comment'], 'Policy value {0} has been set to {1}.'.format(value, info[key])])
ret['changes'][key] = six.text_type(value).lower()
if not ret['changes']:
ret['comment'] = 'Account policy is not changed.'
return ret
if __opts__['test']:
ret['comment'] = 'Account policy is set to be changed.'
ret['result'] = None
return ret
if __salt__['boto_iam.update_account_password_policy'](allow_users_to_change_password,
hard_expiry,
max_password_age,
minimum_password_length,
password_reuse_prevention,
require_lowercase_characters,
require_numbers,
require_symbols,
require_uppercase_characters,
region, key, keyid, profile):
return ret
ret['comment'] = 'Account policy is not changed.'
ret['changes'] = {}
ret['result'] = False
return ret
def server_cert_absent(name, region=None, key=None, keyid=None, profile=None):
'''
Deletes a server certificate.
.. versionadded:: 2015.8.0
name (string)
The name for the server certificate. Do not include the path in this value.
region (string)
The name of the region to connect to.
key (string)
The key to be used in order to connect
keyid (string)
The keyid to be used in order to connect
profile (string)
The profile that contains a dict of region, key, keyid
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_iam.get_server_certificate'](name, region, key, keyid, profile)
if not exists:
ret['comment'] = 'Certificate {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Server certificate {0} is set to be deleted.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_server_cert'](name, region, key, keyid, profile)
if not deleted:
ret['result'] = False
ret['comment'] = 'Certificate {0} failed to be deleted.'.format(name)
return ret
ret['comment'] = 'Certificate {0} was deleted.'.format(name)
ret['changes'] = deleted
return ret
def server_cert_present(name, public_key, private_key, cert_chain=None, path=None,
region=None, key=None, keyid=None, profile=None):
'''
Crete server certificate.
.. versionadded:: 2015.8.0
name (string)
The name for the server certificate. Do not include the path in this value.
public_key (string)
The contents of the public key certificate in PEM-encoded format.
private_key (string)
The contents of the private key in PEM-encoded format.
cert_chain (string)
The contents of the certificate chain. This is typically a
concatenation of the PEM-encoded public key certificates of the chain.
path (string)
The path for the server certificate.
region (string)
The name of the region to connect to.
key (string)
The key to be used in order to connect
keyid (string)
The keyid to be used in order to connect
profile (string)
The profile that contains a dict of region, key, keyid
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_iam.get_server_certificate'](name, region, key, keyid, profile)
log.debug('Variables are : %s.', locals())
if exists:
ret['comment'] = 'Certificate {0} exists.'.format(name)
return ret
if 'salt://' in public_key:
try:
public_key = __salt__['cp.get_file_str'](public_key)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(public_key)
ret['result'] = False
return ret
if 'salt://' in private_key:
try:
private_key = __salt__['cp.get_file_str'](private_key)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(private_key)
ret['result'] = False
return ret
if cert_chain is not None and 'salt://' in cert_chain:
try:
cert_chain = __salt__['cp.get_file_str'](cert_chain)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(cert_chain)
ret['result'] = False
return ret
if __opts__['test']:
ret['comment'] = 'Server certificate {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.upload_server_cert'](name, public_key, private_key, cert_chain,
path, region, key, keyid, profile)
if created is not False:
ret['comment'] = 'Certificate {0} was created.'.format(name)
ret['changes'] = created
return ret
ret['result'] = False
ret['comment'] = 'Certificate {0} failed to be created.'.format(name)
return ret
def policy_present(name, policy_document, path=None, description=None,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM managed policy is present
name (string)
The name of the new policy.
policy_document (dict)
The document of the new policy
path (string)
The path in which the policy will be created. Default is '/'.
description (string)
Description
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
policy = __salt__['boto_iam.get_policy'](name, region, key, keyid, profile)
if not policy:
if __opts__['test']:
ret['comment'] = 'IAM policy {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_policy'](name, policy_document, path, description, region, key, keyid, profile)
if created:
ret['changes']['policy'] = created
ret['comment'] = ' '.join([ret['comment'], 'Policy {0} has been created.'.format(name)])
else:
ret['result'] = False
ret['comment'] = 'Failed to update policy.'
ret['changes'] = {}
return ret
else:
policy = policy.get('policy', {})
ret['comment'] = ' '.join([ret['comment'], 'Policy {0} is present.'.format(name)])
_describe = __salt__['boto_iam.get_policy_version'](name, policy.get('default_version_id'),
region, key, keyid, profile).get('policy_version', {})
if isinstance(_describe['document'], six.string_types):
describeDict = salt.utils.json.loads(_describe['document'])
else:
describeDict = _describe['document']
if isinstance(policy_document, six.string_types):
policy_document = salt.utils.json.loads(policy_document)
r = salt.utils.data.compare_dicts(describeDict, policy_document)
if bool(r):
if __opts__['test']:
ret['comment'] = 'Policy {0} set to be modified.'.format(name)
ret['result'] = None
return ret
ret['comment'] = ' '.join([ret['comment'], 'Policy to be modified'])
policy_document = salt.utils.json.dumps(policy_document)
r = __salt__['boto_iam.create_policy_version'](policy_name=name,
policy_document=policy_document,
set_as_default=True,
region=region, key=key,
keyid=keyid, profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to update policy: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
__salt__['boto_iam.delete_policy_version'](policy_name=name,
version_id=policy['default_version_id'],
region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'].setdefault('new', {})['document'] = policy_document
ret['changes'].setdefault('old', {})['document'] = _describe['document']
return ret
def policy_absent(name,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM managed policy with the specified name is absent
name (string)
The name of the new policy.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
r = __salt__['boto_iam.policy_exists'](name,
region=region, key=key, keyid=keyid, profile=profile)
if not r:
ret['comment'] = 'Policy {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
# delete non-default versions
versions = __salt__['boto_iam.list_policy_versions'](name,
region=region, key=key,
keyid=keyid, profile=profile)
if versions:
for version in versions:
if version.get('is_default_version', False) in ('true', True):
continue
r = __salt__['boto_iam.delete_policy_version'](name,
version_id=version.get('version_id'),
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
ret['result'] = False
ret['comment'] = 'Failed to delete policy {0}.'.format(name)
return ret
r = __salt__['boto_iam.delete_policy'](name,
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
ret['result'] = False
ret['comment'] = 'Failed to delete policy {0}.'.format(name)
return ret
ret['changes']['old'] = {'policy': name}
ret['changes']['new'] = {'policy': None}
ret['comment'] = 'Policy {0} deleted.'.format(name)
return ret
def saml_provider_present(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is present.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if 'salt://' in saml_metadata_document:
try:
saml_metadata_document = __salt__['cp.get_file_str'](saml_metadata_document)
ET.fromstring(saml_metadata_document)
except IOError as e:
log.debug(e)
ret['comment'] = 'SAML document file {0} not found or could not be loaded'.format(name)
ret['result'] = False
return ret
for provider in __salt__['boto_iam.list_saml_providers'](region=region,
key=key, keyid=keyid,
profile=profile):
if provider == name:
ret['comment'] = 'SAML provider {0} is present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'SAML provider {0} is set to be create.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_saml_provider'](name, saml_metadata_document,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['comment'] = 'SAML provider {0} was created.'.format(name)
ret['changes']['new'] = name
return ret
ret['result'] = False
ret['comment'] = 'SAML provider {0} failed to be created.'.format(name)
return ret
def saml_provider_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is absent.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
provider = __salt__['boto_iam.list_saml_providers'](region=region,
key=key, keyid=keyid,
profile=profile)
if not provider:
ret['comment'] = 'SAML provider {0} is absent.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'SAML provider {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_saml_provider'](name, region=region,
key=key, keyid=keyid,
profile=profile)
if deleted is not False:
ret['comment'] = 'SAML provider {0} was deleted.'.format(name)
ret['changes']['old'] = name
return ret
ret['result'] = False
ret['comment'] = 'SAML provider {0} failed to be deleted.'.format(name)
return ret
def _get_error(error):
# Converts boto exception to string that can be used to output error.
error = '\n'.join(error.split('\n')[1:])
error = ET.fromstring(error)
code = error[0][1].text
message = error[0][2].text
return code, message
|
saltstack/salt
|
salt/states/boto_iam.py
|
account_policy
|
python
|
def account_policy(name=None, allow_users_to_change_password=None,
hard_expiry=None, max_password_age=None,
minimum_password_length=None, password_reuse_prevention=None,
require_lowercase_characters=None, require_numbers=None,
require_symbols=None, require_uppercase_characters=None,
region=None, key=None, keyid=None, profile=None):
'''
Change account policy.
.. versionadded:: 2015.8.0
name (string)
The name of the account policy
allow_users_to_change_password (bool)
Allows all IAM users in your account to
use the AWS Management Console to change their own passwords.
hard_expiry (bool)
Prevents IAM users from setting a new password after their
password has expired.
max_password_age (int)
The number of days that an IAM user password is valid.
minimum_password_length (int)
The minimum number of characters allowed in an IAM user password.
password_reuse_prevention (int)
Specifies the number of previous passwords
that IAM users are prevented from reusing.
require_lowercase_characters (bool)
Specifies whether IAM user passwords
must contain at least one lowercase character from the ISO basic Latin alphabet (a to z).
require_numbers (bool)
Specifies whether IAM user passwords must contain at
least one numeric character (0 to 9).
require_symbols (bool)
Specifies whether IAM user passwords must contain at
least one of the following non-alphanumeric characters: ! @ # $ % ^ & * ( ) _ + - = [ ] { } | '
require_uppercase_characters (bool)
Specifies whether IAM user passwords must
contain at least one uppercase character from the ISO basic Latin alphabet (A to Z).
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
'''
config = locals()
ret = {'name': 'Account Policy', 'result': True, 'comment': '', 'changes': {}}
info = __salt__['boto_iam.get_account_policy'](region, key, keyid, profile)
if not info:
ret['comment'] = 'Account policy is not Enabled.'
ret['result'] = False
return ret
for key, value in config.items():
if key in ('region', 'key', 'keyid', 'profile', 'name'):
continue
if value is not None and six.text_type(info[key]) != six.text_type(value).lower():
ret['comment'] = ' '.join([ret['comment'], 'Policy value {0} has been set to {1}.'.format(value, info[key])])
ret['changes'][key] = six.text_type(value).lower()
if not ret['changes']:
ret['comment'] = 'Account policy is not changed.'
return ret
if __opts__['test']:
ret['comment'] = 'Account policy is set to be changed.'
ret['result'] = None
return ret
if __salt__['boto_iam.update_account_password_policy'](allow_users_to_change_password,
hard_expiry,
max_password_age,
minimum_password_length,
password_reuse_prevention,
require_lowercase_characters,
require_numbers,
require_symbols,
require_uppercase_characters,
region, key, keyid, profile):
return ret
ret['comment'] = 'Account policy is not changed.'
ret['changes'] = {}
ret['result'] = False
return ret
|
Change account policy.
.. versionadded:: 2015.8.0
name (string)
The name of the account policy
allow_users_to_change_password (bool)
Allows all IAM users in your account to
use the AWS Management Console to change their own passwords.
hard_expiry (bool)
Prevents IAM users from setting a new password after their
password has expired.
max_password_age (int)
The number of days that an IAM user password is valid.
minimum_password_length (int)
The minimum number of characters allowed in an IAM user password.
password_reuse_prevention (int)
Specifies the number of previous passwords
that IAM users are prevented from reusing.
require_lowercase_characters (bool)
Specifies whether IAM user passwords
must contain at least one lowercase character from the ISO basic Latin alphabet (a to z).
require_numbers (bool)
Specifies whether IAM user passwords must contain at
least one numeric character (0 to 9).
require_symbols (bool)
Specifies whether IAM user passwords must contain at
least one of the following non-alphanumeric characters: ! @ # $ % ^ & * ( ) _ + - = [ ] { } | '
require_uppercase_characters (bool)
Specifies whether IAM user passwords must
contain at least one uppercase character from the ISO basic Latin alphabet (A to Z).
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iam.py#L1235-L1329
| null |
# -*- coding: utf-8 -*-
'''
Manage IAM objects
==================
.. versionadded:: 2015.8.0
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit IAM credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
delete-user:
boto_iam.user_absent:
- name: myuser
- delete_keys: true
.. code-block:: yaml
delete-keys:
boto_iam.keys_absent:
- access_keys:
- 'AKIAJHTMIQ2ASDFLASDF'
- 'PQIAJHTMIQ2ASRTLASFR'
- user_name: myuser
.. code-block:: yaml
create-user:
boto_iam.user_present:
- name: myuser
- policies:
mypolicy: |
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"}]
}
- password: NewPassword$$1
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
create-group:
boto_iam.group_present:
- name: mygroup
- users:
- myuser
- myuser1
- policies:
mypolicy: |
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"}]
}
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
.. code-block:: yaml
change-policy:
boto_iam.account_policy:
- change_password: True
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
.. code-block:: yaml
create server certificate:
boto_iam.server_cert_present:
- name: mycert
- public_key: salt://base/mycert.crt
- private_key: salt://base/mycert.key
- cert_chain: salt://base/mycert_chain.crt
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
delete server certificate:
boto_iam.server_cert_absent:
- name: mycert
.. code-block:: yaml
create keys for user:
boto_iam.keys_present:
- name: myusername
- number: 2
- save_dir: /root
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
create policy:
boto_iam.policy_present:
- name: myname
- policy_document: '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}'
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
add-saml-provider:
boto_iam.saml_provider_present:
- name: my_saml_provider
- saml_metadata_document: salt://base/files/provider.xml
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
# Import Salt Libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.odict as odict
import salt.utils.dictupdate as dictupdate
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
# Import 3rd party libs
try:
from salt._compat import ElementTree as ET
HAS_ELEMENT_TREE = True
except ImportError:
HAS_ELEMENT_TREE = False
log = logging.getLogger(__name__)
__virtualname__ = 'boto_iam'
if six.PY2:
def _byteify(thing):
# Note that we intentionally don't treat odicts here - they won't
# compare equal in many circumstances where AWS treats them the same...
if isinstance(thing, dict):
return dict([(_byteify(k), _byteify(v)) for k, v in six.iteritems(thing)])
elif isinstance(thing, list):
return [_byteify(m) for m in thing]
elif isinstance(thing, six.text_type): # pylint: disable=W1699
return thing.encode('utf-8')
else:
return thing
else: # six.PY3
def _byteify(text):
return text
def __virtual__():
'''
Only load if elementtree xml library and boto are available.
'''
if not HAS_ELEMENT_TREE:
return (False, 'Cannot load {0} state: ElementTree library unavailable'.format(__virtualname__))
if 'boto_iam.get_user' in __salt__:
return True
else:
return (False, 'Cannot load {0} state: boto_iam module unavailable'.format(__virtualname__))
def user_absent(name, delete_keys=True, delete_mfa_devices=True, delete_profile=True, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user is absent. User cannot be deleted if it has keys.
name (string)
The name of the new user.
delete_keys (bool)
Delete all keys from user.
delete_mfa_devices (bool)
Delete all mfa devices from user.
.. versionadded:: 2016.3.0
delete_profile (bool)
Delete profile from user.
.. versionadded:: 2016.3.0
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](name, region, key, keyid, profile):
ret['result'] = True
ret['comment'] = 'IAM User {0} does not exist.'.format(name)
return ret
# delete the user's access keys
if delete_keys:
keys = __salt__['boto_iam.get_all_access_keys'](user_name=name, region=region, key=key,
keyid=keyid, profile=profile)
log.debug('Keys for user %s are %s.', name, keys)
if isinstance(keys, dict):
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
for k in keys:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'Key {0} is set to be deleted.'.format(k['access_key_id'])])
ret['result'] = None
else:
if _delete_key(ret, k['access_key_id'], name, region, key, keyid, profile):
ret['comment'] = ' '.join([ret['comment'], 'Key {0} has been deleted.'.format(k['access_key_id'])])
ret['changes'][k['access_key_id']] = 'deleted'
# delete the user's MFA tokens
if delete_mfa_devices:
devices = __salt__['boto_iam.get_all_mfa_devices'](user_name=name, region=region, key=key, keyid=keyid, profile=profile)
if devices:
for d in devices:
serial = d['serial_number']
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} MFA device {1} is set to be deactivated.'.format(name, serial)])
ret['result'] = None
else:
mfa_deactivated = __salt__['boto_iam.deactivate_mfa_device'](user_name=name, serial=serial, region=region, key=key, keyid=keyid, profile=profile)
if mfa_deactivated:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} MFA device {1} is deactivated.'.format(name, serial)])
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'Virtual MFA device {0} is set to be deleted.'.format(serial)])
ret['result'] = None
else:
mfa_deleted = __salt__['boto_iam.delete_virtual_mfa_device'](serial=serial, region=region, key=key, keyid=keyid, profile=profile)
if mfa_deleted:
ret['comment'] = ' '.join([ret['comment'], 'Virtual MFA device {0} is deleted.'.format(serial)])
# delete the user's login profile
if delete_profile:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} login profile is set to be deleted.'.format(name)])
ret['result'] = None
else:
profile_deleted = __salt__['boto_iam.delete_login_profile'](name, region, key, keyid, profile)
if profile_deleted:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} login profile is deleted.'.format(name)])
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} managed policies are set to be detached.'.format(name)])
ret['result'] = None
else:
_ret = _user_policies_detached(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} inline policies are set to be deleted.'.format(name)])
ret['result'] = None
else:
_ret = _user_policies_deleted(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
# finally, actually delete the user
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} is set to be deleted.'.format(name)])
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_user'](name, region, key, keyid, profile)
if deleted is True:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} is deleted.'.format(name)])
ret['result'] = True
ret['changes']['deleted'] = name
return ret
ret['comment'] = 'IAM user {0} could not be deleted.\n {1}'.format(name, deleted)
ret['result'] = False
return ret
def keys_present(name, number, save_dir, region=None, key=None, keyid=None, profile=None,
save_format="{2}\n{0}\n{3}\n{1}\n"):
'''
.. versionadded:: 2015.8.0
Ensure the IAM access keys are present.
name (string)
The name of the new user.
number (int)
Number of keys that user should have.
save_dir (string)
The directory that the key/keys will be saved. Keys are saved to a file named according
to the username privided.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
save_format (dict)
Save format is repeated for each key. Default format is
"{2}\\n{0}\\n{3}\\n{1}\\n", where {0} and {1} are placeholders for new
key_id and key respectively, whereas {2} and {3} are "key_id-{number}"
and 'key-{number}' strings kept for compatibility.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](name, region, key, keyid, profile):
ret['result'] = False
ret['comment'] = 'IAM User {0} does not exist.'.format(name)
return ret
if not isinstance(number, int):
ret['comment'] = 'The number of keys must be an integer.'
ret['result'] = False
return ret
if not os.path.isdir(save_dir):
ret['comment'] = 'The directory {0} does not exist.'.format(save_dir)
ret['result'] = False
return ret
keys = __salt__['boto_iam.get_all_access_keys'](user_name=name, region=region, key=key,
keyid=keyid, profile=profile)
if isinstance(keys, six.string_types):
log.debug('keys are : false %s', keys)
error, message = _get_error(keys)
ret['comment'] = 'Could not get keys.\n{0}\n{1}'.format(error, message)
ret['result'] = False
return ret
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
log.debug('Keys are : %s.', keys)
if len(keys) >= number:
ret['comment'] = 'The number of keys exist for user {0}'.format(name)
ret['result'] = True
return ret
if __opts__['test']:
ret['comment'] = 'Access key is set to be created for {0}.'.format(name)
ret['result'] = None
return ret
new_keys = {}
for i in range(number-len(keys)):
created = __salt__['boto_iam.create_access_key'](name, region, key, keyid, profile)
if isinstance(created, six.string_types):
error, message = _get_error(created)
ret['comment'] = 'Could not create keys.\n{0}\n{1}'.format(error, message)
ret['result'] = False
return ret
log.debug('Created is : %s', created)
response = 'create_access_key_response'
result = 'create_access_key_result'
new_keys[six.text_type(i)] = {}
new_keys[six.text_type(i)]['key_id'] = created[response][result]['access_key']['access_key_id']
new_keys[six.text_type(i)]['secret_key'] = created[response][result]['access_key']['secret_access_key']
try:
with salt.utils.files.fopen('{0}/{1}'.format(save_dir, name), 'a') as _wrf:
for key_num, key in new_keys.items():
key_id = key['key_id']
secret_key = key['secret_key']
_wrf.write(salt.utils.stringutils.to_str(
save_format.format(
key_id,
secret_key,
'key_id-{0}'.format(key_num),
'key-{0}'.format(key_num)
)
))
ret['comment'] = 'Keys have been written to file {0}/{1}.'.format(save_dir, name)
ret['result'] = True
ret['changes'] = new_keys
return ret
except IOError:
ret['comment'] = 'Could not write to file {0}/{1}.'.format(save_dir, name)
ret['result'] = False
return ret
def keys_absent(access_keys, user_name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user access_key_id is absent.
access_key_id (list)
A list of access key ids
user_name (string)
The username of the user
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': access_keys, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](user_name, region, key, keyid, profile):
ret['result'] = False
ret['comment'] = 'IAM User {0} does not exist.'.format(user_name)
return ret
for k in access_keys:
ret = _delete_key(ret, k, user_name, region, key, keyid, profile)
return ret
def _delete_key(ret, access_key_id, user_name, region=None, key=None, keyid=None, profile=None):
keys = __salt__['boto_iam.get_all_access_keys'](user_name=user_name, region=region, key=key,
keyid=keyid, profile=profile)
log.debug('Keys for user %s are : %s.', keys, user_name)
if isinstance(keys, six.string_types):
log.debug('Keys %s are a string. Something went wrong.', keys)
ret['comment'] = ' '.join([ret['comment'], 'Key {0} could not be deleted.'.format(access_key_id)])
return ret
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
for k in keys:
log.debug('Key is: %s and is compared with: %s', k['access_key_id'], access_key_id)
if six.text_type(k['access_key_id']) == six.text_type(access_key_id):
if __opts__['test']:
ret['comment'] = 'Access key {0} is set to be deleted.'.format(access_key_id)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_access_key'](access_key_id, user_name, region, key,
keyid, profile)
if deleted:
ret['comment'] = ' '.join([ret['comment'], 'Key {0} has been deleted.'.format(access_key_id)])
ret['changes'][access_key_id] = 'deleted'
return ret
ret['comment'] = ' '.join([ret['comment'], 'Key {0} could not be deleted.'.format(access_key_id)])
return ret
ret['comment'] = ' '.join([ret['comment'], 'Key {0} does not exist.'.format(k)])
return ret
def user_present(name, policies=None, policies_from_pillars=None, managed_policies=None, password=None, path=None,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user is present
name (string)
The name of the new user.
policies (dict)
A dict of IAM group policy documents.
policies_from_pillars (list)
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies (list)
A list of managed policy names or ARNs that should be attached to this
user.
password (string)
The password for the new user. Must comply with account policy.
path (string)
The path of the user. Default is '/'.
.. versionadded:: 2015.8.2
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
exists = __salt__['boto_iam.get_user'](name, region, key, keyid, profile)
if not exists:
if __opts__['test']:
ret['comment'] = 'IAM user {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_user'](name, path, region, key, keyid, profile)
if created:
ret['changes']['user'] = created
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been created.'.format(name)])
if password:
ret = _case_password(ret, name, password, region, key, keyid, profile)
_ret = _user_policies_present(name, _policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
else:
ret['comment'] = ' '.join([ret['comment'], 'User {0} is present.'.format(name)])
if password:
ret = _case_password(ret, name, password, region, key, keyid, profile)
_ret = _user_policies_present(name, _policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
_ret = _user_policies_attached(name, managed_policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
return ret
def _user_policies_present(name, policies=None, region=None, key=None, keyid=None, profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_create = {}
policies_to_delete = []
for policy_name, policy in six.iteritems(policies):
if isinstance(policy, six.string_types):
dict_policy = _byteify(salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict))
else:
dict_policy = _byteify(policy)
_policy = _byteify(__salt__['boto_iam.get_user_policy'](name, policy_name, region, key, keyid, profile))
if _policy != dict_policy:
log.debug("Policy mismatch:\n%s\n%s", _policy, dict_policy)
policies_to_create[policy_name] = policy
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
for policy_name in _list:
if policy_name not in policies:
policies_to_delete.append(policy_name)
if policies_to_create or policies_to_delete:
_to_modify = list(policies_to_delete)
_to_modify.extend(policies_to_create)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on user {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'policies': _list}
for policy_name, policy in six.iteritems(policies_to_create):
policy_set = __salt__['boto_iam.put_user_policy'](
name, policy_name, policy, region, key, keyid, profile
)
if not policy_set:
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} for user {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_delete:
policy_unset = __salt__['boto_iam.delete_user_policy'](
name, policy_name, region, key, keyid, profile
)
if not policy_unset:
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to user {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['comment'] = '{0} policies modified on user {1}.'.format(', '.join(_list), name)
return ret
def _user_policies_attached(
name,
managed_policies=None,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_attach = []
policies_to_detach = []
for policy in managed_policies or []:
entities = __salt__['boto_iam.list_entities_for_policy'](policy,
entity_filter='User',
region=region, key=key, keyid=keyid,
profile=profile)
found = False
for userdict in entities.get('policy_users', []):
if name == userdict.get('user_name'):
found = True
break
if not found:
policies_to_attach.append(policy)
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key, keyid=keyid,
profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
for policy_data in _list:
if policy_data.get('policy_name') not in managed_policies \
and policy_data.get('policy_arn') not in managed_policies:
policies_to_detach.append(policy_data.get('policy_arn'))
if policies_to_attach or policies_to_detach:
_to_modify = list(policies_to_detach)
_to_modify.extend(policies_to_attach)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on user {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_name in policies_to_attach:
policy_set = __salt__['boto_iam.attach_user_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_set:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to user {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_detach:
policy_unset = __salt__['boto_iam.detach_user_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to remove policy {0} from user {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
log.debug(newpolicies)
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies modified on user {1}.'.format(', '.join(newpolicies), name)
return ret
def _user_policies_detached(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
_list = __salt__['boto_iam.list_attached_user_policies'](user_name=name,
region=region, key=key, keyid=keyid, profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
if not _list:
ret['comment'] = 'No attached policies in user {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be detached from user {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_arn in oldpolicies:
policy_unset = __salt__['boto_iam.detach_user_policy'](policy_arn,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from user {1}'.format(policy_arn, name)
return ret
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies detached from user {1}.'.format(', '.join(oldpolicies), name)
return ret
def _user_policies_deleted(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
oldpolicies = __salt__['boto_iam.get_all_user_policies'](user_name=name,
region=region, key=key, keyid=keyid, profile=profile)
if not oldpolicies:
ret['comment'] = 'No inline policies in user {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be deleted from user {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'inline_policies': oldpolicies}
for policy_name in oldpolicies:
policy_deleted = __salt__['boto_iam.delete_user_policy'](name,
policy_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_deleted:
newpolicies = __salt__['boto_iam.get_all_user_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from user {1}'.format(policy_name, name)
return ret
newpolicies = __salt__['boto_iam.get_all_user_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['comment'] = '{0} policies deleted from user {1}.'.format(', '.join(oldpolicies), name)
return ret
def _case_password(ret, name, password, region=None, key=None, keyid=None, profile=None):
if __opts__['test']:
ret['comment'] = 'Login policy for {0} is set to be changed.'.format(name)
ret['result'] = None
return ret
login = __salt__['boto_iam.create_login_profile'](name, password, region, key, keyid, profile)
log.debug('Login is : %s.', login)
if login:
if 'Conflict' in login:
ret['comment'] = ' '.join([ret['comment'], 'Login profile for user {0} exists.'.format(name)])
else:
ret['comment'] = ' '.join([ret['comment'], 'Password has been added to User {0}.'.format(name)])
ret['changes']['password'] = 'REDACTED'
else:
ret['result'] = False
ret['comment'] = ' '.join([ret['comment'], 'Password for user {0} could not be set.\nPlease check your password policy.'.format(name)])
return ret
def group_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM group is absent.
name (string)
The name of the group.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_group'](name, region, key, keyid, profile):
ret['result'] = True
ret['comment'] = 'IAM Group {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} managed policies are set to be detached.'.format(name)])
ret['result'] = None
else:
_ret = _group_policies_detached(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} inline policies are set to be deleted.'.format(name)])
ret['result'] = None
else:
_ret = _group_policies_deleted(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} users are set to be removed.'.format(name)])
existing_users = __salt__['boto_iam.get_group_members'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
_ret = _case_group(ret, [], name, existing_users, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
# finally, actually delete the group
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} is set to be deleted.'.format(name)])
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_group'](name, region, key, keyid, profile)
if deleted is True:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} is deleted.'.format(name)])
ret['result'] = True
ret['changes']['deleted'] = name
return ret
ret['comment'] = 'IAM group {0} could not be deleted.\n {1}'.format(name, deleted)
ret['result'] = False
return ret
def group_present(name, policies=None, policies_from_pillars=None, managed_policies=None, users=None, path='/', region=None, key=None, keyid=None, profile=None, delete_policies=True):
'''
.. versionadded:: 2015.8.0
Ensure the IAM group is present
name (string)
The name of the new group.
path (string)
The path for the group, defaults to '/'
policies (dict)
A dict of IAM group policy documents.
policies_from_pillars (list)
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies (list)
A list of policy names or ARNs that should be attached to this group.
users (list)
A list of users to be added to the group.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
delete_policies (boolean)
Delete or detach existing policies that are not in the given list of policies.
Default value is ``True``. If ``False`` is specified, existing policies
will not be deleted or detached allowing manual modifications on the IAM group
to be persistent.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
exists = __salt__['boto_iam.get_group'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
if not exists:
if __opts__['test']:
ret['comment'] = 'IAM group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_group'](group_name=name, path=path, region=region, key=key, keyid=keyid, profile=profile)
if not created:
ret['comment'] = 'Failed to create IAM group {0}.'.format(name)
ret['result'] = False
return ret
ret['changes']['group'] = created
ret['comment'] = ' '.join([ret['comment'], 'Group {0} has been created.'.format(name)])
else:
ret['comment'] = ' '.join([ret['comment'], 'Group {0} is present.'.format(name)])
# Group exists, ensure group policies and users are set.
_ret = _group_policies_present(
name, _policies, region, key, keyid, profile, delete_policies
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
_ret = _group_policies_attached(name, managed_policies, region, key, keyid, profile, delete_policies)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
if users is not None:
log.debug('Users are : %s.', users)
existing_users = __salt__['boto_iam.get_group_members'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
ret = _case_group(ret, users, name, existing_users, region, key, keyid, profile)
return ret
def _case_group(ret, users, group_name, existing_users, region, key, keyid, profile):
_users = []
for user in existing_users:
_users.append(user['user_name'])
log.debug('upstream users are %s', _users)
for user in users:
log.debug('users are %s', user)
if user in _users:
log.debug('user exists')
ret['comment'] = ' '.join([ret['comment'], 'User {0} is already a member of group {1}.'.format(user, group_name)])
continue
else:
log.debug('user is set to be added %s', user)
if __opts__['test']:
ret['comment'] = 'User {0} is set to be added to group {1}.'.format(user, group_name)
ret['result'] = None
else:
__salt__['boto_iam.add_user_to_group'](user, group_name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been added to group {1}.'.format(user, group_name)])
ret['changes'][user] = group_name
for user in _users:
if user not in users:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'User {0} is set to be removed from group {1}.'.format(user, group_name)])
ret['result'] = None
else:
__salt__['boto_iam.remove_user_from_group'](group_name=group_name, user_name=user, region=region,
key=key, keyid=keyid, profile=profile)
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been removed from group {1}.'.format(user, group_name)])
ret['changes'][user] = 'Removed from group {0}.'.format(group_name)
return ret
def _group_policies_present(
name,
policies=None,
region=None,
key=None,
keyid=None,
profile=None,
delete_policies=True):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_create = {}
policies_to_delete = []
for policy_name, policy in six.iteritems(policies):
if isinstance(policy, six.string_types):
dict_policy = _byteify(salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict))
else:
dict_policy = _byteify(policy)
_policy = _byteify(__salt__['boto_iam.get_group_policy'](name, policy_name, region, key, keyid, profile))
if _policy != dict_policy:
log.debug("Policy mismatch:\n%s\n%s", _policy, dict_policy)
policies_to_create[policy_name] = policy
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
for policy_name in _list:
if delete_policies and policy_name not in policies:
policies_to_delete.append(policy_name)
if policies_to_create or policies_to_delete:
_to_modify = list(policies_to_delete)
_to_modify.extend(policies_to_create)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on group {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'policies': _list}
for policy_name, policy in six.iteritems(policies_to_create):
policy_set = __salt__['boto_iam.put_group_policy'](
name, policy_name, policy, region, key, keyid, profile
)
if not policy_set:
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_delete:
policy_unset = __salt__['boto_iam.delete_group_policy'](
name, policy_name, region, key, keyid, profile
)
if not policy_unset:
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['comment'] = '{0} policies modified on group {1}.'.format(', '.join(_list), name)
return ret
def _group_policies_attached(
name,
managed_policies=None,
region=None,
key=None,
keyid=None,
profile=None,
detach_policies=True):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_attach = []
policies_to_detach = []
for policy in managed_policies or []:
entities = __salt__['boto_iam.list_entities_for_policy'](policy,
entity_filter='Group',
region=region, key=key, keyid=keyid,
profile=profile)
found = False
for groupdict in entities.get('policy_groups', []):
if name == groupdict.get('group_name'):
found = True
break
if not found:
policies_to_attach.append(policy)
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key, keyid=keyid,
profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
for policy_data in _list:
if detach_policies \
and policy_data.get('policy_name') not in managed_policies \
and policy_data.get('policy_arn') not in managed_policies:
policies_to_detach.append(policy_data.get('policy_arn'))
if policies_to_attach or policies_to_detach:
_to_modify = list(policies_to_detach)
_to_modify.extend(policies_to_attach)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on group {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_name in policies_to_attach:
policy_set = __salt__['boto_iam.attach_group_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_set:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_detach:
policy_unset = __salt__['boto_iam.detach_group_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to remove policy {0} from group {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
log.debug(newpolicies)
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies modified on group {1}.'.format(', '.join(newpolicies), name)
return ret
def _group_policies_detached(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
_list = __salt__['boto_iam.list_attached_group_policies'](group_name=name,
region=region, key=key, keyid=keyid, profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
if not _list:
ret['comment'] = 'No attached policies in group {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be detached from group {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_arn in oldpolicies:
policy_unset = __salt__['boto_iam.detach_group_policy'](policy_arn,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from group {1}'.format(policy_arn, name)
return ret
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies detached from group {1}.'.format(', '.join(newpolicies), name)
return ret
def _group_policies_deleted(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
oldpolicies = __salt__['boto_iam.get_all_group_policies'](group_name=name,
region=region, key=key, keyid=keyid, profile=profile)
if not oldpolicies:
ret['comment'] = 'No inline policies in group {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be deleted from group {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'inline_policies': oldpolicies}
for policy_name in oldpolicies:
policy_deleted = __salt__['boto_iam.delete_group_policy'](name,
policy_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_deleted:
newpolicies = __salt__['boto_iam.get_all_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from group {1}'.format(policy_name, name)
return ret
newpolicies = __salt__['boto_iam.get_all_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['comment'] = '{0} policies deleted from group {1}.'.format(', '.join(oldpolicies), name)
return ret
def server_cert_absent(name, region=None, key=None, keyid=None, profile=None):
'''
Deletes a server certificate.
.. versionadded:: 2015.8.0
name (string)
The name for the server certificate. Do not include the path in this value.
region (string)
The name of the region to connect to.
key (string)
The key to be used in order to connect
keyid (string)
The keyid to be used in order to connect
profile (string)
The profile that contains a dict of region, key, keyid
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_iam.get_server_certificate'](name, region, key, keyid, profile)
if not exists:
ret['comment'] = 'Certificate {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Server certificate {0} is set to be deleted.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_server_cert'](name, region, key, keyid, profile)
if not deleted:
ret['result'] = False
ret['comment'] = 'Certificate {0} failed to be deleted.'.format(name)
return ret
ret['comment'] = 'Certificate {0} was deleted.'.format(name)
ret['changes'] = deleted
return ret
def server_cert_present(name, public_key, private_key, cert_chain=None, path=None,
region=None, key=None, keyid=None, profile=None):
'''
Crete server certificate.
.. versionadded:: 2015.8.0
name (string)
The name for the server certificate. Do not include the path in this value.
public_key (string)
The contents of the public key certificate in PEM-encoded format.
private_key (string)
The contents of the private key in PEM-encoded format.
cert_chain (string)
The contents of the certificate chain. This is typically a
concatenation of the PEM-encoded public key certificates of the chain.
path (string)
The path for the server certificate.
region (string)
The name of the region to connect to.
key (string)
The key to be used in order to connect
keyid (string)
The keyid to be used in order to connect
profile (string)
The profile that contains a dict of region, key, keyid
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_iam.get_server_certificate'](name, region, key, keyid, profile)
log.debug('Variables are : %s.', locals())
if exists:
ret['comment'] = 'Certificate {0} exists.'.format(name)
return ret
if 'salt://' in public_key:
try:
public_key = __salt__['cp.get_file_str'](public_key)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(public_key)
ret['result'] = False
return ret
if 'salt://' in private_key:
try:
private_key = __salt__['cp.get_file_str'](private_key)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(private_key)
ret['result'] = False
return ret
if cert_chain is not None and 'salt://' in cert_chain:
try:
cert_chain = __salt__['cp.get_file_str'](cert_chain)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(cert_chain)
ret['result'] = False
return ret
if __opts__['test']:
ret['comment'] = 'Server certificate {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.upload_server_cert'](name, public_key, private_key, cert_chain,
path, region, key, keyid, profile)
if created is not False:
ret['comment'] = 'Certificate {0} was created.'.format(name)
ret['changes'] = created
return ret
ret['result'] = False
ret['comment'] = 'Certificate {0} failed to be created.'.format(name)
return ret
def policy_present(name, policy_document, path=None, description=None,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM managed policy is present
name (string)
The name of the new policy.
policy_document (dict)
The document of the new policy
path (string)
The path in which the policy will be created. Default is '/'.
description (string)
Description
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
policy = __salt__['boto_iam.get_policy'](name, region, key, keyid, profile)
if not policy:
if __opts__['test']:
ret['comment'] = 'IAM policy {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_policy'](name, policy_document, path, description, region, key, keyid, profile)
if created:
ret['changes']['policy'] = created
ret['comment'] = ' '.join([ret['comment'], 'Policy {0} has been created.'.format(name)])
else:
ret['result'] = False
ret['comment'] = 'Failed to update policy.'
ret['changes'] = {}
return ret
else:
policy = policy.get('policy', {})
ret['comment'] = ' '.join([ret['comment'], 'Policy {0} is present.'.format(name)])
_describe = __salt__['boto_iam.get_policy_version'](name, policy.get('default_version_id'),
region, key, keyid, profile).get('policy_version', {})
if isinstance(_describe['document'], six.string_types):
describeDict = salt.utils.json.loads(_describe['document'])
else:
describeDict = _describe['document']
if isinstance(policy_document, six.string_types):
policy_document = salt.utils.json.loads(policy_document)
r = salt.utils.data.compare_dicts(describeDict, policy_document)
if bool(r):
if __opts__['test']:
ret['comment'] = 'Policy {0} set to be modified.'.format(name)
ret['result'] = None
return ret
ret['comment'] = ' '.join([ret['comment'], 'Policy to be modified'])
policy_document = salt.utils.json.dumps(policy_document)
r = __salt__['boto_iam.create_policy_version'](policy_name=name,
policy_document=policy_document,
set_as_default=True,
region=region, key=key,
keyid=keyid, profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to update policy: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
__salt__['boto_iam.delete_policy_version'](policy_name=name,
version_id=policy['default_version_id'],
region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'].setdefault('new', {})['document'] = policy_document
ret['changes'].setdefault('old', {})['document'] = _describe['document']
return ret
def policy_absent(name,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM managed policy with the specified name is absent
name (string)
The name of the new policy.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
r = __salt__['boto_iam.policy_exists'](name,
region=region, key=key, keyid=keyid, profile=profile)
if not r:
ret['comment'] = 'Policy {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
# delete non-default versions
versions = __salt__['boto_iam.list_policy_versions'](name,
region=region, key=key,
keyid=keyid, profile=profile)
if versions:
for version in versions:
if version.get('is_default_version', False) in ('true', True):
continue
r = __salt__['boto_iam.delete_policy_version'](name,
version_id=version.get('version_id'),
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
ret['result'] = False
ret['comment'] = 'Failed to delete policy {0}.'.format(name)
return ret
r = __salt__['boto_iam.delete_policy'](name,
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
ret['result'] = False
ret['comment'] = 'Failed to delete policy {0}.'.format(name)
return ret
ret['changes']['old'] = {'policy': name}
ret['changes']['new'] = {'policy': None}
ret['comment'] = 'Policy {0} deleted.'.format(name)
return ret
def saml_provider_present(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is present.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if 'salt://' in saml_metadata_document:
try:
saml_metadata_document = __salt__['cp.get_file_str'](saml_metadata_document)
ET.fromstring(saml_metadata_document)
except IOError as e:
log.debug(e)
ret['comment'] = 'SAML document file {0} not found or could not be loaded'.format(name)
ret['result'] = False
return ret
for provider in __salt__['boto_iam.list_saml_providers'](region=region,
key=key, keyid=keyid,
profile=profile):
if provider == name:
ret['comment'] = 'SAML provider {0} is present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'SAML provider {0} is set to be create.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_saml_provider'](name, saml_metadata_document,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['comment'] = 'SAML provider {0} was created.'.format(name)
ret['changes']['new'] = name
return ret
ret['result'] = False
ret['comment'] = 'SAML provider {0} failed to be created.'.format(name)
return ret
def saml_provider_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is absent.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
provider = __salt__['boto_iam.list_saml_providers'](region=region,
key=key, keyid=keyid,
profile=profile)
if not provider:
ret['comment'] = 'SAML provider {0} is absent.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'SAML provider {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_saml_provider'](name, region=region,
key=key, keyid=keyid,
profile=profile)
if deleted is not False:
ret['comment'] = 'SAML provider {0} was deleted.'.format(name)
ret['changes']['old'] = name
return ret
ret['result'] = False
ret['comment'] = 'SAML provider {0} failed to be deleted.'.format(name)
return ret
def _get_error(error):
# Converts boto exception to string that can be used to output error.
error = '\n'.join(error.split('\n')[1:])
error = ET.fromstring(error)
code = error[0][1].text
message = error[0][2].text
return code, message
|
saltstack/salt
|
salt/states/boto_iam.py
|
server_cert_present
|
python
|
def server_cert_present(name, public_key, private_key, cert_chain=None, path=None,
region=None, key=None, keyid=None, profile=None):
'''
Crete server certificate.
.. versionadded:: 2015.8.0
name (string)
The name for the server certificate. Do not include the path in this value.
public_key (string)
The contents of the public key certificate in PEM-encoded format.
private_key (string)
The contents of the private key in PEM-encoded format.
cert_chain (string)
The contents of the certificate chain. This is typically a
concatenation of the PEM-encoded public key certificates of the chain.
path (string)
The path for the server certificate.
region (string)
The name of the region to connect to.
key (string)
The key to be used in order to connect
keyid (string)
The keyid to be used in order to connect
profile (string)
The profile that contains a dict of region, key, keyid
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_iam.get_server_certificate'](name, region, key, keyid, profile)
log.debug('Variables are : %s.', locals())
if exists:
ret['comment'] = 'Certificate {0} exists.'.format(name)
return ret
if 'salt://' in public_key:
try:
public_key = __salt__['cp.get_file_str'](public_key)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(public_key)
ret['result'] = False
return ret
if 'salt://' in private_key:
try:
private_key = __salt__['cp.get_file_str'](private_key)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(private_key)
ret['result'] = False
return ret
if cert_chain is not None and 'salt://' in cert_chain:
try:
cert_chain = __salt__['cp.get_file_str'](cert_chain)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(cert_chain)
ret['result'] = False
return ret
if __opts__['test']:
ret['comment'] = 'Server certificate {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.upload_server_cert'](name, public_key, private_key, cert_chain,
path, region, key, keyid, profile)
if created is not False:
ret['comment'] = 'Certificate {0} was created.'.format(name)
ret['changes'] = created
return ret
ret['result'] = False
ret['comment'] = 'Certificate {0} failed to be created.'.format(name)
return ret
|
Crete server certificate.
.. versionadded:: 2015.8.0
name (string)
The name for the server certificate. Do not include the path in this value.
public_key (string)
The contents of the public key certificate in PEM-encoded format.
private_key (string)
The contents of the private key in PEM-encoded format.
cert_chain (string)
The contents of the certificate chain. This is typically a
concatenation of the PEM-encoded public key certificates of the chain.
path (string)
The path for the server certificate.
region (string)
The name of the region to connect to.
key (string)
The key to be used in order to connect
keyid (string)
The keyid to be used in order to connect
profile (string)
The profile that contains a dict of region, key, keyid
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iam.py#L1372-L1449
| null |
# -*- coding: utf-8 -*-
'''
Manage IAM objects
==================
.. versionadded:: 2015.8.0
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit IAM credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
delete-user:
boto_iam.user_absent:
- name: myuser
- delete_keys: true
.. code-block:: yaml
delete-keys:
boto_iam.keys_absent:
- access_keys:
- 'AKIAJHTMIQ2ASDFLASDF'
- 'PQIAJHTMIQ2ASRTLASFR'
- user_name: myuser
.. code-block:: yaml
create-user:
boto_iam.user_present:
- name: myuser
- policies:
mypolicy: |
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"}]
}
- password: NewPassword$$1
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
create-group:
boto_iam.group_present:
- name: mygroup
- users:
- myuser
- myuser1
- policies:
mypolicy: |
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"}]
}
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
.. code-block:: yaml
change-policy:
boto_iam.account_policy:
- change_password: True
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
.. code-block:: yaml
create server certificate:
boto_iam.server_cert_present:
- name: mycert
- public_key: salt://base/mycert.crt
- private_key: salt://base/mycert.key
- cert_chain: salt://base/mycert_chain.crt
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
delete server certificate:
boto_iam.server_cert_absent:
- name: mycert
.. code-block:: yaml
create keys for user:
boto_iam.keys_present:
- name: myusername
- number: 2
- save_dir: /root
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
create policy:
boto_iam.policy_present:
- name: myname
- policy_document: '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}'
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
add-saml-provider:
boto_iam.saml_provider_present:
- name: my_saml_provider
- saml_metadata_document: salt://base/files/provider.xml
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
# Import Salt Libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.odict as odict
import salt.utils.dictupdate as dictupdate
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
# Import 3rd party libs
try:
from salt._compat import ElementTree as ET
HAS_ELEMENT_TREE = True
except ImportError:
HAS_ELEMENT_TREE = False
log = logging.getLogger(__name__)
__virtualname__ = 'boto_iam'
if six.PY2:
def _byteify(thing):
# Note that we intentionally don't treat odicts here - they won't
# compare equal in many circumstances where AWS treats them the same...
if isinstance(thing, dict):
return dict([(_byteify(k), _byteify(v)) for k, v in six.iteritems(thing)])
elif isinstance(thing, list):
return [_byteify(m) for m in thing]
elif isinstance(thing, six.text_type): # pylint: disable=W1699
return thing.encode('utf-8')
else:
return thing
else: # six.PY3
def _byteify(text):
return text
def __virtual__():
'''
Only load if elementtree xml library and boto are available.
'''
if not HAS_ELEMENT_TREE:
return (False, 'Cannot load {0} state: ElementTree library unavailable'.format(__virtualname__))
if 'boto_iam.get_user' in __salt__:
return True
else:
return (False, 'Cannot load {0} state: boto_iam module unavailable'.format(__virtualname__))
def user_absent(name, delete_keys=True, delete_mfa_devices=True, delete_profile=True, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user is absent. User cannot be deleted if it has keys.
name (string)
The name of the new user.
delete_keys (bool)
Delete all keys from user.
delete_mfa_devices (bool)
Delete all mfa devices from user.
.. versionadded:: 2016.3.0
delete_profile (bool)
Delete profile from user.
.. versionadded:: 2016.3.0
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](name, region, key, keyid, profile):
ret['result'] = True
ret['comment'] = 'IAM User {0} does not exist.'.format(name)
return ret
# delete the user's access keys
if delete_keys:
keys = __salt__['boto_iam.get_all_access_keys'](user_name=name, region=region, key=key,
keyid=keyid, profile=profile)
log.debug('Keys for user %s are %s.', name, keys)
if isinstance(keys, dict):
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
for k in keys:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'Key {0} is set to be deleted.'.format(k['access_key_id'])])
ret['result'] = None
else:
if _delete_key(ret, k['access_key_id'], name, region, key, keyid, profile):
ret['comment'] = ' '.join([ret['comment'], 'Key {0} has been deleted.'.format(k['access_key_id'])])
ret['changes'][k['access_key_id']] = 'deleted'
# delete the user's MFA tokens
if delete_mfa_devices:
devices = __salt__['boto_iam.get_all_mfa_devices'](user_name=name, region=region, key=key, keyid=keyid, profile=profile)
if devices:
for d in devices:
serial = d['serial_number']
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} MFA device {1} is set to be deactivated.'.format(name, serial)])
ret['result'] = None
else:
mfa_deactivated = __salt__['boto_iam.deactivate_mfa_device'](user_name=name, serial=serial, region=region, key=key, keyid=keyid, profile=profile)
if mfa_deactivated:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} MFA device {1} is deactivated.'.format(name, serial)])
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'Virtual MFA device {0} is set to be deleted.'.format(serial)])
ret['result'] = None
else:
mfa_deleted = __salt__['boto_iam.delete_virtual_mfa_device'](serial=serial, region=region, key=key, keyid=keyid, profile=profile)
if mfa_deleted:
ret['comment'] = ' '.join([ret['comment'], 'Virtual MFA device {0} is deleted.'.format(serial)])
# delete the user's login profile
if delete_profile:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} login profile is set to be deleted.'.format(name)])
ret['result'] = None
else:
profile_deleted = __salt__['boto_iam.delete_login_profile'](name, region, key, keyid, profile)
if profile_deleted:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} login profile is deleted.'.format(name)])
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} managed policies are set to be detached.'.format(name)])
ret['result'] = None
else:
_ret = _user_policies_detached(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} inline policies are set to be deleted.'.format(name)])
ret['result'] = None
else:
_ret = _user_policies_deleted(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
# finally, actually delete the user
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} is set to be deleted.'.format(name)])
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_user'](name, region, key, keyid, profile)
if deleted is True:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} is deleted.'.format(name)])
ret['result'] = True
ret['changes']['deleted'] = name
return ret
ret['comment'] = 'IAM user {0} could not be deleted.\n {1}'.format(name, deleted)
ret['result'] = False
return ret
def keys_present(name, number, save_dir, region=None, key=None, keyid=None, profile=None,
save_format="{2}\n{0}\n{3}\n{1}\n"):
'''
.. versionadded:: 2015.8.0
Ensure the IAM access keys are present.
name (string)
The name of the new user.
number (int)
Number of keys that user should have.
save_dir (string)
The directory that the key/keys will be saved. Keys are saved to a file named according
to the username privided.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
save_format (dict)
Save format is repeated for each key. Default format is
"{2}\\n{0}\\n{3}\\n{1}\\n", where {0} and {1} are placeholders for new
key_id and key respectively, whereas {2} and {3} are "key_id-{number}"
and 'key-{number}' strings kept for compatibility.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](name, region, key, keyid, profile):
ret['result'] = False
ret['comment'] = 'IAM User {0} does not exist.'.format(name)
return ret
if not isinstance(number, int):
ret['comment'] = 'The number of keys must be an integer.'
ret['result'] = False
return ret
if not os.path.isdir(save_dir):
ret['comment'] = 'The directory {0} does not exist.'.format(save_dir)
ret['result'] = False
return ret
keys = __salt__['boto_iam.get_all_access_keys'](user_name=name, region=region, key=key,
keyid=keyid, profile=profile)
if isinstance(keys, six.string_types):
log.debug('keys are : false %s', keys)
error, message = _get_error(keys)
ret['comment'] = 'Could not get keys.\n{0}\n{1}'.format(error, message)
ret['result'] = False
return ret
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
log.debug('Keys are : %s.', keys)
if len(keys) >= number:
ret['comment'] = 'The number of keys exist for user {0}'.format(name)
ret['result'] = True
return ret
if __opts__['test']:
ret['comment'] = 'Access key is set to be created for {0}.'.format(name)
ret['result'] = None
return ret
new_keys = {}
for i in range(number-len(keys)):
created = __salt__['boto_iam.create_access_key'](name, region, key, keyid, profile)
if isinstance(created, six.string_types):
error, message = _get_error(created)
ret['comment'] = 'Could not create keys.\n{0}\n{1}'.format(error, message)
ret['result'] = False
return ret
log.debug('Created is : %s', created)
response = 'create_access_key_response'
result = 'create_access_key_result'
new_keys[six.text_type(i)] = {}
new_keys[six.text_type(i)]['key_id'] = created[response][result]['access_key']['access_key_id']
new_keys[six.text_type(i)]['secret_key'] = created[response][result]['access_key']['secret_access_key']
try:
with salt.utils.files.fopen('{0}/{1}'.format(save_dir, name), 'a') as _wrf:
for key_num, key in new_keys.items():
key_id = key['key_id']
secret_key = key['secret_key']
_wrf.write(salt.utils.stringutils.to_str(
save_format.format(
key_id,
secret_key,
'key_id-{0}'.format(key_num),
'key-{0}'.format(key_num)
)
))
ret['comment'] = 'Keys have been written to file {0}/{1}.'.format(save_dir, name)
ret['result'] = True
ret['changes'] = new_keys
return ret
except IOError:
ret['comment'] = 'Could not write to file {0}/{1}.'.format(save_dir, name)
ret['result'] = False
return ret
def keys_absent(access_keys, user_name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user access_key_id is absent.
access_key_id (list)
A list of access key ids
user_name (string)
The username of the user
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': access_keys, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](user_name, region, key, keyid, profile):
ret['result'] = False
ret['comment'] = 'IAM User {0} does not exist.'.format(user_name)
return ret
for k in access_keys:
ret = _delete_key(ret, k, user_name, region, key, keyid, profile)
return ret
def _delete_key(ret, access_key_id, user_name, region=None, key=None, keyid=None, profile=None):
keys = __salt__['boto_iam.get_all_access_keys'](user_name=user_name, region=region, key=key,
keyid=keyid, profile=profile)
log.debug('Keys for user %s are : %s.', keys, user_name)
if isinstance(keys, six.string_types):
log.debug('Keys %s are a string. Something went wrong.', keys)
ret['comment'] = ' '.join([ret['comment'], 'Key {0} could not be deleted.'.format(access_key_id)])
return ret
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
for k in keys:
log.debug('Key is: %s and is compared with: %s', k['access_key_id'], access_key_id)
if six.text_type(k['access_key_id']) == six.text_type(access_key_id):
if __opts__['test']:
ret['comment'] = 'Access key {0} is set to be deleted.'.format(access_key_id)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_access_key'](access_key_id, user_name, region, key,
keyid, profile)
if deleted:
ret['comment'] = ' '.join([ret['comment'], 'Key {0} has been deleted.'.format(access_key_id)])
ret['changes'][access_key_id] = 'deleted'
return ret
ret['comment'] = ' '.join([ret['comment'], 'Key {0} could not be deleted.'.format(access_key_id)])
return ret
ret['comment'] = ' '.join([ret['comment'], 'Key {0} does not exist.'.format(k)])
return ret
def user_present(name, policies=None, policies_from_pillars=None, managed_policies=None, password=None, path=None,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user is present
name (string)
The name of the new user.
policies (dict)
A dict of IAM group policy documents.
policies_from_pillars (list)
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies (list)
A list of managed policy names or ARNs that should be attached to this
user.
password (string)
The password for the new user. Must comply with account policy.
path (string)
The path of the user. Default is '/'.
.. versionadded:: 2015.8.2
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
exists = __salt__['boto_iam.get_user'](name, region, key, keyid, profile)
if not exists:
if __opts__['test']:
ret['comment'] = 'IAM user {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_user'](name, path, region, key, keyid, profile)
if created:
ret['changes']['user'] = created
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been created.'.format(name)])
if password:
ret = _case_password(ret, name, password, region, key, keyid, profile)
_ret = _user_policies_present(name, _policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
else:
ret['comment'] = ' '.join([ret['comment'], 'User {0} is present.'.format(name)])
if password:
ret = _case_password(ret, name, password, region, key, keyid, profile)
_ret = _user_policies_present(name, _policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
_ret = _user_policies_attached(name, managed_policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
return ret
def _user_policies_present(name, policies=None, region=None, key=None, keyid=None, profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_create = {}
policies_to_delete = []
for policy_name, policy in six.iteritems(policies):
if isinstance(policy, six.string_types):
dict_policy = _byteify(salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict))
else:
dict_policy = _byteify(policy)
_policy = _byteify(__salt__['boto_iam.get_user_policy'](name, policy_name, region, key, keyid, profile))
if _policy != dict_policy:
log.debug("Policy mismatch:\n%s\n%s", _policy, dict_policy)
policies_to_create[policy_name] = policy
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
for policy_name in _list:
if policy_name not in policies:
policies_to_delete.append(policy_name)
if policies_to_create or policies_to_delete:
_to_modify = list(policies_to_delete)
_to_modify.extend(policies_to_create)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on user {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'policies': _list}
for policy_name, policy in six.iteritems(policies_to_create):
policy_set = __salt__['boto_iam.put_user_policy'](
name, policy_name, policy, region, key, keyid, profile
)
if not policy_set:
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} for user {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_delete:
policy_unset = __salt__['boto_iam.delete_user_policy'](
name, policy_name, region, key, keyid, profile
)
if not policy_unset:
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to user {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['comment'] = '{0} policies modified on user {1}.'.format(', '.join(_list), name)
return ret
def _user_policies_attached(
name,
managed_policies=None,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_attach = []
policies_to_detach = []
for policy in managed_policies or []:
entities = __salt__['boto_iam.list_entities_for_policy'](policy,
entity_filter='User',
region=region, key=key, keyid=keyid,
profile=profile)
found = False
for userdict in entities.get('policy_users', []):
if name == userdict.get('user_name'):
found = True
break
if not found:
policies_to_attach.append(policy)
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key, keyid=keyid,
profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
for policy_data in _list:
if policy_data.get('policy_name') not in managed_policies \
and policy_data.get('policy_arn') not in managed_policies:
policies_to_detach.append(policy_data.get('policy_arn'))
if policies_to_attach or policies_to_detach:
_to_modify = list(policies_to_detach)
_to_modify.extend(policies_to_attach)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on user {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_name in policies_to_attach:
policy_set = __salt__['boto_iam.attach_user_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_set:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to user {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_detach:
policy_unset = __salt__['boto_iam.detach_user_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to remove policy {0} from user {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
log.debug(newpolicies)
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies modified on user {1}.'.format(', '.join(newpolicies), name)
return ret
def _user_policies_detached(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
_list = __salt__['boto_iam.list_attached_user_policies'](user_name=name,
region=region, key=key, keyid=keyid, profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
if not _list:
ret['comment'] = 'No attached policies in user {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be detached from user {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_arn in oldpolicies:
policy_unset = __salt__['boto_iam.detach_user_policy'](policy_arn,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from user {1}'.format(policy_arn, name)
return ret
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies detached from user {1}.'.format(', '.join(oldpolicies), name)
return ret
def _user_policies_deleted(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
oldpolicies = __salt__['boto_iam.get_all_user_policies'](user_name=name,
region=region, key=key, keyid=keyid, profile=profile)
if not oldpolicies:
ret['comment'] = 'No inline policies in user {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be deleted from user {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'inline_policies': oldpolicies}
for policy_name in oldpolicies:
policy_deleted = __salt__['boto_iam.delete_user_policy'](name,
policy_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_deleted:
newpolicies = __salt__['boto_iam.get_all_user_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from user {1}'.format(policy_name, name)
return ret
newpolicies = __salt__['boto_iam.get_all_user_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['comment'] = '{0} policies deleted from user {1}.'.format(', '.join(oldpolicies), name)
return ret
def _case_password(ret, name, password, region=None, key=None, keyid=None, profile=None):
if __opts__['test']:
ret['comment'] = 'Login policy for {0} is set to be changed.'.format(name)
ret['result'] = None
return ret
login = __salt__['boto_iam.create_login_profile'](name, password, region, key, keyid, profile)
log.debug('Login is : %s.', login)
if login:
if 'Conflict' in login:
ret['comment'] = ' '.join([ret['comment'], 'Login profile for user {0} exists.'.format(name)])
else:
ret['comment'] = ' '.join([ret['comment'], 'Password has been added to User {0}.'.format(name)])
ret['changes']['password'] = 'REDACTED'
else:
ret['result'] = False
ret['comment'] = ' '.join([ret['comment'], 'Password for user {0} could not be set.\nPlease check your password policy.'.format(name)])
return ret
def group_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM group is absent.
name (string)
The name of the group.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_group'](name, region, key, keyid, profile):
ret['result'] = True
ret['comment'] = 'IAM Group {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} managed policies are set to be detached.'.format(name)])
ret['result'] = None
else:
_ret = _group_policies_detached(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} inline policies are set to be deleted.'.format(name)])
ret['result'] = None
else:
_ret = _group_policies_deleted(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} users are set to be removed.'.format(name)])
existing_users = __salt__['boto_iam.get_group_members'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
_ret = _case_group(ret, [], name, existing_users, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
# finally, actually delete the group
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} is set to be deleted.'.format(name)])
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_group'](name, region, key, keyid, profile)
if deleted is True:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} is deleted.'.format(name)])
ret['result'] = True
ret['changes']['deleted'] = name
return ret
ret['comment'] = 'IAM group {0} could not be deleted.\n {1}'.format(name, deleted)
ret['result'] = False
return ret
def group_present(name, policies=None, policies_from_pillars=None, managed_policies=None, users=None, path='/', region=None, key=None, keyid=None, profile=None, delete_policies=True):
'''
.. versionadded:: 2015.8.0
Ensure the IAM group is present
name (string)
The name of the new group.
path (string)
The path for the group, defaults to '/'
policies (dict)
A dict of IAM group policy documents.
policies_from_pillars (list)
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies (list)
A list of policy names or ARNs that should be attached to this group.
users (list)
A list of users to be added to the group.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
delete_policies (boolean)
Delete or detach existing policies that are not in the given list of policies.
Default value is ``True``. If ``False`` is specified, existing policies
will not be deleted or detached allowing manual modifications on the IAM group
to be persistent.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
exists = __salt__['boto_iam.get_group'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
if not exists:
if __opts__['test']:
ret['comment'] = 'IAM group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_group'](group_name=name, path=path, region=region, key=key, keyid=keyid, profile=profile)
if not created:
ret['comment'] = 'Failed to create IAM group {0}.'.format(name)
ret['result'] = False
return ret
ret['changes']['group'] = created
ret['comment'] = ' '.join([ret['comment'], 'Group {0} has been created.'.format(name)])
else:
ret['comment'] = ' '.join([ret['comment'], 'Group {0} is present.'.format(name)])
# Group exists, ensure group policies and users are set.
_ret = _group_policies_present(
name, _policies, region, key, keyid, profile, delete_policies
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
_ret = _group_policies_attached(name, managed_policies, region, key, keyid, profile, delete_policies)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
if users is not None:
log.debug('Users are : %s.', users)
existing_users = __salt__['boto_iam.get_group_members'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
ret = _case_group(ret, users, name, existing_users, region, key, keyid, profile)
return ret
def _case_group(ret, users, group_name, existing_users, region, key, keyid, profile):
_users = []
for user in existing_users:
_users.append(user['user_name'])
log.debug('upstream users are %s', _users)
for user in users:
log.debug('users are %s', user)
if user in _users:
log.debug('user exists')
ret['comment'] = ' '.join([ret['comment'], 'User {0} is already a member of group {1}.'.format(user, group_name)])
continue
else:
log.debug('user is set to be added %s', user)
if __opts__['test']:
ret['comment'] = 'User {0} is set to be added to group {1}.'.format(user, group_name)
ret['result'] = None
else:
__salt__['boto_iam.add_user_to_group'](user, group_name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been added to group {1}.'.format(user, group_name)])
ret['changes'][user] = group_name
for user in _users:
if user not in users:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'User {0} is set to be removed from group {1}.'.format(user, group_name)])
ret['result'] = None
else:
__salt__['boto_iam.remove_user_from_group'](group_name=group_name, user_name=user, region=region,
key=key, keyid=keyid, profile=profile)
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been removed from group {1}.'.format(user, group_name)])
ret['changes'][user] = 'Removed from group {0}.'.format(group_name)
return ret
def _group_policies_present(
name,
policies=None,
region=None,
key=None,
keyid=None,
profile=None,
delete_policies=True):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_create = {}
policies_to_delete = []
for policy_name, policy in six.iteritems(policies):
if isinstance(policy, six.string_types):
dict_policy = _byteify(salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict))
else:
dict_policy = _byteify(policy)
_policy = _byteify(__salt__['boto_iam.get_group_policy'](name, policy_name, region, key, keyid, profile))
if _policy != dict_policy:
log.debug("Policy mismatch:\n%s\n%s", _policy, dict_policy)
policies_to_create[policy_name] = policy
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
for policy_name in _list:
if delete_policies and policy_name not in policies:
policies_to_delete.append(policy_name)
if policies_to_create or policies_to_delete:
_to_modify = list(policies_to_delete)
_to_modify.extend(policies_to_create)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on group {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'policies': _list}
for policy_name, policy in six.iteritems(policies_to_create):
policy_set = __salt__['boto_iam.put_group_policy'](
name, policy_name, policy, region, key, keyid, profile
)
if not policy_set:
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_delete:
policy_unset = __salt__['boto_iam.delete_group_policy'](
name, policy_name, region, key, keyid, profile
)
if not policy_unset:
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['comment'] = '{0} policies modified on group {1}.'.format(', '.join(_list), name)
return ret
def _group_policies_attached(
name,
managed_policies=None,
region=None,
key=None,
keyid=None,
profile=None,
detach_policies=True):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_attach = []
policies_to_detach = []
for policy in managed_policies or []:
entities = __salt__['boto_iam.list_entities_for_policy'](policy,
entity_filter='Group',
region=region, key=key, keyid=keyid,
profile=profile)
found = False
for groupdict in entities.get('policy_groups', []):
if name == groupdict.get('group_name'):
found = True
break
if not found:
policies_to_attach.append(policy)
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key, keyid=keyid,
profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
for policy_data in _list:
if detach_policies \
and policy_data.get('policy_name') not in managed_policies \
and policy_data.get('policy_arn') not in managed_policies:
policies_to_detach.append(policy_data.get('policy_arn'))
if policies_to_attach or policies_to_detach:
_to_modify = list(policies_to_detach)
_to_modify.extend(policies_to_attach)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on group {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_name in policies_to_attach:
policy_set = __salt__['boto_iam.attach_group_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_set:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_detach:
policy_unset = __salt__['boto_iam.detach_group_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to remove policy {0} from group {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
log.debug(newpolicies)
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies modified on group {1}.'.format(', '.join(newpolicies), name)
return ret
def _group_policies_detached(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
_list = __salt__['boto_iam.list_attached_group_policies'](group_name=name,
region=region, key=key, keyid=keyid, profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
if not _list:
ret['comment'] = 'No attached policies in group {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be detached from group {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_arn in oldpolicies:
policy_unset = __salt__['boto_iam.detach_group_policy'](policy_arn,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from group {1}'.format(policy_arn, name)
return ret
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies detached from group {1}.'.format(', '.join(newpolicies), name)
return ret
def _group_policies_deleted(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
oldpolicies = __salt__['boto_iam.get_all_group_policies'](group_name=name,
region=region, key=key, keyid=keyid, profile=profile)
if not oldpolicies:
ret['comment'] = 'No inline policies in group {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be deleted from group {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'inline_policies': oldpolicies}
for policy_name in oldpolicies:
policy_deleted = __salt__['boto_iam.delete_group_policy'](name,
policy_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_deleted:
newpolicies = __salt__['boto_iam.get_all_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from group {1}'.format(policy_name, name)
return ret
newpolicies = __salt__['boto_iam.get_all_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['comment'] = '{0} policies deleted from group {1}.'.format(', '.join(oldpolicies), name)
return ret
def account_policy(name=None, allow_users_to_change_password=None,
hard_expiry=None, max_password_age=None,
minimum_password_length=None, password_reuse_prevention=None,
require_lowercase_characters=None, require_numbers=None,
require_symbols=None, require_uppercase_characters=None,
region=None, key=None, keyid=None, profile=None):
'''
Change account policy.
.. versionadded:: 2015.8.0
name (string)
The name of the account policy
allow_users_to_change_password (bool)
Allows all IAM users in your account to
use the AWS Management Console to change their own passwords.
hard_expiry (bool)
Prevents IAM users from setting a new password after their
password has expired.
max_password_age (int)
The number of days that an IAM user password is valid.
minimum_password_length (int)
The minimum number of characters allowed in an IAM user password.
password_reuse_prevention (int)
Specifies the number of previous passwords
that IAM users are prevented from reusing.
require_lowercase_characters (bool)
Specifies whether IAM user passwords
must contain at least one lowercase character from the ISO basic Latin alphabet (a to z).
require_numbers (bool)
Specifies whether IAM user passwords must contain at
least one numeric character (0 to 9).
require_symbols (bool)
Specifies whether IAM user passwords must contain at
least one of the following non-alphanumeric characters: ! @ # $ % ^ & * ( ) _ + - = [ ] { } | '
require_uppercase_characters (bool)
Specifies whether IAM user passwords must
contain at least one uppercase character from the ISO basic Latin alphabet (A to Z).
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
'''
config = locals()
ret = {'name': 'Account Policy', 'result': True, 'comment': '', 'changes': {}}
info = __salt__['boto_iam.get_account_policy'](region, key, keyid, profile)
if not info:
ret['comment'] = 'Account policy is not Enabled.'
ret['result'] = False
return ret
for key, value in config.items():
if key in ('region', 'key', 'keyid', 'profile', 'name'):
continue
if value is not None and six.text_type(info[key]) != six.text_type(value).lower():
ret['comment'] = ' '.join([ret['comment'], 'Policy value {0} has been set to {1}.'.format(value, info[key])])
ret['changes'][key] = six.text_type(value).lower()
if not ret['changes']:
ret['comment'] = 'Account policy is not changed.'
return ret
if __opts__['test']:
ret['comment'] = 'Account policy is set to be changed.'
ret['result'] = None
return ret
if __salt__['boto_iam.update_account_password_policy'](allow_users_to_change_password,
hard_expiry,
max_password_age,
minimum_password_length,
password_reuse_prevention,
require_lowercase_characters,
require_numbers,
require_symbols,
require_uppercase_characters,
region, key, keyid, profile):
return ret
ret['comment'] = 'Account policy is not changed.'
ret['changes'] = {}
ret['result'] = False
return ret
def server_cert_absent(name, region=None, key=None, keyid=None, profile=None):
'''
Deletes a server certificate.
.. versionadded:: 2015.8.0
name (string)
The name for the server certificate. Do not include the path in this value.
region (string)
The name of the region to connect to.
key (string)
The key to be used in order to connect
keyid (string)
The keyid to be used in order to connect
profile (string)
The profile that contains a dict of region, key, keyid
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_iam.get_server_certificate'](name, region, key, keyid, profile)
if not exists:
ret['comment'] = 'Certificate {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Server certificate {0} is set to be deleted.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_server_cert'](name, region, key, keyid, profile)
if not deleted:
ret['result'] = False
ret['comment'] = 'Certificate {0} failed to be deleted.'.format(name)
return ret
ret['comment'] = 'Certificate {0} was deleted.'.format(name)
ret['changes'] = deleted
return ret
def policy_present(name, policy_document, path=None, description=None,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM managed policy is present
name (string)
The name of the new policy.
policy_document (dict)
The document of the new policy
path (string)
The path in which the policy will be created. Default is '/'.
description (string)
Description
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
policy = __salt__['boto_iam.get_policy'](name, region, key, keyid, profile)
if not policy:
if __opts__['test']:
ret['comment'] = 'IAM policy {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_policy'](name, policy_document, path, description, region, key, keyid, profile)
if created:
ret['changes']['policy'] = created
ret['comment'] = ' '.join([ret['comment'], 'Policy {0} has been created.'.format(name)])
else:
ret['result'] = False
ret['comment'] = 'Failed to update policy.'
ret['changes'] = {}
return ret
else:
policy = policy.get('policy', {})
ret['comment'] = ' '.join([ret['comment'], 'Policy {0} is present.'.format(name)])
_describe = __salt__['boto_iam.get_policy_version'](name, policy.get('default_version_id'),
region, key, keyid, profile).get('policy_version', {})
if isinstance(_describe['document'], six.string_types):
describeDict = salt.utils.json.loads(_describe['document'])
else:
describeDict = _describe['document']
if isinstance(policy_document, six.string_types):
policy_document = salt.utils.json.loads(policy_document)
r = salt.utils.data.compare_dicts(describeDict, policy_document)
if bool(r):
if __opts__['test']:
ret['comment'] = 'Policy {0} set to be modified.'.format(name)
ret['result'] = None
return ret
ret['comment'] = ' '.join([ret['comment'], 'Policy to be modified'])
policy_document = salt.utils.json.dumps(policy_document)
r = __salt__['boto_iam.create_policy_version'](policy_name=name,
policy_document=policy_document,
set_as_default=True,
region=region, key=key,
keyid=keyid, profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to update policy: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
__salt__['boto_iam.delete_policy_version'](policy_name=name,
version_id=policy['default_version_id'],
region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'].setdefault('new', {})['document'] = policy_document
ret['changes'].setdefault('old', {})['document'] = _describe['document']
return ret
def policy_absent(name,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM managed policy with the specified name is absent
name (string)
The name of the new policy.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
r = __salt__['boto_iam.policy_exists'](name,
region=region, key=key, keyid=keyid, profile=profile)
if not r:
ret['comment'] = 'Policy {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
# delete non-default versions
versions = __salt__['boto_iam.list_policy_versions'](name,
region=region, key=key,
keyid=keyid, profile=profile)
if versions:
for version in versions:
if version.get('is_default_version', False) in ('true', True):
continue
r = __salt__['boto_iam.delete_policy_version'](name,
version_id=version.get('version_id'),
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
ret['result'] = False
ret['comment'] = 'Failed to delete policy {0}.'.format(name)
return ret
r = __salt__['boto_iam.delete_policy'](name,
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
ret['result'] = False
ret['comment'] = 'Failed to delete policy {0}.'.format(name)
return ret
ret['changes']['old'] = {'policy': name}
ret['changes']['new'] = {'policy': None}
ret['comment'] = 'Policy {0} deleted.'.format(name)
return ret
def saml_provider_present(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is present.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if 'salt://' in saml_metadata_document:
try:
saml_metadata_document = __salt__['cp.get_file_str'](saml_metadata_document)
ET.fromstring(saml_metadata_document)
except IOError as e:
log.debug(e)
ret['comment'] = 'SAML document file {0} not found or could not be loaded'.format(name)
ret['result'] = False
return ret
for provider in __salt__['boto_iam.list_saml_providers'](region=region,
key=key, keyid=keyid,
profile=profile):
if provider == name:
ret['comment'] = 'SAML provider {0} is present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'SAML provider {0} is set to be create.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_saml_provider'](name, saml_metadata_document,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['comment'] = 'SAML provider {0} was created.'.format(name)
ret['changes']['new'] = name
return ret
ret['result'] = False
ret['comment'] = 'SAML provider {0} failed to be created.'.format(name)
return ret
def saml_provider_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is absent.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
provider = __salt__['boto_iam.list_saml_providers'](region=region,
key=key, keyid=keyid,
profile=profile)
if not provider:
ret['comment'] = 'SAML provider {0} is absent.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'SAML provider {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_saml_provider'](name, region=region,
key=key, keyid=keyid,
profile=profile)
if deleted is not False:
ret['comment'] = 'SAML provider {0} was deleted.'.format(name)
ret['changes']['old'] = name
return ret
ret['result'] = False
ret['comment'] = 'SAML provider {0} failed to be deleted.'.format(name)
return ret
def _get_error(error):
# Converts boto exception to string that can be used to output error.
error = '\n'.join(error.split('\n')[1:])
error = ET.fromstring(error)
code = error[0][1].text
message = error[0][2].text
return code, message
|
saltstack/salt
|
salt/states/boto_iam.py
|
saml_provider_present
|
python
|
def saml_provider_present(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is present.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if 'salt://' in saml_metadata_document:
try:
saml_metadata_document = __salt__['cp.get_file_str'](saml_metadata_document)
ET.fromstring(saml_metadata_document)
except IOError as e:
log.debug(e)
ret['comment'] = 'SAML document file {0} not found or could not be loaded'.format(name)
ret['result'] = False
return ret
for provider in __salt__['boto_iam.list_saml_providers'](region=region,
key=key, keyid=keyid,
profile=profile):
if provider == name:
ret['comment'] = 'SAML provider {0} is present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'SAML provider {0} is set to be create.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_saml_provider'](name, saml_metadata_document,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['comment'] = 'SAML provider {0} was created.'.format(name)
ret['changes']['new'] = name
return ret
ret['result'] = False
ret['comment'] = 'SAML provider {0} failed to be created.'.format(name)
return ret
|
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is present.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iam.py#L1611-L1665
| null |
# -*- coding: utf-8 -*-
'''
Manage IAM objects
==================
.. versionadded:: 2015.8.0
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit IAM credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
delete-user:
boto_iam.user_absent:
- name: myuser
- delete_keys: true
.. code-block:: yaml
delete-keys:
boto_iam.keys_absent:
- access_keys:
- 'AKIAJHTMIQ2ASDFLASDF'
- 'PQIAJHTMIQ2ASRTLASFR'
- user_name: myuser
.. code-block:: yaml
create-user:
boto_iam.user_present:
- name: myuser
- policies:
mypolicy: |
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"}]
}
- password: NewPassword$$1
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
create-group:
boto_iam.group_present:
- name: mygroup
- users:
- myuser
- myuser1
- policies:
mypolicy: |
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"}]
}
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
.. code-block:: yaml
change-policy:
boto_iam.account_policy:
- change_password: True
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
.. code-block:: yaml
create server certificate:
boto_iam.server_cert_present:
- name: mycert
- public_key: salt://base/mycert.crt
- private_key: salt://base/mycert.key
- cert_chain: salt://base/mycert_chain.crt
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
delete server certificate:
boto_iam.server_cert_absent:
- name: mycert
.. code-block:: yaml
create keys for user:
boto_iam.keys_present:
- name: myusername
- number: 2
- save_dir: /root
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
create policy:
boto_iam.policy_present:
- name: myname
- policy_document: '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}'
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
add-saml-provider:
boto_iam.saml_provider_present:
- name: my_saml_provider
- saml_metadata_document: salt://base/files/provider.xml
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
# Import Salt Libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.odict as odict
import salt.utils.dictupdate as dictupdate
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
# Import 3rd party libs
try:
from salt._compat import ElementTree as ET
HAS_ELEMENT_TREE = True
except ImportError:
HAS_ELEMENT_TREE = False
log = logging.getLogger(__name__)
__virtualname__ = 'boto_iam'
if six.PY2:
def _byteify(thing):
# Note that we intentionally don't treat odicts here - they won't
# compare equal in many circumstances where AWS treats them the same...
if isinstance(thing, dict):
return dict([(_byteify(k), _byteify(v)) for k, v in six.iteritems(thing)])
elif isinstance(thing, list):
return [_byteify(m) for m in thing]
elif isinstance(thing, six.text_type): # pylint: disable=W1699
return thing.encode('utf-8')
else:
return thing
else: # six.PY3
def _byteify(text):
return text
def __virtual__():
'''
Only load if elementtree xml library and boto are available.
'''
if not HAS_ELEMENT_TREE:
return (False, 'Cannot load {0} state: ElementTree library unavailable'.format(__virtualname__))
if 'boto_iam.get_user' in __salt__:
return True
else:
return (False, 'Cannot load {0} state: boto_iam module unavailable'.format(__virtualname__))
def user_absent(name, delete_keys=True, delete_mfa_devices=True, delete_profile=True, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user is absent. User cannot be deleted if it has keys.
name (string)
The name of the new user.
delete_keys (bool)
Delete all keys from user.
delete_mfa_devices (bool)
Delete all mfa devices from user.
.. versionadded:: 2016.3.0
delete_profile (bool)
Delete profile from user.
.. versionadded:: 2016.3.0
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](name, region, key, keyid, profile):
ret['result'] = True
ret['comment'] = 'IAM User {0} does not exist.'.format(name)
return ret
# delete the user's access keys
if delete_keys:
keys = __salt__['boto_iam.get_all_access_keys'](user_name=name, region=region, key=key,
keyid=keyid, profile=profile)
log.debug('Keys for user %s are %s.', name, keys)
if isinstance(keys, dict):
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
for k in keys:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'Key {0} is set to be deleted.'.format(k['access_key_id'])])
ret['result'] = None
else:
if _delete_key(ret, k['access_key_id'], name, region, key, keyid, profile):
ret['comment'] = ' '.join([ret['comment'], 'Key {0} has been deleted.'.format(k['access_key_id'])])
ret['changes'][k['access_key_id']] = 'deleted'
# delete the user's MFA tokens
if delete_mfa_devices:
devices = __salt__['boto_iam.get_all_mfa_devices'](user_name=name, region=region, key=key, keyid=keyid, profile=profile)
if devices:
for d in devices:
serial = d['serial_number']
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} MFA device {1} is set to be deactivated.'.format(name, serial)])
ret['result'] = None
else:
mfa_deactivated = __salt__['boto_iam.deactivate_mfa_device'](user_name=name, serial=serial, region=region, key=key, keyid=keyid, profile=profile)
if mfa_deactivated:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} MFA device {1} is deactivated.'.format(name, serial)])
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'Virtual MFA device {0} is set to be deleted.'.format(serial)])
ret['result'] = None
else:
mfa_deleted = __salt__['boto_iam.delete_virtual_mfa_device'](serial=serial, region=region, key=key, keyid=keyid, profile=profile)
if mfa_deleted:
ret['comment'] = ' '.join([ret['comment'], 'Virtual MFA device {0} is deleted.'.format(serial)])
# delete the user's login profile
if delete_profile:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} login profile is set to be deleted.'.format(name)])
ret['result'] = None
else:
profile_deleted = __salt__['boto_iam.delete_login_profile'](name, region, key, keyid, profile)
if profile_deleted:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} login profile is deleted.'.format(name)])
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} managed policies are set to be detached.'.format(name)])
ret['result'] = None
else:
_ret = _user_policies_detached(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} inline policies are set to be deleted.'.format(name)])
ret['result'] = None
else:
_ret = _user_policies_deleted(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
# finally, actually delete the user
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} is set to be deleted.'.format(name)])
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_user'](name, region, key, keyid, profile)
if deleted is True:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} is deleted.'.format(name)])
ret['result'] = True
ret['changes']['deleted'] = name
return ret
ret['comment'] = 'IAM user {0} could not be deleted.\n {1}'.format(name, deleted)
ret['result'] = False
return ret
def keys_present(name, number, save_dir, region=None, key=None, keyid=None, profile=None,
save_format="{2}\n{0}\n{3}\n{1}\n"):
'''
.. versionadded:: 2015.8.0
Ensure the IAM access keys are present.
name (string)
The name of the new user.
number (int)
Number of keys that user should have.
save_dir (string)
The directory that the key/keys will be saved. Keys are saved to a file named according
to the username privided.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
save_format (dict)
Save format is repeated for each key. Default format is
"{2}\\n{0}\\n{3}\\n{1}\\n", where {0} and {1} are placeholders for new
key_id and key respectively, whereas {2} and {3} are "key_id-{number}"
and 'key-{number}' strings kept for compatibility.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](name, region, key, keyid, profile):
ret['result'] = False
ret['comment'] = 'IAM User {0} does not exist.'.format(name)
return ret
if not isinstance(number, int):
ret['comment'] = 'The number of keys must be an integer.'
ret['result'] = False
return ret
if not os.path.isdir(save_dir):
ret['comment'] = 'The directory {0} does not exist.'.format(save_dir)
ret['result'] = False
return ret
keys = __salt__['boto_iam.get_all_access_keys'](user_name=name, region=region, key=key,
keyid=keyid, profile=profile)
if isinstance(keys, six.string_types):
log.debug('keys are : false %s', keys)
error, message = _get_error(keys)
ret['comment'] = 'Could not get keys.\n{0}\n{1}'.format(error, message)
ret['result'] = False
return ret
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
log.debug('Keys are : %s.', keys)
if len(keys) >= number:
ret['comment'] = 'The number of keys exist for user {0}'.format(name)
ret['result'] = True
return ret
if __opts__['test']:
ret['comment'] = 'Access key is set to be created for {0}.'.format(name)
ret['result'] = None
return ret
new_keys = {}
for i in range(number-len(keys)):
created = __salt__['boto_iam.create_access_key'](name, region, key, keyid, profile)
if isinstance(created, six.string_types):
error, message = _get_error(created)
ret['comment'] = 'Could not create keys.\n{0}\n{1}'.format(error, message)
ret['result'] = False
return ret
log.debug('Created is : %s', created)
response = 'create_access_key_response'
result = 'create_access_key_result'
new_keys[six.text_type(i)] = {}
new_keys[six.text_type(i)]['key_id'] = created[response][result]['access_key']['access_key_id']
new_keys[six.text_type(i)]['secret_key'] = created[response][result]['access_key']['secret_access_key']
try:
with salt.utils.files.fopen('{0}/{1}'.format(save_dir, name), 'a') as _wrf:
for key_num, key in new_keys.items():
key_id = key['key_id']
secret_key = key['secret_key']
_wrf.write(salt.utils.stringutils.to_str(
save_format.format(
key_id,
secret_key,
'key_id-{0}'.format(key_num),
'key-{0}'.format(key_num)
)
))
ret['comment'] = 'Keys have been written to file {0}/{1}.'.format(save_dir, name)
ret['result'] = True
ret['changes'] = new_keys
return ret
except IOError:
ret['comment'] = 'Could not write to file {0}/{1}.'.format(save_dir, name)
ret['result'] = False
return ret
def keys_absent(access_keys, user_name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user access_key_id is absent.
access_key_id (list)
A list of access key ids
user_name (string)
The username of the user
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': access_keys, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](user_name, region, key, keyid, profile):
ret['result'] = False
ret['comment'] = 'IAM User {0} does not exist.'.format(user_name)
return ret
for k in access_keys:
ret = _delete_key(ret, k, user_name, region, key, keyid, profile)
return ret
def _delete_key(ret, access_key_id, user_name, region=None, key=None, keyid=None, profile=None):
keys = __salt__['boto_iam.get_all_access_keys'](user_name=user_name, region=region, key=key,
keyid=keyid, profile=profile)
log.debug('Keys for user %s are : %s.', keys, user_name)
if isinstance(keys, six.string_types):
log.debug('Keys %s are a string. Something went wrong.', keys)
ret['comment'] = ' '.join([ret['comment'], 'Key {0} could not be deleted.'.format(access_key_id)])
return ret
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
for k in keys:
log.debug('Key is: %s and is compared with: %s', k['access_key_id'], access_key_id)
if six.text_type(k['access_key_id']) == six.text_type(access_key_id):
if __opts__['test']:
ret['comment'] = 'Access key {0} is set to be deleted.'.format(access_key_id)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_access_key'](access_key_id, user_name, region, key,
keyid, profile)
if deleted:
ret['comment'] = ' '.join([ret['comment'], 'Key {0} has been deleted.'.format(access_key_id)])
ret['changes'][access_key_id] = 'deleted'
return ret
ret['comment'] = ' '.join([ret['comment'], 'Key {0} could not be deleted.'.format(access_key_id)])
return ret
ret['comment'] = ' '.join([ret['comment'], 'Key {0} does not exist.'.format(k)])
return ret
def user_present(name, policies=None, policies_from_pillars=None, managed_policies=None, password=None, path=None,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user is present
name (string)
The name of the new user.
policies (dict)
A dict of IAM group policy documents.
policies_from_pillars (list)
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies (list)
A list of managed policy names or ARNs that should be attached to this
user.
password (string)
The password for the new user. Must comply with account policy.
path (string)
The path of the user. Default is '/'.
.. versionadded:: 2015.8.2
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
exists = __salt__['boto_iam.get_user'](name, region, key, keyid, profile)
if not exists:
if __opts__['test']:
ret['comment'] = 'IAM user {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_user'](name, path, region, key, keyid, profile)
if created:
ret['changes']['user'] = created
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been created.'.format(name)])
if password:
ret = _case_password(ret, name, password, region, key, keyid, profile)
_ret = _user_policies_present(name, _policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
else:
ret['comment'] = ' '.join([ret['comment'], 'User {0} is present.'.format(name)])
if password:
ret = _case_password(ret, name, password, region, key, keyid, profile)
_ret = _user_policies_present(name, _policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
_ret = _user_policies_attached(name, managed_policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
return ret
def _user_policies_present(name, policies=None, region=None, key=None, keyid=None, profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_create = {}
policies_to_delete = []
for policy_name, policy in six.iteritems(policies):
if isinstance(policy, six.string_types):
dict_policy = _byteify(salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict))
else:
dict_policy = _byteify(policy)
_policy = _byteify(__salt__['boto_iam.get_user_policy'](name, policy_name, region, key, keyid, profile))
if _policy != dict_policy:
log.debug("Policy mismatch:\n%s\n%s", _policy, dict_policy)
policies_to_create[policy_name] = policy
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
for policy_name in _list:
if policy_name not in policies:
policies_to_delete.append(policy_name)
if policies_to_create or policies_to_delete:
_to_modify = list(policies_to_delete)
_to_modify.extend(policies_to_create)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on user {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'policies': _list}
for policy_name, policy in six.iteritems(policies_to_create):
policy_set = __salt__['boto_iam.put_user_policy'](
name, policy_name, policy, region, key, keyid, profile
)
if not policy_set:
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} for user {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_delete:
policy_unset = __salt__['boto_iam.delete_user_policy'](
name, policy_name, region, key, keyid, profile
)
if not policy_unset:
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to user {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['comment'] = '{0} policies modified on user {1}.'.format(', '.join(_list), name)
return ret
def _user_policies_attached(
name,
managed_policies=None,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_attach = []
policies_to_detach = []
for policy in managed_policies or []:
entities = __salt__['boto_iam.list_entities_for_policy'](policy,
entity_filter='User',
region=region, key=key, keyid=keyid,
profile=profile)
found = False
for userdict in entities.get('policy_users', []):
if name == userdict.get('user_name'):
found = True
break
if not found:
policies_to_attach.append(policy)
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key, keyid=keyid,
profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
for policy_data in _list:
if policy_data.get('policy_name') not in managed_policies \
and policy_data.get('policy_arn') not in managed_policies:
policies_to_detach.append(policy_data.get('policy_arn'))
if policies_to_attach or policies_to_detach:
_to_modify = list(policies_to_detach)
_to_modify.extend(policies_to_attach)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on user {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_name in policies_to_attach:
policy_set = __salt__['boto_iam.attach_user_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_set:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to user {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_detach:
policy_unset = __salt__['boto_iam.detach_user_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to remove policy {0} from user {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
log.debug(newpolicies)
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies modified on user {1}.'.format(', '.join(newpolicies), name)
return ret
def _user_policies_detached(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
_list = __salt__['boto_iam.list_attached_user_policies'](user_name=name,
region=region, key=key, keyid=keyid, profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
if not _list:
ret['comment'] = 'No attached policies in user {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be detached from user {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_arn in oldpolicies:
policy_unset = __salt__['boto_iam.detach_user_policy'](policy_arn,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from user {1}'.format(policy_arn, name)
return ret
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies detached from user {1}.'.format(', '.join(oldpolicies), name)
return ret
def _user_policies_deleted(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
oldpolicies = __salt__['boto_iam.get_all_user_policies'](user_name=name,
region=region, key=key, keyid=keyid, profile=profile)
if not oldpolicies:
ret['comment'] = 'No inline policies in user {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be deleted from user {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'inline_policies': oldpolicies}
for policy_name in oldpolicies:
policy_deleted = __salt__['boto_iam.delete_user_policy'](name,
policy_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_deleted:
newpolicies = __salt__['boto_iam.get_all_user_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from user {1}'.format(policy_name, name)
return ret
newpolicies = __salt__['boto_iam.get_all_user_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['comment'] = '{0} policies deleted from user {1}.'.format(', '.join(oldpolicies), name)
return ret
def _case_password(ret, name, password, region=None, key=None, keyid=None, profile=None):
if __opts__['test']:
ret['comment'] = 'Login policy for {0} is set to be changed.'.format(name)
ret['result'] = None
return ret
login = __salt__['boto_iam.create_login_profile'](name, password, region, key, keyid, profile)
log.debug('Login is : %s.', login)
if login:
if 'Conflict' in login:
ret['comment'] = ' '.join([ret['comment'], 'Login profile for user {0} exists.'.format(name)])
else:
ret['comment'] = ' '.join([ret['comment'], 'Password has been added to User {0}.'.format(name)])
ret['changes']['password'] = 'REDACTED'
else:
ret['result'] = False
ret['comment'] = ' '.join([ret['comment'], 'Password for user {0} could not be set.\nPlease check your password policy.'.format(name)])
return ret
def group_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM group is absent.
name (string)
The name of the group.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_group'](name, region, key, keyid, profile):
ret['result'] = True
ret['comment'] = 'IAM Group {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} managed policies are set to be detached.'.format(name)])
ret['result'] = None
else:
_ret = _group_policies_detached(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} inline policies are set to be deleted.'.format(name)])
ret['result'] = None
else:
_ret = _group_policies_deleted(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} users are set to be removed.'.format(name)])
existing_users = __salt__['boto_iam.get_group_members'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
_ret = _case_group(ret, [], name, existing_users, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
# finally, actually delete the group
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} is set to be deleted.'.format(name)])
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_group'](name, region, key, keyid, profile)
if deleted is True:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} is deleted.'.format(name)])
ret['result'] = True
ret['changes']['deleted'] = name
return ret
ret['comment'] = 'IAM group {0} could not be deleted.\n {1}'.format(name, deleted)
ret['result'] = False
return ret
def group_present(name, policies=None, policies_from_pillars=None, managed_policies=None, users=None, path='/', region=None, key=None, keyid=None, profile=None, delete_policies=True):
'''
.. versionadded:: 2015.8.0
Ensure the IAM group is present
name (string)
The name of the new group.
path (string)
The path for the group, defaults to '/'
policies (dict)
A dict of IAM group policy documents.
policies_from_pillars (list)
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies (list)
A list of policy names or ARNs that should be attached to this group.
users (list)
A list of users to be added to the group.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
delete_policies (boolean)
Delete or detach existing policies that are not in the given list of policies.
Default value is ``True``. If ``False`` is specified, existing policies
will not be deleted or detached allowing manual modifications on the IAM group
to be persistent.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
exists = __salt__['boto_iam.get_group'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
if not exists:
if __opts__['test']:
ret['comment'] = 'IAM group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_group'](group_name=name, path=path, region=region, key=key, keyid=keyid, profile=profile)
if not created:
ret['comment'] = 'Failed to create IAM group {0}.'.format(name)
ret['result'] = False
return ret
ret['changes']['group'] = created
ret['comment'] = ' '.join([ret['comment'], 'Group {0} has been created.'.format(name)])
else:
ret['comment'] = ' '.join([ret['comment'], 'Group {0} is present.'.format(name)])
# Group exists, ensure group policies and users are set.
_ret = _group_policies_present(
name, _policies, region, key, keyid, profile, delete_policies
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
_ret = _group_policies_attached(name, managed_policies, region, key, keyid, profile, delete_policies)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
if users is not None:
log.debug('Users are : %s.', users)
existing_users = __salt__['boto_iam.get_group_members'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
ret = _case_group(ret, users, name, existing_users, region, key, keyid, profile)
return ret
def _case_group(ret, users, group_name, existing_users, region, key, keyid, profile):
_users = []
for user in existing_users:
_users.append(user['user_name'])
log.debug('upstream users are %s', _users)
for user in users:
log.debug('users are %s', user)
if user in _users:
log.debug('user exists')
ret['comment'] = ' '.join([ret['comment'], 'User {0} is already a member of group {1}.'.format(user, group_name)])
continue
else:
log.debug('user is set to be added %s', user)
if __opts__['test']:
ret['comment'] = 'User {0} is set to be added to group {1}.'.format(user, group_name)
ret['result'] = None
else:
__salt__['boto_iam.add_user_to_group'](user, group_name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been added to group {1}.'.format(user, group_name)])
ret['changes'][user] = group_name
for user in _users:
if user not in users:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'User {0} is set to be removed from group {1}.'.format(user, group_name)])
ret['result'] = None
else:
__salt__['boto_iam.remove_user_from_group'](group_name=group_name, user_name=user, region=region,
key=key, keyid=keyid, profile=profile)
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been removed from group {1}.'.format(user, group_name)])
ret['changes'][user] = 'Removed from group {0}.'.format(group_name)
return ret
def _group_policies_present(
name,
policies=None,
region=None,
key=None,
keyid=None,
profile=None,
delete_policies=True):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_create = {}
policies_to_delete = []
for policy_name, policy in six.iteritems(policies):
if isinstance(policy, six.string_types):
dict_policy = _byteify(salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict))
else:
dict_policy = _byteify(policy)
_policy = _byteify(__salt__['boto_iam.get_group_policy'](name, policy_name, region, key, keyid, profile))
if _policy != dict_policy:
log.debug("Policy mismatch:\n%s\n%s", _policy, dict_policy)
policies_to_create[policy_name] = policy
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
for policy_name in _list:
if delete_policies and policy_name not in policies:
policies_to_delete.append(policy_name)
if policies_to_create or policies_to_delete:
_to_modify = list(policies_to_delete)
_to_modify.extend(policies_to_create)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on group {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'policies': _list}
for policy_name, policy in six.iteritems(policies_to_create):
policy_set = __salt__['boto_iam.put_group_policy'](
name, policy_name, policy, region, key, keyid, profile
)
if not policy_set:
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_delete:
policy_unset = __salt__['boto_iam.delete_group_policy'](
name, policy_name, region, key, keyid, profile
)
if not policy_unset:
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['comment'] = '{0} policies modified on group {1}.'.format(', '.join(_list), name)
return ret
def _group_policies_attached(
name,
managed_policies=None,
region=None,
key=None,
keyid=None,
profile=None,
detach_policies=True):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_attach = []
policies_to_detach = []
for policy in managed_policies or []:
entities = __salt__['boto_iam.list_entities_for_policy'](policy,
entity_filter='Group',
region=region, key=key, keyid=keyid,
profile=profile)
found = False
for groupdict in entities.get('policy_groups', []):
if name == groupdict.get('group_name'):
found = True
break
if not found:
policies_to_attach.append(policy)
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key, keyid=keyid,
profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
for policy_data in _list:
if detach_policies \
and policy_data.get('policy_name') not in managed_policies \
and policy_data.get('policy_arn') not in managed_policies:
policies_to_detach.append(policy_data.get('policy_arn'))
if policies_to_attach or policies_to_detach:
_to_modify = list(policies_to_detach)
_to_modify.extend(policies_to_attach)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on group {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_name in policies_to_attach:
policy_set = __salt__['boto_iam.attach_group_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_set:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_detach:
policy_unset = __salt__['boto_iam.detach_group_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to remove policy {0} from group {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
log.debug(newpolicies)
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies modified on group {1}.'.format(', '.join(newpolicies), name)
return ret
def _group_policies_detached(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
_list = __salt__['boto_iam.list_attached_group_policies'](group_name=name,
region=region, key=key, keyid=keyid, profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
if not _list:
ret['comment'] = 'No attached policies in group {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be detached from group {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_arn in oldpolicies:
policy_unset = __salt__['boto_iam.detach_group_policy'](policy_arn,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from group {1}'.format(policy_arn, name)
return ret
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies detached from group {1}.'.format(', '.join(newpolicies), name)
return ret
def _group_policies_deleted(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
oldpolicies = __salt__['boto_iam.get_all_group_policies'](group_name=name,
region=region, key=key, keyid=keyid, profile=profile)
if not oldpolicies:
ret['comment'] = 'No inline policies in group {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be deleted from group {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'inline_policies': oldpolicies}
for policy_name in oldpolicies:
policy_deleted = __salt__['boto_iam.delete_group_policy'](name,
policy_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_deleted:
newpolicies = __salt__['boto_iam.get_all_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from group {1}'.format(policy_name, name)
return ret
newpolicies = __salt__['boto_iam.get_all_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['comment'] = '{0} policies deleted from group {1}.'.format(', '.join(oldpolicies), name)
return ret
def account_policy(name=None, allow_users_to_change_password=None,
hard_expiry=None, max_password_age=None,
minimum_password_length=None, password_reuse_prevention=None,
require_lowercase_characters=None, require_numbers=None,
require_symbols=None, require_uppercase_characters=None,
region=None, key=None, keyid=None, profile=None):
'''
Change account policy.
.. versionadded:: 2015.8.0
name (string)
The name of the account policy
allow_users_to_change_password (bool)
Allows all IAM users in your account to
use the AWS Management Console to change their own passwords.
hard_expiry (bool)
Prevents IAM users from setting a new password after their
password has expired.
max_password_age (int)
The number of days that an IAM user password is valid.
minimum_password_length (int)
The minimum number of characters allowed in an IAM user password.
password_reuse_prevention (int)
Specifies the number of previous passwords
that IAM users are prevented from reusing.
require_lowercase_characters (bool)
Specifies whether IAM user passwords
must contain at least one lowercase character from the ISO basic Latin alphabet (a to z).
require_numbers (bool)
Specifies whether IAM user passwords must contain at
least one numeric character (0 to 9).
require_symbols (bool)
Specifies whether IAM user passwords must contain at
least one of the following non-alphanumeric characters: ! @ # $ % ^ & * ( ) _ + - = [ ] { } | '
require_uppercase_characters (bool)
Specifies whether IAM user passwords must
contain at least one uppercase character from the ISO basic Latin alphabet (A to Z).
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
'''
config = locals()
ret = {'name': 'Account Policy', 'result': True, 'comment': '', 'changes': {}}
info = __salt__['boto_iam.get_account_policy'](region, key, keyid, profile)
if not info:
ret['comment'] = 'Account policy is not Enabled.'
ret['result'] = False
return ret
for key, value in config.items():
if key in ('region', 'key', 'keyid', 'profile', 'name'):
continue
if value is not None and six.text_type(info[key]) != six.text_type(value).lower():
ret['comment'] = ' '.join([ret['comment'], 'Policy value {0} has been set to {1}.'.format(value, info[key])])
ret['changes'][key] = six.text_type(value).lower()
if not ret['changes']:
ret['comment'] = 'Account policy is not changed.'
return ret
if __opts__['test']:
ret['comment'] = 'Account policy is set to be changed.'
ret['result'] = None
return ret
if __salt__['boto_iam.update_account_password_policy'](allow_users_to_change_password,
hard_expiry,
max_password_age,
minimum_password_length,
password_reuse_prevention,
require_lowercase_characters,
require_numbers,
require_symbols,
require_uppercase_characters,
region, key, keyid, profile):
return ret
ret['comment'] = 'Account policy is not changed.'
ret['changes'] = {}
ret['result'] = False
return ret
def server_cert_absent(name, region=None, key=None, keyid=None, profile=None):
'''
Deletes a server certificate.
.. versionadded:: 2015.8.0
name (string)
The name for the server certificate. Do not include the path in this value.
region (string)
The name of the region to connect to.
key (string)
The key to be used in order to connect
keyid (string)
The keyid to be used in order to connect
profile (string)
The profile that contains a dict of region, key, keyid
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_iam.get_server_certificate'](name, region, key, keyid, profile)
if not exists:
ret['comment'] = 'Certificate {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Server certificate {0} is set to be deleted.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_server_cert'](name, region, key, keyid, profile)
if not deleted:
ret['result'] = False
ret['comment'] = 'Certificate {0} failed to be deleted.'.format(name)
return ret
ret['comment'] = 'Certificate {0} was deleted.'.format(name)
ret['changes'] = deleted
return ret
def server_cert_present(name, public_key, private_key, cert_chain=None, path=None,
region=None, key=None, keyid=None, profile=None):
'''
Crete server certificate.
.. versionadded:: 2015.8.0
name (string)
The name for the server certificate. Do not include the path in this value.
public_key (string)
The contents of the public key certificate in PEM-encoded format.
private_key (string)
The contents of the private key in PEM-encoded format.
cert_chain (string)
The contents of the certificate chain. This is typically a
concatenation of the PEM-encoded public key certificates of the chain.
path (string)
The path for the server certificate.
region (string)
The name of the region to connect to.
key (string)
The key to be used in order to connect
keyid (string)
The keyid to be used in order to connect
profile (string)
The profile that contains a dict of region, key, keyid
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_iam.get_server_certificate'](name, region, key, keyid, profile)
log.debug('Variables are : %s.', locals())
if exists:
ret['comment'] = 'Certificate {0} exists.'.format(name)
return ret
if 'salt://' in public_key:
try:
public_key = __salt__['cp.get_file_str'](public_key)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(public_key)
ret['result'] = False
return ret
if 'salt://' in private_key:
try:
private_key = __salt__['cp.get_file_str'](private_key)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(private_key)
ret['result'] = False
return ret
if cert_chain is not None and 'salt://' in cert_chain:
try:
cert_chain = __salt__['cp.get_file_str'](cert_chain)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(cert_chain)
ret['result'] = False
return ret
if __opts__['test']:
ret['comment'] = 'Server certificate {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.upload_server_cert'](name, public_key, private_key, cert_chain,
path, region, key, keyid, profile)
if created is not False:
ret['comment'] = 'Certificate {0} was created.'.format(name)
ret['changes'] = created
return ret
ret['result'] = False
ret['comment'] = 'Certificate {0} failed to be created.'.format(name)
return ret
def policy_present(name, policy_document, path=None, description=None,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM managed policy is present
name (string)
The name of the new policy.
policy_document (dict)
The document of the new policy
path (string)
The path in which the policy will be created. Default is '/'.
description (string)
Description
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
policy = __salt__['boto_iam.get_policy'](name, region, key, keyid, profile)
if not policy:
if __opts__['test']:
ret['comment'] = 'IAM policy {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_policy'](name, policy_document, path, description, region, key, keyid, profile)
if created:
ret['changes']['policy'] = created
ret['comment'] = ' '.join([ret['comment'], 'Policy {0} has been created.'.format(name)])
else:
ret['result'] = False
ret['comment'] = 'Failed to update policy.'
ret['changes'] = {}
return ret
else:
policy = policy.get('policy', {})
ret['comment'] = ' '.join([ret['comment'], 'Policy {0} is present.'.format(name)])
_describe = __salt__['boto_iam.get_policy_version'](name, policy.get('default_version_id'),
region, key, keyid, profile).get('policy_version', {})
if isinstance(_describe['document'], six.string_types):
describeDict = salt.utils.json.loads(_describe['document'])
else:
describeDict = _describe['document']
if isinstance(policy_document, six.string_types):
policy_document = salt.utils.json.loads(policy_document)
r = salt.utils.data.compare_dicts(describeDict, policy_document)
if bool(r):
if __opts__['test']:
ret['comment'] = 'Policy {0} set to be modified.'.format(name)
ret['result'] = None
return ret
ret['comment'] = ' '.join([ret['comment'], 'Policy to be modified'])
policy_document = salt.utils.json.dumps(policy_document)
r = __salt__['boto_iam.create_policy_version'](policy_name=name,
policy_document=policy_document,
set_as_default=True,
region=region, key=key,
keyid=keyid, profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to update policy: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
__salt__['boto_iam.delete_policy_version'](policy_name=name,
version_id=policy['default_version_id'],
region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'].setdefault('new', {})['document'] = policy_document
ret['changes'].setdefault('old', {})['document'] = _describe['document']
return ret
def policy_absent(name,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM managed policy with the specified name is absent
name (string)
The name of the new policy.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
r = __salt__['boto_iam.policy_exists'](name,
region=region, key=key, keyid=keyid, profile=profile)
if not r:
ret['comment'] = 'Policy {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
# delete non-default versions
versions = __salt__['boto_iam.list_policy_versions'](name,
region=region, key=key,
keyid=keyid, profile=profile)
if versions:
for version in versions:
if version.get('is_default_version', False) in ('true', True):
continue
r = __salt__['boto_iam.delete_policy_version'](name,
version_id=version.get('version_id'),
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
ret['result'] = False
ret['comment'] = 'Failed to delete policy {0}.'.format(name)
return ret
r = __salt__['boto_iam.delete_policy'](name,
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
ret['result'] = False
ret['comment'] = 'Failed to delete policy {0}.'.format(name)
return ret
ret['changes']['old'] = {'policy': name}
ret['changes']['new'] = {'policy': None}
ret['comment'] = 'Policy {0} deleted.'.format(name)
return ret
def saml_provider_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is absent.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
provider = __salt__['boto_iam.list_saml_providers'](region=region,
key=key, keyid=keyid,
profile=profile)
if not provider:
ret['comment'] = 'SAML provider {0} is absent.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'SAML provider {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_saml_provider'](name, region=region,
key=key, keyid=keyid,
profile=profile)
if deleted is not False:
ret['comment'] = 'SAML provider {0} was deleted.'.format(name)
ret['changes']['old'] = name
return ret
ret['result'] = False
ret['comment'] = 'SAML provider {0} failed to be deleted.'.format(name)
return ret
def _get_error(error):
# Converts boto exception to string that can be used to output error.
error = '\n'.join(error.split('\n')[1:])
error = ET.fromstring(error)
code = error[0][1].text
message = error[0][2].text
return code, message
|
saltstack/salt
|
salt/states/boto_iam.py
|
saml_provider_absent
|
python
|
def saml_provider_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is absent.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
provider = __salt__['boto_iam.list_saml_providers'](region=region,
key=key, keyid=keyid,
profile=profile)
if not provider:
ret['comment'] = 'SAML provider {0} is absent.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'SAML provider {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_saml_provider'](name, region=region,
key=key, keyid=keyid,
profile=profile)
if deleted is not False:
ret['comment'] = 'SAML provider {0} was deleted.'.format(name)
ret['changes']['old'] = name
return ret
ret['result'] = False
ret['comment'] = 'SAML provider {0} failed to be deleted.'.format(name)
return ret
|
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is absent.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iam.py#L1668-L1713
| null |
# -*- coding: utf-8 -*-
'''
Manage IAM objects
==================
.. versionadded:: 2015.8.0
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit IAM credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
delete-user:
boto_iam.user_absent:
- name: myuser
- delete_keys: true
.. code-block:: yaml
delete-keys:
boto_iam.keys_absent:
- access_keys:
- 'AKIAJHTMIQ2ASDFLASDF'
- 'PQIAJHTMIQ2ASRTLASFR'
- user_name: myuser
.. code-block:: yaml
create-user:
boto_iam.user_present:
- name: myuser
- policies:
mypolicy: |
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"}]
}
- password: NewPassword$$1
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
create-group:
boto_iam.group_present:
- name: mygroup
- users:
- myuser
- myuser1
- policies:
mypolicy: |
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"}]
}
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
.. code-block:: yaml
change-policy:
boto_iam.account_policy:
- change_password: True
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
.. code-block:: yaml
create server certificate:
boto_iam.server_cert_present:
- name: mycert
- public_key: salt://base/mycert.crt
- private_key: salt://base/mycert.key
- cert_chain: salt://base/mycert_chain.crt
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
delete server certificate:
boto_iam.server_cert_absent:
- name: mycert
.. code-block:: yaml
create keys for user:
boto_iam.keys_present:
- name: myusername
- number: 2
- save_dir: /root
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
create policy:
boto_iam.policy_present:
- name: myname
- policy_document: '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}'
- region: eu-west-1
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'fdkjsafkljsASSADFalkfjasdf'
.. code-block:: yaml
add-saml-provider:
boto_iam.saml_provider_present:
- name: my_saml_provider
- saml_metadata_document: salt://base/files/provider.xml
- keyid: 'AKIAJHTMIQ2ASDFLASDF'
- key: 'safsdfsal;fdkjsafkljsASSADFalkfj'
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
# Import Salt Libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.odict as odict
import salt.utils.dictupdate as dictupdate
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
# Import 3rd party libs
try:
from salt._compat import ElementTree as ET
HAS_ELEMENT_TREE = True
except ImportError:
HAS_ELEMENT_TREE = False
log = logging.getLogger(__name__)
__virtualname__ = 'boto_iam'
if six.PY2:
def _byteify(thing):
# Note that we intentionally don't treat odicts here - they won't
# compare equal in many circumstances where AWS treats them the same...
if isinstance(thing, dict):
return dict([(_byteify(k), _byteify(v)) for k, v in six.iteritems(thing)])
elif isinstance(thing, list):
return [_byteify(m) for m in thing]
elif isinstance(thing, six.text_type): # pylint: disable=W1699
return thing.encode('utf-8')
else:
return thing
else: # six.PY3
def _byteify(text):
return text
def __virtual__():
'''
Only load if elementtree xml library and boto are available.
'''
if not HAS_ELEMENT_TREE:
return (False, 'Cannot load {0} state: ElementTree library unavailable'.format(__virtualname__))
if 'boto_iam.get_user' in __salt__:
return True
else:
return (False, 'Cannot load {0} state: boto_iam module unavailable'.format(__virtualname__))
def user_absent(name, delete_keys=True, delete_mfa_devices=True, delete_profile=True, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user is absent. User cannot be deleted if it has keys.
name (string)
The name of the new user.
delete_keys (bool)
Delete all keys from user.
delete_mfa_devices (bool)
Delete all mfa devices from user.
.. versionadded:: 2016.3.0
delete_profile (bool)
Delete profile from user.
.. versionadded:: 2016.3.0
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](name, region, key, keyid, profile):
ret['result'] = True
ret['comment'] = 'IAM User {0} does not exist.'.format(name)
return ret
# delete the user's access keys
if delete_keys:
keys = __salt__['boto_iam.get_all_access_keys'](user_name=name, region=region, key=key,
keyid=keyid, profile=profile)
log.debug('Keys for user %s are %s.', name, keys)
if isinstance(keys, dict):
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
for k in keys:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'Key {0} is set to be deleted.'.format(k['access_key_id'])])
ret['result'] = None
else:
if _delete_key(ret, k['access_key_id'], name, region, key, keyid, profile):
ret['comment'] = ' '.join([ret['comment'], 'Key {0} has been deleted.'.format(k['access_key_id'])])
ret['changes'][k['access_key_id']] = 'deleted'
# delete the user's MFA tokens
if delete_mfa_devices:
devices = __salt__['boto_iam.get_all_mfa_devices'](user_name=name, region=region, key=key, keyid=keyid, profile=profile)
if devices:
for d in devices:
serial = d['serial_number']
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} MFA device {1} is set to be deactivated.'.format(name, serial)])
ret['result'] = None
else:
mfa_deactivated = __salt__['boto_iam.deactivate_mfa_device'](user_name=name, serial=serial, region=region, key=key, keyid=keyid, profile=profile)
if mfa_deactivated:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} MFA device {1} is deactivated.'.format(name, serial)])
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'Virtual MFA device {0} is set to be deleted.'.format(serial)])
ret['result'] = None
else:
mfa_deleted = __salt__['boto_iam.delete_virtual_mfa_device'](serial=serial, region=region, key=key, keyid=keyid, profile=profile)
if mfa_deleted:
ret['comment'] = ' '.join([ret['comment'], 'Virtual MFA device {0} is deleted.'.format(serial)])
# delete the user's login profile
if delete_profile:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} login profile is set to be deleted.'.format(name)])
ret['result'] = None
else:
profile_deleted = __salt__['boto_iam.delete_login_profile'](name, region, key, keyid, profile)
if profile_deleted:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} login profile is deleted.'.format(name)])
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} managed policies are set to be detached.'.format(name)])
ret['result'] = None
else:
_ret = _user_policies_detached(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} inline policies are set to be deleted.'.format(name)])
ret['result'] = None
else:
_ret = _user_policies_deleted(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
# finally, actually delete the user
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} is set to be deleted.'.format(name)])
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_user'](name, region, key, keyid, profile)
if deleted is True:
ret['comment'] = ' '.join([ret['comment'], 'IAM user {0} is deleted.'.format(name)])
ret['result'] = True
ret['changes']['deleted'] = name
return ret
ret['comment'] = 'IAM user {0} could not be deleted.\n {1}'.format(name, deleted)
ret['result'] = False
return ret
def keys_present(name, number, save_dir, region=None, key=None, keyid=None, profile=None,
save_format="{2}\n{0}\n{3}\n{1}\n"):
'''
.. versionadded:: 2015.8.0
Ensure the IAM access keys are present.
name (string)
The name of the new user.
number (int)
Number of keys that user should have.
save_dir (string)
The directory that the key/keys will be saved. Keys are saved to a file named according
to the username privided.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
save_format (dict)
Save format is repeated for each key. Default format is
"{2}\\n{0}\\n{3}\\n{1}\\n", where {0} and {1} are placeholders for new
key_id and key respectively, whereas {2} and {3} are "key_id-{number}"
and 'key-{number}' strings kept for compatibility.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](name, region, key, keyid, profile):
ret['result'] = False
ret['comment'] = 'IAM User {0} does not exist.'.format(name)
return ret
if not isinstance(number, int):
ret['comment'] = 'The number of keys must be an integer.'
ret['result'] = False
return ret
if not os.path.isdir(save_dir):
ret['comment'] = 'The directory {0} does not exist.'.format(save_dir)
ret['result'] = False
return ret
keys = __salt__['boto_iam.get_all_access_keys'](user_name=name, region=region, key=key,
keyid=keyid, profile=profile)
if isinstance(keys, six.string_types):
log.debug('keys are : false %s', keys)
error, message = _get_error(keys)
ret['comment'] = 'Could not get keys.\n{0}\n{1}'.format(error, message)
ret['result'] = False
return ret
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
log.debug('Keys are : %s.', keys)
if len(keys) >= number:
ret['comment'] = 'The number of keys exist for user {0}'.format(name)
ret['result'] = True
return ret
if __opts__['test']:
ret['comment'] = 'Access key is set to be created for {0}.'.format(name)
ret['result'] = None
return ret
new_keys = {}
for i in range(number-len(keys)):
created = __salt__['boto_iam.create_access_key'](name, region, key, keyid, profile)
if isinstance(created, six.string_types):
error, message = _get_error(created)
ret['comment'] = 'Could not create keys.\n{0}\n{1}'.format(error, message)
ret['result'] = False
return ret
log.debug('Created is : %s', created)
response = 'create_access_key_response'
result = 'create_access_key_result'
new_keys[six.text_type(i)] = {}
new_keys[six.text_type(i)]['key_id'] = created[response][result]['access_key']['access_key_id']
new_keys[six.text_type(i)]['secret_key'] = created[response][result]['access_key']['secret_access_key']
try:
with salt.utils.files.fopen('{0}/{1}'.format(save_dir, name), 'a') as _wrf:
for key_num, key in new_keys.items():
key_id = key['key_id']
secret_key = key['secret_key']
_wrf.write(salt.utils.stringutils.to_str(
save_format.format(
key_id,
secret_key,
'key_id-{0}'.format(key_num),
'key-{0}'.format(key_num)
)
))
ret['comment'] = 'Keys have been written to file {0}/{1}.'.format(save_dir, name)
ret['result'] = True
ret['changes'] = new_keys
return ret
except IOError:
ret['comment'] = 'Could not write to file {0}/{1}.'.format(save_dir, name)
ret['result'] = False
return ret
def keys_absent(access_keys, user_name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user access_key_id is absent.
access_key_id (list)
A list of access key ids
user_name (string)
The username of the user
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': access_keys, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_user'](user_name, region, key, keyid, profile):
ret['result'] = False
ret['comment'] = 'IAM User {0} does not exist.'.format(user_name)
return ret
for k in access_keys:
ret = _delete_key(ret, k, user_name, region, key, keyid, profile)
return ret
def _delete_key(ret, access_key_id, user_name, region=None, key=None, keyid=None, profile=None):
keys = __salt__['boto_iam.get_all_access_keys'](user_name=user_name, region=region, key=key,
keyid=keyid, profile=profile)
log.debug('Keys for user %s are : %s.', keys, user_name)
if isinstance(keys, six.string_types):
log.debug('Keys %s are a string. Something went wrong.', keys)
ret['comment'] = ' '.join([ret['comment'], 'Key {0} could not be deleted.'.format(access_key_id)])
return ret
keys = keys['list_access_keys_response']['list_access_keys_result']['access_key_metadata']
for k in keys:
log.debug('Key is: %s and is compared with: %s', k['access_key_id'], access_key_id)
if six.text_type(k['access_key_id']) == six.text_type(access_key_id):
if __opts__['test']:
ret['comment'] = 'Access key {0} is set to be deleted.'.format(access_key_id)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_access_key'](access_key_id, user_name, region, key,
keyid, profile)
if deleted:
ret['comment'] = ' '.join([ret['comment'], 'Key {0} has been deleted.'.format(access_key_id)])
ret['changes'][access_key_id] = 'deleted'
return ret
ret['comment'] = ' '.join([ret['comment'], 'Key {0} could not be deleted.'.format(access_key_id)])
return ret
ret['comment'] = ' '.join([ret['comment'], 'Key {0} does not exist.'.format(k)])
return ret
def user_present(name, policies=None, policies_from_pillars=None, managed_policies=None, password=None, path=None,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM user is present
name (string)
The name of the new user.
policies (dict)
A dict of IAM group policy documents.
policies_from_pillars (list)
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies (list)
A list of managed policy names or ARNs that should be attached to this
user.
password (string)
The password for the new user. Must comply with account policy.
path (string)
The path of the user. Default is '/'.
.. versionadded:: 2015.8.2
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
exists = __salt__['boto_iam.get_user'](name, region, key, keyid, profile)
if not exists:
if __opts__['test']:
ret['comment'] = 'IAM user {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_user'](name, path, region, key, keyid, profile)
if created:
ret['changes']['user'] = created
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been created.'.format(name)])
if password:
ret = _case_password(ret, name, password, region, key, keyid, profile)
_ret = _user_policies_present(name, _policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
else:
ret['comment'] = ' '.join([ret['comment'], 'User {0} is present.'.format(name)])
if password:
ret = _case_password(ret, name, password, region, key, keyid, profile)
_ret = _user_policies_present(name, _policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
_ret = _user_policies_attached(name, managed_policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
return ret
def _user_policies_present(name, policies=None, region=None, key=None, keyid=None, profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_create = {}
policies_to_delete = []
for policy_name, policy in six.iteritems(policies):
if isinstance(policy, six.string_types):
dict_policy = _byteify(salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict))
else:
dict_policy = _byteify(policy)
_policy = _byteify(__salt__['boto_iam.get_user_policy'](name, policy_name, region, key, keyid, profile))
if _policy != dict_policy:
log.debug("Policy mismatch:\n%s\n%s", _policy, dict_policy)
policies_to_create[policy_name] = policy
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
for policy_name in _list:
if policy_name not in policies:
policies_to_delete.append(policy_name)
if policies_to_create or policies_to_delete:
_to_modify = list(policies_to_delete)
_to_modify.extend(policies_to_create)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on user {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'policies': _list}
for policy_name, policy in six.iteritems(policies_to_create):
policy_set = __salt__['boto_iam.put_user_policy'](
name, policy_name, policy, region, key, keyid, profile
)
if not policy_set:
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} for user {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_delete:
policy_unset = __salt__['boto_iam.delete_user_policy'](
name, policy_name, region, key, keyid, profile
)
if not policy_unset:
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to user {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.get_all_user_policies'](
user_name=name, region=region, key=key, keyid=keyid, profile=profile
)
ret['changes']['new'] = {'policies': _list}
ret['comment'] = '{0} policies modified on user {1}.'.format(', '.join(_list), name)
return ret
def _user_policies_attached(
name,
managed_policies=None,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_attach = []
policies_to_detach = []
for policy in managed_policies or []:
entities = __salt__['boto_iam.list_entities_for_policy'](policy,
entity_filter='User',
region=region, key=key, keyid=keyid,
profile=profile)
found = False
for userdict in entities.get('policy_users', []):
if name == userdict.get('user_name'):
found = True
break
if not found:
policies_to_attach.append(policy)
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key, keyid=keyid,
profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
for policy_data in _list:
if policy_data.get('policy_name') not in managed_policies \
and policy_data.get('policy_arn') not in managed_policies:
policies_to_detach.append(policy_data.get('policy_arn'))
if policies_to_attach or policies_to_detach:
_to_modify = list(policies_to_detach)
_to_modify.extend(policies_to_attach)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on user {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_name in policies_to_attach:
policy_set = __salt__['boto_iam.attach_user_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_set:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to user {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_detach:
policy_unset = __salt__['boto_iam.detach_user_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to remove policy {0} from user {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key,
keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
log.debug(newpolicies)
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies modified on user {1}.'.format(', '.join(newpolicies), name)
return ret
def _user_policies_detached(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
_list = __salt__['boto_iam.list_attached_user_policies'](user_name=name,
region=region, key=key, keyid=keyid, profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
if not _list:
ret['comment'] = 'No attached policies in user {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be detached from user {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_arn in oldpolicies:
policy_unset = __salt__['boto_iam.detach_user_policy'](policy_arn,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from user {1}'.format(policy_arn, name)
return ret
_list = __salt__['boto_iam.list_attached_user_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies detached from user {1}.'.format(', '.join(oldpolicies), name)
return ret
def _user_policies_deleted(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
oldpolicies = __salt__['boto_iam.get_all_user_policies'](user_name=name,
region=region, key=key, keyid=keyid, profile=profile)
if not oldpolicies:
ret['comment'] = 'No inline policies in user {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be deleted from user {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'inline_policies': oldpolicies}
for policy_name in oldpolicies:
policy_deleted = __salt__['boto_iam.delete_user_policy'](name,
policy_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_deleted:
newpolicies = __salt__['boto_iam.get_all_user_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from user {1}'.format(policy_name, name)
return ret
newpolicies = __salt__['boto_iam.get_all_user_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['comment'] = '{0} policies deleted from user {1}.'.format(', '.join(oldpolicies), name)
return ret
def _case_password(ret, name, password, region=None, key=None, keyid=None, profile=None):
if __opts__['test']:
ret['comment'] = 'Login policy for {0} is set to be changed.'.format(name)
ret['result'] = None
return ret
login = __salt__['boto_iam.create_login_profile'](name, password, region, key, keyid, profile)
log.debug('Login is : %s.', login)
if login:
if 'Conflict' in login:
ret['comment'] = ' '.join([ret['comment'], 'Login profile for user {0} exists.'.format(name)])
else:
ret['comment'] = ' '.join([ret['comment'], 'Password has been added to User {0}.'.format(name)])
ret['changes']['password'] = 'REDACTED'
else:
ret['result'] = False
ret['comment'] = ' '.join([ret['comment'], 'Password for user {0} could not be set.\nPlease check your password policy.'.format(name)])
return ret
def group_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM group is absent.
name (string)
The name of the group.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_iam.get_group'](name, region, key, keyid, profile):
ret['result'] = True
ret['comment'] = 'IAM Group {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} managed policies are set to be detached.'.format(name)])
ret['result'] = None
else:
_ret = _group_policies_detached(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} inline policies are set to be deleted.'.format(name)])
ret['result'] = None
else:
_ret = _group_policies_deleted(name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} users are set to be removed.'.format(name)])
existing_users = __salt__['boto_iam.get_group_members'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
_ret = _case_group(ret, [], name, existing_users, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
# finally, actually delete the group
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} is set to be deleted.'.format(name)])
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_group'](name, region, key, keyid, profile)
if deleted is True:
ret['comment'] = ' '.join([ret['comment'], 'IAM group {0} is deleted.'.format(name)])
ret['result'] = True
ret['changes']['deleted'] = name
return ret
ret['comment'] = 'IAM group {0} could not be deleted.\n {1}'.format(name, deleted)
ret['result'] = False
return ret
def group_present(name, policies=None, policies_from_pillars=None, managed_policies=None, users=None, path='/', region=None, key=None, keyid=None, profile=None, delete_policies=True):
'''
.. versionadded:: 2015.8.0
Ensure the IAM group is present
name (string)
The name of the new group.
path (string)
The path for the group, defaults to '/'
policies (dict)
A dict of IAM group policy documents.
policies_from_pillars (list)
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies (list)
A list of policy names or ARNs that should be attached to this group.
users (list)
A list of users to be added to the group.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
delete_policies (boolean)
Delete or detach existing policies that are not in the given list of policies.
Default value is ``True``. If ``False`` is specified, existing policies
will not be deleted or detached allowing manual modifications on the IAM group
to be persistent.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
exists = __salt__['boto_iam.get_group'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
if not exists:
if __opts__['test']:
ret['comment'] = 'IAM group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_group'](group_name=name, path=path, region=region, key=key, keyid=keyid, profile=profile)
if not created:
ret['comment'] = 'Failed to create IAM group {0}.'.format(name)
ret['result'] = False
return ret
ret['changes']['group'] = created
ret['comment'] = ' '.join([ret['comment'], 'Group {0} has been created.'.format(name)])
else:
ret['comment'] = ' '.join([ret['comment'], 'Group {0} is present.'.format(name)])
# Group exists, ensure group policies and users are set.
_ret = _group_policies_present(
name, _policies, region, key, keyid, profile, delete_policies
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
_ret = _group_policies_attached(name, managed_policies, region, key, keyid, profile, delete_policies)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
if users is not None:
log.debug('Users are : %s.', users)
existing_users = __salt__['boto_iam.get_group_members'](group_name=name, region=region, key=key, keyid=keyid, profile=profile)
ret = _case_group(ret, users, name, existing_users, region, key, keyid, profile)
return ret
def _case_group(ret, users, group_name, existing_users, region, key, keyid, profile):
_users = []
for user in existing_users:
_users.append(user['user_name'])
log.debug('upstream users are %s', _users)
for user in users:
log.debug('users are %s', user)
if user in _users:
log.debug('user exists')
ret['comment'] = ' '.join([ret['comment'], 'User {0} is already a member of group {1}.'.format(user, group_name)])
continue
else:
log.debug('user is set to be added %s', user)
if __opts__['test']:
ret['comment'] = 'User {0} is set to be added to group {1}.'.format(user, group_name)
ret['result'] = None
else:
__salt__['boto_iam.add_user_to_group'](user, group_name, region, key, keyid, profile)
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been added to group {1}.'.format(user, group_name)])
ret['changes'][user] = group_name
for user in _users:
if user not in users:
if __opts__['test']:
ret['comment'] = ' '.join([ret['comment'], 'User {0} is set to be removed from group {1}.'.format(user, group_name)])
ret['result'] = None
else:
__salt__['boto_iam.remove_user_from_group'](group_name=group_name, user_name=user, region=region,
key=key, keyid=keyid, profile=profile)
ret['comment'] = ' '.join([ret['comment'], 'User {0} has been removed from group {1}.'.format(user, group_name)])
ret['changes'][user] = 'Removed from group {0}.'.format(group_name)
return ret
def _group_policies_present(
name,
policies=None,
region=None,
key=None,
keyid=None,
profile=None,
delete_policies=True):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_create = {}
policies_to_delete = []
for policy_name, policy in six.iteritems(policies):
if isinstance(policy, six.string_types):
dict_policy = _byteify(salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict))
else:
dict_policy = _byteify(policy)
_policy = _byteify(__salt__['boto_iam.get_group_policy'](name, policy_name, region, key, keyid, profile))
if _policy != dict_policy:
log.debug("Policy mismatch:\n%s\n%s", _policy, dict_policy)
policies_to_create[policy_name] = policy
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
for policy_name in _list:
if delete_policies and policy_name not in policies:
policies_to_delete.append(policy_name)
if policies_to_create or policies_to_delete:
_to_modify = list(policies_to_delete)
_to_modify.extend(policies_to_create)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on group {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'policies': _list}
for policy_name, policy in six.iteritems(policies_to_create):
policy_set = __salt__['boto_iam.put_group_policy'](
name, policy_name, policy, region, key, keyid, profile
)
if not policy_set:
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_delete:
policy_unset = __salt__['boto_iam.delete_group_policy'](
name, policy_name, region, key, keyid, profile
)
if not policy_unset:
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.get_all_group_policies'](
name, region, key, keyid, profile
)
ret['changes']['new'] = {'policies': _list}
ret['comment'] = '{0} policies modified on group {1}.'.format(', '.join(_list), name)
return ret
def _group_policies_attached(
name,
managed_policies=None,
region=None,
key=None,
keyid=None,
profile=None,
detach_policies=True):
ret = {'result': True, 'comment': '', 'changes': {}}
policies_to_attach = []
policies_to_detach = []
for policy in managed_policies or []:
entities = __salt__['boto_iam.list_entities_for_policy'](policy,
entity_filter='Group',
region=region, key=key, keyid=keyid,
profile=profile)
found = False
for groupdict in entities.get('policy_groups', []):
if name == groupdict.get('group_name'):
found = True
break
if not found:
policies_to_attach.append(policy)
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key, keyid=keyid,
profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
for policy_data in _list:
if detach_policies \
and policy_data.get('policy_name') not in managed_policies \
and policy_data.get('policy_arn') not in managed_policies:
policies_to_detach.append(policy_data.get('policy_arn'))
if policies_to_attach or policies_to_detach:
_to_modify = list(policies_to_detach)
_to_modify.extend(policies_to_attach)
if __opts__['test']:
ret['comment'] = '{0} policies to be modified on group {1}.'.format(', '.join(_to_modify), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_name in policies_to_attach:
policy_set = __salt__['boto_iam.attach_group_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_set:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to add policy {0} to group {1}'.format(policy_name, name)
return ret
for policy_name in policies_to_detach:
policy_unset = __salt__['boto_iam.detach_group_policy'](policy_name,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to remove policy {0} from group {1}'.format(policy_name, name)
return ret
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
log.debug(newpolicies)
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies modified on group {1}.'.format(', '.join(newpolicies), name)
return ret
def _group_policies_detached(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
_list = __salt__['boto_iam.list_attached_group_policies'](group_name=name,
region=region, key=key, keyid=keyid, profile=profile)
oldpolicies = [x.get('policy_arn') for x in _list]
if not _list:
ret['comment'] = 'No attached policies in group {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be detached from group {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'managed_policies': oldpolicies}
for policy_arn in oldpolicies:
policy_unset = __salt__['boto_iam.detach_group_policy'](policy_arn,
name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_unset:
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from group {1}'.format(policy_arn, name)
return ret
_list = __salt__['boto_iam.list_attached_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
newpolicies = [x.get('policy_arn') for x in _list]
ret['changes']['new'] = {'managed_policies': newpolicies}
ret['comment'] = '{0} policies detached from group {1}.'.format(', '.join(newpolicies), name)
return ret
def _group_policies_deleted(
name,
region=None,
key=None,
keyid=None,
profile=None):
ret = {'result': True, 'comment': '', 'changes': {}}
oldpolicies = __salt__['boto_iam.get_all_group_policies'](group_name=name,
region=region, key=key, keyid=keyid, profile=profile)
if not oldpolicies:
ret['comment'] = 'No inline policies in group {0}.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = '{0} policies to be deleted from group {1}.'.format(', '.join(oldpolicies), name)
ret['result'] = None
return ret
ret['changes']['old'] = {'inline_policies': oldpolicies}
for policy_name in oldpolicies:
policy_deleted = __salt__['boto_iam.delete_group_policy'](name,
policy_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if not policy_deleted:
newpolicies = __salt__['boto_iam.get_all_group_policies'](name, region=region,
key=key, keyid=keyid,
profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['result'] = False
ret['comment'] = 'Failed to detach {0} from group {1}'.format(policy_name, name)
return ret
newpolicies = __salt__['boto_iam.get_all_group_policies'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['new'] = {'inline_policies': newpolicies}
ret['comment'] = '{0} policies deleted from group {1}.'.format(', '.join(oldpolicies), name)
return ret
def account_policy(name=None, allow_users_to_change_password=None,
hard_expiry=None, max_password_age=None,
minimum_password_length=None, password_reuse_prevention=None,
require_lowercase_characters=None, require_numbers=None,
require_symbols=None, require_uppercase_characters=None,
region=None, key=None, keyid=None, profile=None):
'''
Change account policy.
.. versionadded:: 2015.8.0
name (string)
The name of the account policy
allow_users_to_change_password (bool)
Allows all IAM users in your account to
use the AWS Management Console to change their own passwords.
hard_expiry (bool)
Prevents IAM users from setting a new password after their
password has expired.
max_password_age (int)
The number of days that an IAM user password is valid.
minimum_password_length (int)
The minimum number of characters allowed in an IAM user password.
password_reuse_prevention (int)
Specifies the number of previous passwords
that IAM users are prevented from reusing.
require_lowercase_characters (bool)
Specifies whether IAM user passwords
must contain at least one lowercase character from the ISO basic Latin alphabet (a to z).
require_numbers (bool)
Specifies whether IAM user passwords must contain at
least one numeric character (0 to 9).
require_symbols (bool)
Specifies whether IAM user passwords must contain at
least one of the following non-alphanumeric characters: ! @ # $ % ^ & * ( ) _ + - = [ ] { } | '
require_uppercase_characters (bool)
Specifies whether IAM user passwords must
contain at least one uppercase character from the ISO basic Latin alphabet (A to Z).
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
'''
config = locals()
ret = {'name': 'Account Policy', 'result': True, 'comment': '', 'changes': {}}
info = __salt__['boto_iam.get_account_policy'](region, key, keyid, profile)
if not info:
ret['comment'] = 'Account policy is not Enabled.'
ret['result'] = False
return ret
for key, value in config.items():
if key in ('region', 'key', 'keyid', 'profile', 'name'):
continue
if value is not None and six.text_type(info[key]) != six.text_type(value).lower():
ret['comment'] = ' '.join([ret['comment'], 'Policy value {0} has been set to {1}.'.format(value, info[key])])
ret['changes'][key] = six.text_type(value).lower()
if not ret['changes']:
ret['comment'] = 'Account policy is not changed.'
return ret
if __opts__['test']:
ret['comment'] = 'Account policy is set to be changed.'
ret['result'] = None
return ret
if __salt__['boto_iam.update_account_password_policy'](allow_users_to_change_password,
hard_expiry,
max_password_age,
minimum_password_length,
password_reuse_prevention,
require_lowercase_characters,
require_numbers,
require_symbols,
require_uppercase_characters,
region, key, keyid, profile):
return ret
ret['comment'] = 'Account policy is not changed.'
ret['changes'] = {}
ret['result'] = False
return ret
def server_cert_absent(name, region=None, key=None, keyid=None, profile=None):
'''
Deletes a server certificate.
.. versionadded:: 2015.8.0
name (string)
The name for the server certificate. Do not include the path in this value.
region (string)
The name of the region to connect to.
key (string)
The key to be used in order to connect
keyid (string)
The keyid to be used in order to connect
profile (string)
The profile that contains a dict of region, key, keyid
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_iam.get_server_certificate'](name, region, key, keyid, profile)
if not exists:
ret['comment'] = 'Certificate {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Server certificate {0} is set to be deleted.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_iam.delete_server_cert'](name, region, key, keyid, profile)
if not deleted:
ret['result'] = False
ret['comment'] = 'Certificate {0} failed to be deleted.'.format(name)
return ret
ret['comment'] = 'Certificate {0} was deleted.'.format(name)
ret['changes'] = deleted
return ret
def server_cert_present(name, public_key, private_key, cert_chain=None, path=None,
region=None, key=None, keyid=None, profile=None):
'''
Crete server certificate.
.. versionadded:: 2015.8.0
name (string)
The name for the server certificate. Do not include the path in this value.
public_key (string)
The contents of the public key certificate in PEM-encoded format.
private_key (string)
The contents of the private key in PEM-encoded format.
cert_chain (string)
The contents of the certificate chain. This is typically a
concatenation of the PEM-encoded public key certificates of the chain.
path (string)
The path for the server certificate.
region (string)
The name of the region to connect to.
key (string)
The key to be used in order to connect
keyid (string)
The keyid to be used in order to connect
profile (string)
The profile that contains a dict of region, key, keyid
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_iam.get_server_certificate'](name, region, key, keyid, profile)
log.debug('Variables are : %s.', locals())
if exists:
ret['comment'] = 'Certificate {0} exists.'.format(name)
return ret
if 'salt://' in public_key:
try:
public_key = __salt__['cp.get_file_str'](public_key)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(public_key)
ret['result'] = False
return ret
if 'salt://' in private_key:
try:
private_key = __salt__['cp.get_file_str'](private_key)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(private_key)
ret['result'] = False
return ret
if cert_chain is not None and 'salt://' in cert_chain:
try:
cert_chain = __salt__['cp.get_file_str'](cert_chain)
except IOError as e:
log.debug(e)
ret['comment'] = 'File {0} not found.'.format(cert_chain)
ret['result'] = False
return ret
if __opts__['test']:
ret['comment'] = 'Server certificate {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.upload_server_cert'](name, public_key, private_key, cert_chain,
path, region, key, keyid, profile)
if created is not False:
ret['comment'] = 'Certificate {0} was created.'.format(name)
ret['changes'] = created
return ret
ret['result'] = False
ret['comment'] = 'Certificate {0} failed to be created.'.format(name)
return ret
def policy_present(name, policy_document, path=None, description=None,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM managed policy is present
name (string)
The name of the new policy.
policy_document (dict)
The document of the new policy
path (string)
The path in which the policy will be created. Default is '/'.
description (string)
Description
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
policy = __salt__['boto_iam.get_policy'](name, region, key, keyid, profile)
if not policy:
if __opts__['test']:
ret['comment'] = 'IAM policy {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_policy'](name, policy_document, path, description, region, key, keyid, profile)
if created:
ret['changes']['policy'] = created
ret['comment'] = ' '.join([ret['comment'], 'Policy {0} has been created.'.format(name)])
else:
ret['result'] = False
ret['comment'] = 'Failed to update policy.'
ret['changes'] = {}
return ret
else:
policy = policy.get('policy', {})
ret['comment'] = ' '.join([ret['comment'], 'Policy {0} is present.'.format(name)])
_describe = __salt__['boto_iam.get_policy_version'](name, policy.get('default_version_id'),
region, key, keyid, profile).get('policy_version', {})
if isinstance(_describe['document'], six.string_types):
describeDict = salt.utils.json.loads(_describe['document'])
else:
describeDict = _describe['document']
if isinstance(policy_document, six.string_types):
policy_document = salt.utils.json.loads(policy_document)
r = salt.utils.data.compare_dicts(describeDict, policy_document)
if bool(r):
if __opts__['test']:
ret['comment'] = 'Policy {0} set to be modified.'.format(name)
ret['result'] = None
return ret
ret['comment'] = ' '.join([ret['comment'], 'Policy to be modified'])
policy_document = salt.utils.json.dumps(policy_document)
r = __salt__['boto_iam.create_policy_version'](policy_name=name,
policy_document=policy_document,
set_as_default=True,
region=region, key=key,
keyid=keyid, profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to update policy: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
__salt__['boto_iam.delete_policy_version'](policy_name=name,
version_id=policy['default_version_id'],
region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'].setdefault('new', {})['document'] = policy_document
ret['changes'].setdefault('old', {})['document'] = _describe['document']
return ret
def policy_absent(name,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2015.8.0
Ensure the IAM managed policy with the specified name is absent
name (string)
The name of the new policy.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
r = __salt__['boto_iam.policy_exists'](name,
region=region, key=key, keyid=keyid, profile=profile)
if not r:
ret['comment'] = 'Policy {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Policy {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
# delete non-default versions
versions = __salt__['boto_iam.list_policy_versions'](name,
region=region, key=key,
keyid=keyid, profile=profile)
if versions:
for version in versions:
if version.get('is_default_version', False) in ('true', True):
continue
r = __salt__['boto_iam.delete_policy_version'](name,
version_id=version.get('version_id'),
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
ret['result'] = False
ret['comment'] = 'Failed to delete policy {0}.'.format(name)
return ret
r = __salt__['boto_iam.delete_policy'](name,
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
ret['result'] = False
ret['comment'] = 'Failed to delete policy {0}.'.format(name)
return ret
ret['changes']['old'] = {'policy': name}
ret['changes']['new'] = {'policy': None}
ret['comment'] = 'Policy {0} deleted.'.format(name)
return ret
def saml_provider_present(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is present.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret key to be used.
keyid (string)
Access key to be used.
profile (dict)
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if 'salt://' in saml_metadata_document:
try:
saml_metadata_document = __salt__['cp.get_file_str'](saml_metadata_document)
ET.fromstring(saml_metadata_document)
except IOError as e:
log.debug(e)
ret['comment'] = 'SAML document file {0} not found or could not be loaded'.format(name)
ret['result'] = False
return ret
for provider in __salt__['boto_iam.list_saml_providers'](region=region,
key=key, keyid=keyid,
profile=profile):
if provider == name:
ret['comment'] = 'SAML provider {0} is present.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'SAML provider {0} is set to be create.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_iam.create_saml_provider'](name, saml_metadata_document,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['comment'] = 'SAML provider {0} was created.'.format(name)
ret['changes']['new'] = name
return ret
ret['result'] = False
ret['comment'] = 'SAML provider {0} failed to be created.'.format(name)
return ret
def _get_error(error):
# Converts boto exception to string that can be used to output error.
error = '\n'.join(error.split('\n')[1:])
error = ET.fromstring(error)
code = error[0][1].text
message = error[0][2].text
return code, message
|
saltstack/salt
|
salt/modules/napalm_bgp.py
|
config
|
python
|
def config(group=None, neighbor=None, **kwargs):
'''
Provides the BGP configuration on the device.
:param group: Name of the group selected to display the configuration.
:param neighbor: IP Address of the neighbor to display the configuration.
If the group parameter is not specified, the neighbor setting will be
ignored.
:return: A dictionary containing the BGP configuration from the network
device. The keys of the main dictionary are the group names.
Each group has the following properties:
* type (string)
* description (string)
* apply_groups (string list)
* multihop_ttl (int)
* multipath (True/False)
* local_address (string)
* local_as (int)
* remote_as (int)
* import_policy (string)
* export_policy (string)
* remove_private_as (True/False)
* prefix_limit (dictionary)
* neighbors (dictionary)
Each neighbor in the dictionary of neighbors provides:
* description (string)
* import_policy (string)
* export_policy (string)
* local_address (string)
* local_as (int)
* remote_as (int)
* authentication_key (string)
* prefix_limit (dictionary)
* route_reflector_client (True/False)
* nhs (True/False)
CLI Example:
.. code-block:: bash
salt '*' bgp.config # entire BGP config
salt '*' bgp.config PEERS-GROUP-NAME # provides detail only about BGP group PEERS-GROUP-NAME
salt '*' bgp.config PEERS-GROUP-NAME 172.17.17.1 # provides details only about BGP neighbor 172.17.17.1,
# configured in the group PEERS-GROUP-NAME
Output Example:
.. code-block:: python
{
'PEERS-GROUP-NAME':{
'type' : 'external',
'description' : 'Here we should have a nice description',
'apply_groups' : ['BGP-PREFIX-LIMIT'],
'import_policy' : 'PUBLIC-PEER-IN',
'export_policy' : 'PUBLIC-PEER-OUT',
'remove_private': True,
'multipath' : True,
'multihop_ttl' : 30,
'neighbors' : {
'192.168.0.1': {
'description' : 'Facebook [CDN]',
'prefix_limit' : {
'inet': {
'unicast': {
'limit': 100,
'teardown': {
'threshold' : 95,
'timeout' : 5
}
}
}
}
'peer-as' : 32934,
'route_reflector': False,
'nhs' : True
},
'172.17.17.1': {
'description' : 'Twitter [CDN]',
'prefix_limit' : {
'inet': {
'unicast': {
'limit': 500,
'no-validate': 'IMPORT-FLOW-ROUTES'
}
}
}
'peer_as' : 13414
'route_reflector': False,
'nhs' : False
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_bgp_config',
**{
'group': group,
'neighbor': neighbor
}
)
|
Provides the BGP configuration on the device.
:param group: Name of the group selected to display the configuration.
:param neighbor: IP Address of the neighbor to display the configuration.
If the group parameter is not specified, the neighbor setting will be
ignored.
:return: A dictionary containing the BGP configuration from the network
device. The keys of the main dictionary are the group names.
Each group has the following properties:
* type (string)
* description (string)
* apply_groups (string list)
* multihop_ttl (int)
* multipath (True/False)
* local_address (string)
* local_as (int)
* remote_as (int)
* import_policy (string)
* export_policy (string)
* remove_private_as (True/False)
* prefix_limit (dictionary)
* neighbors (dictionary)
Each neighbor in the dictionary of neighbors provides:
* description (string)
* import_policy (string)
* export_policy (string)
* local_address (string)
* local_as (int)
* remote_as (int)
* authentication_key (string)
* prefix_limit (dictionary)
* route_reflector_client (True/False)
* nhs (True/False)
CLI Example:
.. code-block:: bash
salt '*' bgp.config # entire BGP config
salt '*' bgp.config PEERS-GROUP-NAME # provides detail only about BGP group PEERS-GROUP-NAME
salt '*' bgp.config PEERS-GROUP-NAME 172.17.17.1 # provides details only about BGP neighbor 172.17.17.1,
# configured in the group PEERS-GROUP-NAME
Output Example:
.. code-block:: python
{
'PEERS-GROUP-NAME':{
'type' : 'external',
'description' : 'Here we should have a nice description',
'apply_groups' : ['BGP-PREFIX-LIMIT'],
'import_policy' : 'PUBLIC-PEER-IN',
'export_policy' : 'PUBLIC-PEER-OUT',
'remove_private': True,
'multipath' : True,
'multihop_ttl' : 30,
'neighbors' : {
'192.168.0.1': {
'description' : 'Facebook [CDN]',
'prefix_limit' : {
'inet': {
'unicast': {
'limit': 100,
'teardown': {
'threshold' : 95,
'timeout' : 5
}
}
}
}
'peer-as' : 32934,
'route_reflector': False,
'nhs' : True
},
'172.17.17.1': {
'description' : 'Twitter [CDN]',
'prefix_limit' : {
'inet': {
'unicast': {
'limit': 500,
'no-validate': 'IMPORT-FLOW-ROUTES'
}
}
}
'peer_as' : 13414
'route_reflector': False,
'nhs' : False
}
}
}
}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_bgp.py#L61-L170
|
[
"def call(napalm_device, method, *args, **kwargs):\n '''\n Calls arbitrary methods from the network driver instance.\n Please check the readthedocs_ page for the updated list of getters.\n\n .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix\n\n method\n Specifies the name of the method to be called.\n\n *args\n Arguments.\n\n **kwargs\n More arguments.\n\n :return: A dictionary with three keys:\n\n * result (True/False): if the operation succeeded\n * out (object): returns the object as-is from the call\n * comment (string): provides more details in case the call failed\n * traceback (string): complete traceback in case of exception. \\\n Please submit an issue including this traceback \\\n on the `correct driver repo`_ and make sure to read the FAQ_\n\n .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new\n .. FAQ_: https://github.com/napalm-automation/napalm#faq\n\n Example:\n\n .. code-block:: python\n\n salt.utils.napalm.call(\n napalm_object,\n 'cli',\n [\n 'show version',\n 'show chassis fan'\n ]\n )\n '''\n result = False\n out = None\n opts = napalm_device.get('__opts__', {})\n retry = kwargs.pop('__retry', True) # retry executing the task?\n force_reconnect = kwargs.get('force_reconnect', False)\n if force_reconnect:\n log.debug('Forced reconnection initiated')\n log.debug('The current opts (under the proxy key):')\n log.debug(opts['proxy'])\n opts['proxy'].update(**kwargs)\n log.debug('Updated to:')\n log.debug(opts['proxy'])\n napalm_device = get_device(opts)\n try:\n if not napalm_device.get('UP', False):\n raise Exception('not connected')\n # if connected will try to execute desired command\n kwargs_copy = {}\n kwargs_copy.update(kwargs)\n for karg, warg in six.iteritems(kwargs_copy):\n # lets clear None arguments\n # to not be sent to NAPALM methods\n if warg is None:\n kwargs.pop(karg)\n out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs)\n # calls the method with the specified parameters\n result = True\n except Exception as error:\n # either not connected\n # either unable to execute the command\n hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]')\n err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons.\n if isinstance(error, NotImplementedError):\n comment = '{method} is not implemented for the NAPALM {driver} driver!'.format(\n method=method,\n driver=napalm_device.get('DRIVER_NAME')\n )\n elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException):\n # Received disconection whilst executing the operation.\n # Instructed to retry (default behaviour)\n # thus trying to re-establish the connection\n # and re-execute the command\n # if any of the operations (close, open, call) will rise again ConnectionClosedException\n # it will fail loudly.\n kwargs['__retry'] = False # do not attempt re-executing\n comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname)\n log.error(err_tb)\n log.error(comment)\n log.debug('Clearing the connection with %s', hostname)\n call(napalm_device, 'close', __retry=False) # safely close the connection\n # Make sure we don't leave any TCP connection open behind\n # if we fail to close properly, we might not be able to access the\n log.debug('Re-opening the connection with %s', hostname)\n call(napalm_device, 'open', __retry=False)\n log.debug('Connection re-opened with %s', hostname)\n log.debug('Re-executing %s', method)\n return call(napalm_device, method, *args, **kwargs)\n # If still not able to reconnect and execute the task,\n # the proxy keepalive feature (if enabled) will attempt\n # to reconnect.\n # If the device is using a SSH-based connection, the failure\n # will also notify the paramiko transport and the `is_alive` flag\n # is going to be set correctly.\n # More background: the network device may decide to disconnect,\n # although the SSH session itself is alive and usable, the reason\n # being the lack of activity on the CLI.\n # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval\n # are targeting the transport layer, whilst the device takes the decision\n # when there isn't any activity on the CLI, thus at the application layer.\n # Moreover, the disconnect is silent and paramiko's is_alive flag will\n # continue to return True, although the connection is already unusable.\n # For more info, see https://github.com/paramiko/paramiko/issues/813.\n # But after a command fails, the `is_alive` flag becomes aware of these\n # changes and will return False from there on. And this is how the\n # Salt proxy keepalive helps: immediately after the first failure, it\n # will know the state of the connection and will try reconnecting.\n else:\n comment = 'Cannot execute \"{method}\" on {device}{port} as {user}. Reason: {error}!'.format(\n device=napalm_device.get('HOSTNAME', '[unspecified hostname]'),\n port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port'))\n if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''),\n user=napalm_device.get('USERNAME', ''),\n method=method,\n error=error\n )\n log.error(comment)\n log.error(err_tb)\n return {\n 'out': {},\n 'result': False,\n 'comment': comment,\n 'traceback': err_tb\n }\n finally:\n if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True):\n # either running in a not-always-alive proxy\n # either running in a regular minion\n # close the connection when the call is over\n # unless the CLOSE is explicitly set as False\n napalm_device['DRIVER'].close()\n return {\n 'out': out,\n 'result': result,\n 'comment': ''\n }\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM BGP
==========
Manages BGP configuration on network devices and provides statistics.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python lib
import logging
log = logging.getLogger(__file__)
# import NAPALM utils
import salt.utils.napalm
from salt.utils.napalm import proxy_napalm_wrap
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'bgp'
__proxyenabled__ = ['napalm']
# uses NAPALM-based proxy to interact with network devices
__virtual_aliases__ = ('napalm_bgp',)
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@proxy_napalm_wrap
@proxy_napalm_wrap
def neighbors(neighbor=None, **kwargs):
'''
Provides details regarding the BGP sessions configured on the network device.
:param neighbor: IP Address of a specific neighbor.
:return: A dictionary with the statistics of the all/selected BGP
neighbors. Outer dictionary keys represent the VRF name. Keys of inner
dictionary represent the AS numbers, while the values are lists of
dictionaries, having the following keys:
- up (True/False)
- local_as (int)
- remote_as (int)
- local_address (string)
- routing_table (string)
- local_address_configured (True/False)
- local_port (int)
- remote_address (string)
- remote_port (int)
- multihop (True/False)
- multipath (True/False)
- remove_private_as (True/False)
- import_policy (string)
- export_policy (string)
- input_messages (int)
- output_messages (int)
- input_updates (int)
- output_updates (int)
- messages_queued_out (int)
- connection_state (string)
- previous_connection_state (string)
- last_event (string)
- suppress_4byte_as (True/False)
- local_as_prepend (True/False)
- holdtime (int)
- configured_holdtime (int)
- keepalive (int)
- configured_keepalive (int)
- active_prefix_count (int)
- received_prefix_count (int)
- accepted_prefix_count (int)
- suppressed_prefix_count (int)
- advertised_prefix_count (int)
- flap_count (int)
CLI Example:
.. code-block:: bash
salt '*' bgp.neighbors # all neighbors
salt '*' bgp.neighbors 172.17.17.1 # only session with BGP neighbor(s) 172.17.17.1
Output Example:
.. code-block:: python
{
'default': {
8121: [
{
'up' : True,
'local_as' : 13335,
'remote_as' : 8121,
'local_address' : '172.101.76.1',
'local_address_configured' : True,
'local_port' : 179,
'remote_address' : '192.247.78.0',
'router_id' : '192.168.0.1',
'remote_port' : 58380,
'multihop' : False,
'import_policy' : '4-NTT-TRANSIT-IN',
'export_policy' : '4-NTT-TRANSIT-OUT',
'input_messages' : 123,
'output_messages' : 13,
'input_updates' : 123,
'output_updates' : 5,
'messages_queued_out' : 23,
'connection_state' : 'Established',
'previous_connection_state' : 'EstabSync',
'last_event' : 'RecvKeepAlive',
'suppress_4byte_as' : False,
'local_as_prepend' : False,
'holdtime' : 90,
'configured_holdtime' : 90,
'keepalive' : 30,
'configured_keepalive' : 30,
'active_prefix_count' : 132808,
'received_prefix_count' : 566739,
'accepted_prefix_count' : 566479,
'suppressed_prefix_count' : 0,
'advertise_prefix_count' : 0,
'flap_count' : 27
}
]
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_bgp_neighbors_detail',
**{
'neighbor_address': neighbor
}
)
|
saltstack/salt
|
salt/cloud/clouds/lxc.py
|
_salt
|
python
|
def _salt(fun, *args, **kw):
'''Execute a salt function on a specific minion
Special kwargs:
salt_target
target to exec things on
salt_timeout
timeout for jobs
salt_job_poll
poll interval to wait for job finish result
'''
try:
poll = kw.pop('salt_job_poll')
except KeyError:
poll = 0.1
try:
target = kw.pop('salt_target')
except KeyError:
target = None
try:
timeout = int(kw.pop('salt_timeout'))
except (KeyError, ValueError):
# try to has some low timeouts for very basic commands
timeout = __FUN_TIMEOUT.get(
fun,
900 # wait up to 15 minutes for the default timeout
)
try:
kwargs = kw.pop('kwargs')
except KeyError:
kwargs = {}
if not target:
infos = get_configured_provider()
if not infos:
return
target = infos['target']
laps = time.time()
cache = False
if fun in __CACHED_FUNS:
cache = True
laps = laps // __CACHED_FUNS[fun]
try:
sargs = salt.utils.json.dumps(args)
except TypeError:
sargs = ''
try:
skw = salt.utils.json.dumps(kw)
except TypeError:
skw = ''
try:
skwargs = salt.utils.json.dumps(kwargs)
except TypeError:
skwargs = ''
cache_key = (laps, target, fun, sargs, skw, skwargs)
if not cache or (cache and (cache_key not in __CACHED_CALLS)):
conn = _client()
runner = _runner()
rkwargs = kwargs.copy()
rkwargs['timeout'] = timeout
rkwargs.setdefault('tgt_type', 'list')
kwargs.setdefault('tgt_type', 'list')
ping_retries = 0
# the target(s) have environ one minute to respond
# we call 60 ping request, this prevent us
# from blindly send commands to unmatched minions
ping_max_retries = 60
ping = True
# do not check ping... if we are pinguing
if fun == 'test.ping':
ping_retries = ping_max_retries + 1
# be sure that the executors are alive
while ping_retries <= ping_max_retries:
try:
if ping_retries > 0:
time.sleep(1)
pings = conn.cmd(tgt=target,
timeout=10,
fun='test.ping')
values = list(pings.values())
if not values:
ping = False
for v in values:
if v is not True:
ping = False
if not ping:
raise ValueError('Unreachable')
break
except Exception:
ping = False
ping_retries += 1
log.error('%s unreachable, retrying', target)
if not ping:
raise SaltCloudSystemExit('Target {0} unreachable'.format(target))
jid = conn.cmd_async(tgt=target,
fun=fun,
arg=args,
kwarg=kw,
**rkwargs)
cret = conn.cmd(tgt=target,
fun='saltutil.find_job',
arg=[jid],
timeout=10,
**kwargs)
running = bool(cret.get(target, False))
endto = time.time() + timeout
while running:
rkwargs = {
'tgt': target,
'fun': 'saltutil.find_job',
'arg': [jid],
'timeout': 10
}
cret = conn.cmd(**rkwargs)
running = bool(cret.get(target, False))
if not running:
break
if running and (time.time() > endto):
raise Exception('Timeout {0}s for {1} is elapsed'.format(
timeout, pprint.pformat(rkwargs)))
time.sleep(poll)
# timeout for the master to return data about a specific job
wait_for_res = float({
'test.ping': '5',
}.get(fun, '120'))
while wait_for_res:
wait_for_res -= 0.5
cret = runner.cmd(
'jobs.lookup_jid',
[jid, {'__kwarg__': True}])
if target in cret:
ret = cret[target]
break
# recent changes
elif 'data' in cret and 'outputter' in cret:
ret = cret['data']
break
# special case, some answers may be crafted
# to handle the unresponsivness of a specific command
# which is also meaningful, e.g. a minion not yet provisioned
if fun in ['test.ping'] and not wait_for_res:
ret = {
'test.ping': False,
}.get(fun, False)
time.sleep(0.5)
try:
if 'is not available.' in ret:
raise SaltCloudSystemExit(
'module/function {0} is not available'.format(fun))
except SaltCloudSystemExit:
raise
except TypeError:
pass
if cache:
__CACHED_CALLS[cache_key] = ret
elif cache and cache_key in __CACHED_CALLS:
ret = __CACHED_CALLS[cache_key]
return ret
|
Execute a salt function on a specific minion
Special kwargs:
salt_target
target to exec things on
salt_timeout
timeout for jobs
salt_job_poll
poll interval to wait for job finish result
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/lxc.py#L97-L254
|
[
"def _runner():\n # opts = _master_opts()\n # opts['output'] = 'quiet'\n return salt.runner.RunnerClient(_master_opts())\n",
"def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n",
"def get_configured_provider(vm_=None):\n '''\n Return the contextual provider of None if no configured\n one can be found.\n '''\n if vm_ is None:\n vm_ = {}\n dalias, driver = __active_provider_name__.split(':')\n data = None\n tgt = 'unknown'\n img_provider = __opts__.get('list_images', '')\n arg_providers = __opts__.get('names', [])\n matched = False\n # --list-images level\n if img_provider:\n tgt = 'provider: {0}'.format(img_provider)\n if dalias == img_provider:\n data = get_provider(img_provider)\n matched = True\n # providers are set in configuration\n if not data and 'profile' not in __opts__ and arg_providers:\n for name in arg_providers:\n tgt = 'provider: {0}'.format(name)\n if dalias == name:\n data = get_provider(name)\n if data:\n matched = True\n break\n # -p is providen, get the uplinked provider\n elif 'profile' in __opts__:\n curprof = __opts__['profile']\n profs = __opts__['profiles']\n tgt = 'profile: {0}'.format(curprof)\n if (\n curprof in profs and\n profs[curprof]['provider'] == __active_provider_name__\n ):\n prov, cdriver = profs[curprof]['provider'].split(':')\n tgt += ' provider: {0}'.format(prov)\n data = get_provider(prov)\n matched = True\n # fallback if we have only __active_provider_name__\n if (\n (__opts__.get('destroy', False) and not data) or (\n not matched and __active_provider_name__\n )\n ):\n data = __opts__.get('providers',\n {}).get(dalias, {}).get(driver, {})\n # in all cases, verify that the linked saltmaster is alive.\n if data:\n ret = _salt('test.ping', salt_target=data['target'])\n if ret:\n return data\n else:\n log.error(\n 'Configured provider %s minion: %s is unreachable',\n __active_provider_name__, data['target']\n )\n return False\n",
"def _client():\n return salt.client.get_local_client(mopts=_master_opts())\n"
] |
# -*- coding: utf-8 -*-
'''
Install Salt on an LXC Container
================================
.. versionadded:: 2014.7.0
Please read :ref:`core config documentation <config_lxc>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import os
import pprint
import time
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.client
import salt.runner
# Import 3rd-party libs
from salt.ext import six
# Get logging started
log = logging.getLogger(__name__)
__FUN_TIMEOUT = {
'cmd.run': 60 * 60,
'test.ping': 10,
'lxc.info': 40,
'lxc.list': 300,
'lxc.templates': 100,
'grains.items': 100,
}
__CACHED_CALLS = {}
__CACHED_FUNS = {
'test.ping': 3 * 60, # cache ping for 3 minutes
'lxc.list': 2 # cache lxc.list for 2 seconds
}
def __virtual__():
'''
Needs no special configuration
'''
return True
def _get_grain_id(id_):
if not get_configured_provider():
return
infos = get_configured_provider()
return 'salt.cloud.lxc.{0}.{1}'.format(infos['target'], id_)
def _minion_opts(cfg='minion'):
if 'conf_file' in __opts__:
default_dir = os.path.dirname(__opts__['conf_file'])
else:
default_dir = __opts__['config_dir'],
cfg = os.environ.get(
'SALT_MINION_CONFIG', os.path.join(default_dir, cfg))
opts = config.minion_config(cfg)
return opts
def _master_opts(cfg='master'):
if 'conf_file' in __opts__:
default_dir = os.path.dirname(__opts__['conf_file'])
else:
default_dir = __opts__['config_dir'],
cfg = os.environ.get(
'SALT_MASTER_CONFIG', os.path.join(default_dir, cfg))
opts = config.master_config(cfg)
opts['output'] = 'quiet'
return opts
def _client():
return salt.client.get_local_client(mopts=_master_opts())
def _runner():
# opts = _master_opts()
# opts['output'] = 'quiet'
return salt.runner.RunnerClient(_master_opts())
def avail_images():
return _salt('lxc.templates')
def list_nodes(conn=None, call=None):
hide = False
names = __opts__.get('names', [])
profiles = __opts__.get('profiles', {})
profile = __opts__.get('profile',
__opts__.get('internal_lxc_profile', []))
destroy_opt = __opts__.get('destroy', False)
action = __opts__.get('action', '')
for opt in ['full_query', 'select_query', 'query']:
if __opts__.get(opt, False):
call = 'full'
if destroy_opt:
call = 'full'
if action and not call:
call = 'action'
if profile and names and not destroy_opt:
hide = True
if not get_configured_provider():
return
path = None
if profile and profile in profiles:
path = profiles[profile].get('path', None)
lxclist = _salt('lxc.list', extra=True, path=path)
nodes = {}
for state, lxcs in six.iteritems(lxclist):
for lxcc, linfos in six.iteritems(lxcs):
info = {
'id': lxcc,
'name': lxcc, # required for cloud cache
'image': None,
'size': linfos['size'],
'state': state.lower(),
'public_ips': linfos['public_ips'],
'private_ips': linfos['private_ips'],
}
# in creation mode, we need to go inside the create method
# so we hide the running vm from being seen as already installed
# do not also mask half configured nodes which are explicitly asked
# to be acted on, on the command line
if (call in ['full'] or not hide) and ((lxcc in names and call in ['action']) or call in ['full']):
nodes[lxcc] = {
'id': lxcc,
'name': lxcc, # required for cloud cache
'image': None,
'size': linfos['size'],
'state': state.lower(),
'public_ips': linfos['public_ips'],
'private_ips': linfos['private_ips'],
}
else:
nodes[lxcc] = {'id': lxcc, 'state': state.lower()}
return nodes
def list_nodes_full(conn=None, call=None):
if not get_configured_provider():
return
if not call:
call = 'action'
return list_nodes(conn=conn, call=call)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if not get_configured_provider():
return
if not call:
call = 'action'
nodes = list_nodes_full(call=call)
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not call:
call = 'select'
if not get_configured_provider():
return
info = ['id', 'name', 'image', 'size', 'state', 'public_ips', 'private_ips']
return salt.utils.cloud.list_nodes_select(
list_nodes_full(call='action'),
__opts__.get('query.selection', info), call)
def _checkpoint(ret):
sret = '''
id: {name}
last message: {comment}'''.format(**ret)
keys = list(ret['changes'].items())
keys.sort()
for ch, comment in keys:
sret += (
'\n'
' {0}:\n'
' {1}'
).format(ch, comment.replace(
'\n',
'\n'
' '))
if not ret['result']:
if 'changes' in ret:
del ret['changes']
raise SaltCloudSystemExit(sret)
log.info(sret)
return sret
def destroy(vm_, call=None):
'''Destroy a lxc container'''
destroy_opt = __opts__.get('destroy', False)
profiles = __opts__.get('profiles', {})
profile = __opts__.get('profile',
__opts__.get('internal_lxc_profile', []))
path = None
if profile and profile in profiles:
path = profiles[profile].get('path', None)
action = __opts__.get('action', '')
if action != 'destroy' and not destroy_opt:
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not get_configured_provider():
return
ret = {'comment': '{0} was not found'.format(vm_),
'result': False}
if _salt('lxc.info', vm_, path=path):
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(vm_),
args={'name': vm_, 'instance_id': vm_},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
cret = _salt('lxc.destroy', vm_, stop=True, path=path)
ret['result'] = cret['result']
if ret['result']:
ret['comment'] = '{0} was destroyed'.format(vm_)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(vm_),
args={'name': vm_, 'instance_id': vm_},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](vm_, __active_provider_name__.split(':')[0], __opts__)
return ret
def create(vm_, call=None):
'''Create an lxc Container.
This function is idempotent and will try to either provision
or finish the provision of an lxc container.
NOTE: Most of the initialization code has been moved and merged
with the lxc runner and lxc.init functions
'''
prov = get_configured_provider(vm_)
if not prov:
return
# we cant use profile as a configuration key as it conflicts
# with salt cloud internals
profile = vm_.get(
'lxc_profile',
vm_.get('container_profile', None))
event_data = vm_.copy()
event_data['profile'] = profile
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', event_data, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
ret = {'name': vm_['name'], 'changes': {}, 'result': True, 'comment': ''}
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for %s', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value(
'keysize', vm_, __opts__))
# get the minion key pair to distribute back to the container
kwarg = copy.deepcopy(vm_)
kwarg['host'] = prov['target']
kwarg['profile'] = profile
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
cret = _runner().cmd('lxc.cloud_init', [vm_['name']], kwarg=kwarg)
ret['runner_return'] = cret
ret['result'] = cret['result']
if not ret['result']:
ret['Error'] = 'Error while creating {0},'.format(vm_['name'])
else:
ret['changes']['created'] = 'created'
# When using cloud states to manage LXC containers
# __opts__['profile'] is not implicitly reset between operations
# on different containers. However list_nodes will hide container
# if profile is set in opts assuming that it have to be created.
# But in cloud state we do want to check at first if it really
# exists hence the need to remove profile from global opts once
# current container is created.
if 'profile' in __opts__:
__opts__['internal_lxc_profile'] = __opts__['profile']
del __opts__['profile']
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def get_provider(name):
data = None
if name in __opts__['providers']:
data = __opts__['providers'][name]
if 'lxc' in data:
data = data['lxc']
else:
data = None
return data
def get_configured_provider(vm_=None):
'''
Return the contextual provider of None if no configured
one can be found.
'''
if vm_ is None:
vm_ = {}
dalias, driver = __active_provider_name__.split(':')
data = None
tgt = 'unknown'
img_provider = __opts__.get('list_images', '')
arg_providers = __opts__.get('names', [])
matched = False
# --list-images level
if img_provider:
tgt = 'provider: {0}'.format(img_provider)
if dalias == img_provider:
data = get_provider(img_provider)
matched = True
# providers are set in configuration
if not data and 'profile' not in __opts__ and arg_providers:
for name in arg_providers:
tgt = 'provider: {0}'.format(name)
if dalias == name:
data = get_provider(name)
if data:
matched = True
break
# -p is providen, get the uplinked provider
elif 'profile' in __opts__:
curprof = __opts__['profile']
profs = __opts__['profiles']
tgt = 'profile: {0}'.format(curprof)
if (
curprof in profs and
profs[curprof]['provider'] == __active_provider_name__
):
prov, cdriver = profs[curprof]['provider'].split(':')
tgt += ' provider: {0}'.format(prov)
data = get_provider(prov)
matched = True
# fallback if we have only __active_provider_name__
if (
(__opts__.get('destroy', False) and not data) or (
not matched and __active_provider_name__
)
):
data = __opts__.get('providers',
{}).get(dalias, {}).get(driver, {})
# in all cases, verify that the linked saltmaster is alive.
if data:
ret = _salt('test.ping', salt_target=data['target'])
if ret:
return data
else:
log.error(
'Configured provider %s minion: %s is unreachable',
__active_provider_name__, data['target']
)
return False
|
saltstack/salt
|
salt/cloud/clouds/lxc.py
|
list_nodes_select
|
python
|
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not call:
call = 'select'
if not get_configured_provider():
return
info = ['id', 'name', 'image', 'size', 'state', 'public_ips', 'private_ips']
return salt.utils.cloud.list_nodes_select(
list_nodes_full(call='action'),
__opts__.get('query.selection', info), call)
|
Return a list of the VMs that are on the provider, with select fields
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/lxc.py#L338-L349
|
[
"def list_nodes_full(conn=None, call=None):\n if not get_configured_provider():\n return\n if not call:\n call = 'action'\n return list_nodes(conn=conn, call=call)\n",
"def list_nodes_select(nodes, selection, call=None):\n '''\n Return a list of the VMs that are on the provider, with select fields\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes_select function must be called '\n 'with -f or --function.'\n )\n\n if 'error' in nodes:\n raise SaltCloudSystemExit(\n 'An error occurred while listing nodes: {0}'.format(\n nodes['error']['Errors']['Error']['Message']\n )\n )\n\n ret = {}\n for node in nodes:\n pairs = {}\n data = nodes[node]\n for key in data:\n if six.text_type(key) in selection:\n value = data[key]\n pairs[key] = value\n ret[node] = pairs\n\n return ret\n",
"def get_configured_provider(vm_=None):\n '''\n Return the contextual provider of None if no configured\n one can be found.\n '''\n if vm_ is None:\n vm_ = {}\n dalias, driver = __active_provider_name__.split(':')\n data = None\n tgt = 'unknown'\n img_provider = __opts__.get('list_images', '')\n arg_providers = __opts__.get('names', [])\n matched = False\n # --list-images level\n if img_provider:\n tgt = 'provider: {0}'.format(img_provider)\n if dalias == img_provider:\n data = get_provider(img_provider)\n matched = True\n # providers are set in configuration\n if not data and 'profile' not in __opts__ and arg_providers:\n for name in arg_providers:\n tgt = 'provider: {0}'.format(name)\n if dalias == name:\n data = get_provider(name)\n if data:\n matched = True\n break\n # -p is providen, get the uplinked provider\n elif 'profile' in __opts__:\n curprof = __opts__['profile']\n profs = __opts__['profiles']\n tgt = 'profile: {0}'.format(curprof)\n if (\n curprof in profs and\n profs[curprof]['provider'] == __active_provider_name__\n ):\n prov, cdriver = profs[curprof]['provider'].split(':')\n tgt += ' provider: {0}'.format(prov)\n data = get_provider(prov)\n matched = True\n # fallback if we have only __active_provider_name__\n if (\n (__opts__.get('destroy', False) and not data) or (\n not matched and __active_provider_name__\n )\n ):\n data = __opts__.get('providers',\n {}).get(dalias, {}).get(driver, {})\n # in all cases, verify that the linked saltmaster is alive.\n if data:\n ret = _salt('test.ping', salt_target=data['target'])\n if ret:\n return data\n else:\n log.error(\n 'Configured provider %s minion: %s is unreachable',\n __active_provider_name__, data['target']\n )\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Install Salt on an LXC Container
================================
.. versionadded:: 2014.7.0
Please read :ref:`core config documentation <config_lxc>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import os
import pprint
import time
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.client
import salt.runner
# Import 3rd-party libs
from salt.ext import six
# Get logging started
log = logging.getLogger(__name__)
__FUN_TIMEOUT = {
'cmd.run': 60 * 60,
'test.ping': 10,
'lxc.info': 40,
'lxc.list': 300,
'lxc.templates': 100,
'grains.items': 100,
}
__CACHED_CALLS = {}
__CACHED_FUNS = {
'test.ping': 3 * 60, # cache ping for 3 minutes
'lxc.list': 2 # cache lxc.list for 2 seconds
}
def __virtual__():
'''
Needs no special configuration
'''
return True
def _get_grain_id(id_):
if not get_configured_provider():
return
infos = get_configured_provider()
return 'salt.cloud.lxc.{0}.{1}'.format(infos['target'], id_)
def _minion_opts(cfg='minion'):
if 'conf_file' in __opts__:
default_dir = os.path.dirname(__opts__['conf_file'])
else:
default_dir = __opts__['config_dir'],
cfg = os.environ.get(
'SALT_MINION_CONFIG', os.path.join(default_dir, cfg))
opts = config.minion_config(cfg)
return opts
def _master_opts(cfg='master'):
if 'conf_file' in __opts__:
default_dir = os.path.dirname(__opts__['conf_file'])
else:
default_dir = __opts__['config_dir'],
cfg = os.environ.get(
'SALT_MASTER_CONFIG', os.path.join(default_dir, cfg))
opts = config.master_config(cfg)
opts['output'] = 'quiet'
return opts
def _client():
return salt.client.get_local_client(mopts=_master_opts())
def _runner():
# opts = _master_opts()
# opts['output'] = 'quiet'
return salt.runner.RunnerClient(_master_opts())
def _salt(fun, *args, **kw):
'''Execute a salt function on a specific minion
Special kwargs:
salt_target
target to exec things on
salt_timeout
timeout for jobs
salt_job_poll
poll interval to wait for job finish result
'''
try:
poll = kw.pop('salt_job_poll')
except KeyError:
poll = 0.1
try:
target = kw.pop('salt_target')
except KeyError:
target = None
try:
timeout = int(kw.pop('salt_timeout'))
except (KeyError, ValueError):
# try to has some low timeouts for very basic commands
timeout = __FUN_TIMEOUT.get(
fun,
900 # wait up to 15 minutes for the default timeout
)
try:
kwargs = kw.pop('kwargs')
except KeyError:
kwargs = {}
if not target:
infos = get_configured_provider()
if not infos:
return
target = infos['target']
laps = time.time()
cache = False
if fun in __CACHED_FUNS:
cache = True
laps = laps // __CACHED_FUNS[fun]
try:
sargs = salt.utils.json.dumps(args)
except TypeError:
sargs = ''
try:
skw = salt.utils.json.dumps(kw)
except TypeError:
skw = ''
try:
skwargs = salt.utils.json.dumps(kwargs)
except TypeError:
skwargs = ''
cache_key = (laps, target, fun, sargs, skw, skwargs)
if not cache or (cache and (cache_key not in __CACHED_CALLS)):
conn = _client()
runner = _runner()
rkwargs = kwargs.copy()
rkwargs['timeout'] = timeout
rkwargs.setdefault('tgt_type', 'list')
kwargs.setdefault('tgt_type', 'list')
ping_retries = 0
# the target(s) have environ one minute to respond
# we call 60 ping request, this prevent us
# from blindly send commands to unmatched minions
ping_max_retries = 60
ping = True
# do not check ping... if we are pinguing
if fun == 'test.ping':
ping_retries = ping_max_retries + 1
# be sure that the executors are alive
while ping_retries <= ping_max_retries:
try:
if ping_retries > 0:
time.sleep(1)
pings = conn.cmd(tgt=target,
timeout=10,
fun='test.ping')
values = list(pings.values())
if not values:
ping = False
for v in values:
if v is not True:
ping = False
if not ping:
raise ValueError('Unreachable')
break
except Exception:
ping = False
ping_retries += 1
log.error('%s unreachable, retrying', target)
if not ping:
raise SaltCloudSystemExit('Target {0} unreachable'.format(target))
jid = conn.cmd_async(tgt=target,
fun=fun,
arg=args,
kwarg=kw,
**rkwargs)
cret = conn.cmd(tgt=target,
fun='saltutil.find_job',
arg=[jid],
timeout=10,
**kwargs)
running = bool(cret.get(target, False))
endto = time.time() + timeout
while running:
rkwargs = {
'tgt': target,
'fun': 'saltutil.find_job',
'arg': [jid],
'timeout': 10
}
cret = conn.cmd(**rkwargs)
running = bool(cret.get(target, False))
if not running:
break
if running and (time.time() > endto):
raise Exception('Timeout {0}s for {1} is elapsed'.format(
timeout, pprint.pformat(rkwargs)))
time.sleep(poll)
# timeout for the master to return data about a specific job
wait_for_res = float({
'test.ping': '5',
}.get(fun, '120'))
while wait_for_res:
wait_for_res -= 0.5
cret = runner.cmd(
'jobs.lookup_jid',
[jid, {'__kwarg__': True}])
if target in cret:
ret = cret[target]
break
# recent changes
elif 'data' in cret and 'outputter' in cret:
ret = cret['data']
break
# special case, some answers may be crafted
# to handle the unresponsivness of a specific command
# which is also meaningful, e.g. a minion not yet provisioned
if fun in ['test.ping'] and not wait_for_res:
ret = {
'test.ping': False,
}.get(fun, False)
time.sleep(0.5)
try:
if 'is not available.' in ret:
raise SaltCloudSystemExit(
'module/function {0} is not available'.format(fun))
except SaltCloudSystemExit:
raise
except TypeError:
pass
if cache:
__CACHED_CALLS[cache_key] = ret
elif cache and cache_key in __CACHED_CALLS:
ret = __CACHED_CALLS[cache_key]
return ret
def avail_images():
return _salt('lxc.templates')
def list_nodes(conn=None, call=None):
hide = False
names = __opts__.get('names', [])
profiles = __opts__.get('profiles', {})
profile = __opts__.get('profile',
__opts__.get('internal_lxc_profile', []))
destroy_opt = __opts__.get('destroy', False)
action = __opts__.get('action', '')
for opt in ['full_query', 'select_query', 'query']:
if __opts__.get(opt, False):
call = 'full'
if destroy_opt:
call = 'full'
if action and not call:
call = 'action'
if profile and names and not destroy_opt:
hide = True
if not get_configured_provider():
return
path = None
if profile and profile in profiles:
path = profiles[profile].get('path', None)
lxclist = _salt('lxc.list', extra=True, path=path)
nodes = {}
for state, lxcs in six.iteritems(lxclist):
for lxcc, linfos in six.iteritems(lxcs):
info = {
'id': lxcc,
'name': lxcc, # required for cloud cache
'image': None,
'size': linfos['size'],
'state': state.lower(),
'public_ips': linfos['public_ips'],
'private_ips': linfos['private_ips'],
}
# in creation mode, we need to go inside the create method
# so we hide the running vm from being seen as already installed
# do not also mask half configured nodes which are explicitly asked
# to be acted on, on the command line
if (call in ['full'] or not hide) and ((lxcc in names and call in ['action']) or call in ['full']):
nodes[lxcc] = {
'id': lxcc,
'name': lxcc, # required for cloud cache
'image': None,
'size': linfos['size'],
'state': state.lower(),
'public_ips': linfos['public_ips'],
'private_ips': linfos['private_ips'],
}
else:
nodes[lxcc] = {'id': lxcc, 'state': state.lower()}
return nodes
def list_nodes_full(conn=None, call=None):
if not get_configured_provider():
return
if not call:
call = 'action'
return list_nodes(conn=conn, call=call)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if not get_configured_provider():
return
if not call:
call = 'action'
nodes = list_nodes_full(call=call)
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def _checkpoint(ret):
sret = '''
id: {name}
last message: {comment}'''.format(**ret)
keys = list(ret['changes'].items())
keys.sort()
for ch, comment in keys:
sret += (
'\n'
' {0}:\n'
' {1}'
).format(ch, comment.replace(
'\n',
'\n'
' '))
if not ret['result']:
if 'changes' in ret:
del ret['changes']
raise SaltCloudSystemExit(sret)
log.info(sret)
return sret
def destroy(vm_, call=None):
'''Destroy a lxc container'''
destroy_opt = __opts__.get('destroy', False)
profiles = __opts__.get('profiles', {})
profile = __opts__.get('profile',
__opts__.get('internal_lxc_profile', []))
path = None
if profile and profile in profiles:
path = profiles[profile].get('path', None)
action = __opts__.get('action', '')
if action != 'destroy' and not destroy_opt:
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not get_configured_provider():
return
ret = {'comment': '{0} was not found'.format(vm_),
'result': False}
if _salt('lxc.info', vm_, path=path):
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(vm_),
args={'name': vm_, 'instance_id': vm_},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
cret = _salt('lxc.destroy', vm_, stop=True, path=path)
ret['result'] = cret['result']
if ret['result']:
ret['comment'] = '{0} was destroyed'.format(vm_)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(vm_),
args={'name': vm_, 'instance_id': vm_},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](vm_, __active_provider_name__.split(':')[0], __opts__)
return ret
def create(vm_, call=None):
'''Create an lxc Container.
This function is idempotent and will try to either provision
or finish the provision of an lxc container.
NOTE: Most of the initialization code has been moved and merged
with the lxc runner and lxc.init functions
'''
prov = get_configured_provider(vm_)
if not prov:
return
# we cant use profile as a configuration key as it conflicts
# with salt cloud internals
profile = vm_.get(
'lxc_profile',
vm_.get('container_profile', None))
event_data = vm_.copy()
event_data['profile'] = profile
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', event_data, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
ret = {'name': vm_['name'], 'changes': {}, 'result': True, 'comment': ''}
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for %s', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value(
'keysize', vm_, __opts__))
# get the minion key pair to distribute back to the container
kwarg = copy.deepcopy(vm_)
kwarg['host'] = prov['target']
kwarg['profile'] = profile
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
cret = _runner().cmd('lxc.cloud_init', [vm_['name']], kwarg=kwarg)
ret['runner_return'] = cret
ret['result'] = cret['result']
if not ret['result']:
ret['Error'] = 'Error while creating {0},'.format(vm_['name'])
else:
ret['changes']['created'] = 'created'
# When using cloud states to manage LXC containers
# __opts__['profile'] is not implicitly reset between operations
# on different containers. However list_nodes will hide container
# if profile is set in opts assuming that it have to be created.
# But in cloud state we do want to check at first if it really
# exists hence the need to remove profile from global opts once
# current container is created.
if 'profile' in __opts__:
__opts__['internal_lxc_profile'] = __opts__['profile']
del __opts__['profile']
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def get_provider(name):
data = None
if name in __opts__['providers']:
data = __opts__['providers'][name]
if 'lxc' in data:
data = data['lxc']
else:
data = None
return data
def get_configured_provider(vm_=None):
'''
Return the contextual provider of None if no configured
one can be found.
'''
if vm_ is None:
vm_ = {}
dalias, driver = __active_provider_name__.split(':')
data = None
tgt = 'unknown'
img_provider = __opts__.get('list_images', '')
arg_providers = __opts__.get('names', [])
matched = False
# --list-images level
if img_provider:
tgt = 'provider: {0}'.format(img_provider)
if dalias == img_provider:
data = get_provider(img_provider)
matched = True
# providers are set in configuration
if not data and 'profile' not in __opts__ and arg_providers:
for name in arg_providers:
tgt = 'provider: {0}'.format(name)
if dalias == name:
data = get_provider(name)
if data:
matched = True
break
# -p is providen, get the uplinked provider
elif 'profile' in __opts__:
curprof = __opts__['profile']
profs = __opts__['profiles']
tgt = 'profile: {0}'.format(curprof)
if (
curprof in profs and
profs[curprof]['provider'] == __active_provider_name__
):
prov, cdriver = profs[curprof]['provider'].split(':')
tgt += ' provider: {0}'.format(prov)
data = get_provider(prov)
matched = True
# fallback if we have only __active_provider_name__
if (
(__opts__.get('destroy', False) and not data) or (
not matched and __active_provider_name__
)
):
data = __opts__.get('providers',
{}).get(dalias, {}).get(driver, {})
# in all cases, verify that the linked saltmaster is alive.
if data:
ret = _salt('test.ping', salt_target=data['target'])
if ret:
return data
else:
log.error(
'Configured provider %s minion: %s is unreachable',
__active_provider_name__, data['target']
)
return False
|
saltstack/salt
|
salt/cloud/clouds/lxc.py
|
destroy
|
python
|
def destroy(vm_, call=None):
'''Destroy a lxc container'''
destroy_opt = __opts__.get('destroy', False)
profiles = __opts__.get('profiles', {})
profile = __opts__.get('profile',
__opts__.get('internal_lxc_profile', []))
path = None
if profile and profile in profiles:
path = profiles[profile].get('path', None)
action = __opts__.get('action', '')
if action != 'destroy' and not destroy_opt:
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not get_configured_provider():
return
ret = {'comment': '{0} was not found'.format(vm_),
'result': False}
if _salt('lxc.info', vm_, path=path):
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(vm_),
args={'name': vm_, 'instance_id': vm_},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
cret = _salt('lxc.destroy', vm_, stop=True, path=path)
ret['result'] = cret['result']
if ret['result']:
ret['comment'] = '{0} was destroyed'.format(vm_)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(vm_),
args={'name': vm_, 'instance_id': vm_},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](vm_, __active_provider_name__.split(':')[0], __opts__)
return ret
|
Destroy a lxc container
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/lxc.py#L375-L417
|
[
"def get_configured_provider(vm_=None):\n '''\n Return the contextual provider of None if no configured\n one can be found.\n '''\n if vm_ is None:\n vm_ = {}\n dalias, driver = __active_provider_name__.split(':')\n data = None\n tgt = 'unknown'\n img_provider = __opts__.get('list_images', '')\n arg_providers = __opts__.get('names', [])\n matched = False\n # --list-images level\n if img_provider:\n tgt = 'provider: {0}'.format(img_provider)\n if dalias == img_provider:\n data = get_provider(img_provider)\n matched = True\n # providers are set in configuration\n if not data and 'profile' not in __opts__ and arg_providers:\n for name in arg_providers:\n tgt = 'provider: {0}'.format(name)\n if dalias == name:\n data = get_provider(name)\n if data:\n matched = True\n break\n # -p is providen, get the uplinked provider\n elif 'profile' in __opts__:\n curprof = __opts__['profile']\n profs = __opts__['profiles']\n tgt = 'profile: {0}'.format(curprof)\n if (\n curprof in profs and\n profs[curprof]['provider'] == __active_provider_name__\n ):\n prov, cdriver = profs[curprof]['provider'].split(':')\n tgt += ' provider: {0}'.format(prov)\n data = get_provider(prov)\n matched = True\n # fallback if we have only __active_provider_name__\n if (\n (__opts__.get('destroy', False) and not data) or (\n not matched and __active_provider_name__\n )\n ):\n data = __opts__.get('providers',\n {}).get(dalias, {}).get(driver, {})\n # in all cases, verify that the linked saltmaster is alive.\n if data:\n ret = _salt('test.ping', salt_target=data['target'])\n if ret:\n return data\n else:\n log.error(\n 'Configured provider %s minion: %s is unreachable',\n __active_provider_name__, data['target']\n )\n return False\n",
"def _salt(fun, *args, **kw):\n '''Execute a salt function on a specific minion\n\n Special kwargs:\n\n salt_target\n target to exec things on\n salt_timeout\n timeout for jobs\n salt_job_poll\n poll interval to wait for job finish result\n '''\n try:\n poll = kw.pop('salt_job_poll')\n except KeyError:\n poll = 0.1\n try:\n target = kw.pop('salt_target')\n except KeyError:\n target = None\n try:\n timeout = int(kw.pop('salt_timeout'))\n except (KeyError, ValueError):\n # try to has some low timeouts for very basic commands\n timeout = __FUN_TIMEOUT.get(\n fun,\n 900 # wait up to 15 minutes for the default timeout\n )\n try:\n kwargs = kw.pop('kwargs')\n except KeyError:\n kwargs = {}\n if not target:\n infos = get_configured_provider()\n if not infos:\n return\n target = infos['target']\n laps = time.time()\n cache = False\n if fun in __CACHED_FUNS:\n cache = True\n laps = laps // __CACHED_FUNS[fun]\n try:\n sargs = salt.utils.json.dumps(args)\n except TypeError:\n sargs = ''\n try:\n skw = salt.utils.json.dumps(kw)\n except TypeError:\n skw = ''\n try:\n skwargs = salt.utils.json.dumps(kwargs)\n except TypeError:\n skwargs = ''\n cache_key = (laps, target, fun, sargs, skw, skwargs)\n if not cache or (cache and (cache_key not in __CACHED_CALLS)):\n conn = _client()\n runner = _runner()\n rkwargs = kwargs.copy()\n rkwargs['timeout'] = timeout\n rkwargs.setdefault('tgt_type', 'list')\n kwargs.setdefault('tgt_type', 'list')\n ping_retries = 0\n # the target(s) have environ one minute to respond\n # we call 60 ping request, this prevent us\n # from blindly send commands to unmatched minions\n ping_max_retries = 60\n ping = True\n # do not check ping... if we are pinguing\n if fun == 'test.ping':\n ping_retries = ping_max_retries + 1\n # be sure that the executors are alive\n while ping_retries <= ping_max_retries:\n try:\n if ping_retries > 0:\n time.sleep(1)\n pings = conn.cmd(tgt=target,\n timeout=10,\n fun='test.ping')\n values = list(pings.values())\n if not values:\n ping = False\n for v in values:\n if v is not True:\n ping = False\n if not ping:\n raise ValueError('Unreachable')\n break\n except Exception:\n ping = False\n ping_retries += 1\n log.error('%s unreachable, retrying', target)\n if not ping:\n raise SaltCloudSystemExit('Target {0} unreachable'.format(target))\n jid = conn.cmd_async(tgt=target,\n fun=fun,\n arg=args,\n kwarg=kw,\n **rkwargs)\n cret = conn.cmd(tgt=target,\n fun='saltutil.find_job',\n arg=[jid],\n timeout=10,\n **kwargs)\n running = bool(cret.get(target, False))\n endto = time.time() + timeout\n while running:\n rkwargs = {\n 'tgt': target,\n 'fun': 'saltutil.find_job',\n 'arg': [jid],\n 'timeout': 10\n }\n cret = conn.cmd(**rkwargs)\n running = bool(cret.get(target, False))\n if not running:\n break\n if running and (time.time() > endto):\n raise Exception('Timeout {0}s for {1} is elapsed'.format(\n timeout, pprint.pformat(rkwargs)))\n time.sleep(poll)\n # timeout for the master to return data about a specific job\n wait_for_res = float({\n 'test.ping': '5',\n }.get(fun, '120'))\n while wait_for_res:\n wait_for_res -= 0.5\n cret = runner.cmd(\n 'jobs.lookup_jid',\n [jid, {'__kwarg__': True}])\n if target in cret:\n ret = cret[target]\n break\n # recent changes\n elif 'data' in cret and 'outputter' in cret:\n ret = cret['data']\n break\n # special case, some answers may be crafted\n # to handle the unresponsivness of a specific command\n # which is also meaningful, e.g. a minion not yet provisioned\n if fun in ['test.ping'] and not wait_for_res:\n ret = {\n 'test.ping': False,\n }.get(fun, False)\n time.sleep(0.5)\n try:\n if 'is not available.' in ret:\n raise SaltCloudSystemExit(\n 'module/function {0} is not available'.format(fun))\n except SaltCloudSystemExit:\n raise\n except TypeError:\n pass\n if cache:\n __CACHED_CALLS[cache_key] = ret\n elif cache and cache_key in __CACHED_CALLS:\n ret = __CACHED_CALLS[cache_key]\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Install Salt on an LXC Container
================================
.. versionadded:: 2014.7.0
Please read :ref:`core config documentation <config_lxc>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import os
import pprint
import time
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.client
import salt.runner
# Import 3rd-party libs
from salt.ext import six
# Get logging started
log = logging.getLogger(__name__)
__FUN_TIMEOUT = {
'cmd.run': 60 * 60,
'test.ping': 10,
'lxc.info': 40,
'lxc.list': 300,
'lxc.templates': 100,
'grains.items': 100,
}
__CACHED_CALLS = {}
__CACHED_FUNS = {
'test.ping': 3 * 60, # cache ping for 3 minutes
'lxc.list': 2 # cache lxc.list for 2 seconds
}
def __virtual__():
'''
Needs no special configuration
'''
return True
def _get_grain_id(id_):
if not get_configured_provider():
return
infos = get_configured_provider()
return 'salt.cloud.lxc.{0}.{1}'.format(infos['target'], id_)
def _minion_opts(cfg='minion'):
if 'conf_file' in __opts__:
default_dir = os.path.dirname(__opts__['conf_file'])
else:
default_dir = __opts__['config_dir'],
cfg = os.environ.get(
'SALT_MINION_CONFIG', os.path.join(default_dir, cfg))
opts = config.minion_config(cfg)
return opts
def _master_opts(cfg='master'):
if 'conf_file' in __opts__:
default_dir = os.path.dirname(__opts__['conf_file'])
else:
default_dir = __opts__['config_dir'],
cfg = os.environ.get(
'SALT_MASTER_CONFIG', os.path.join(default_dir, cfg))
opts = config.master_config(cfg)
opts['output'] = 'quiet'
return opts
def _client():
return salt.client.get_local_client(mopts=_master_opts())
def _runner():
# opts = _master_opts()
# opts['output'] = 'quiet'
return salt.runner.RunnerClient(_master_opts())
def _salt(fun, *args, **kw):
'''Execute a salt function on a specific minion
Special kwargs:
salt_target
target to exec things on
salt_timeout
timeout for jobs
salt_job_poll
poll interval to wait for job finish result
'''
try:
poll = kw.pop('salt_job_poll')
except KeyError:
poll = 0.1
try:
target = kw.pop('salt_target')
except KeyError:
target = None
try:
timeout = int(kw.pop('salt_timeout'))
except (KeyError, ValueError):
# try to has some low timeouts for very basic commands
timeout = __FUN_TIMEOUT.get(
fun,
900 # wait up to 15 minutes for the default timeout
)
try:
kwargs = kw.pop('kwargs')
except KeyError:
kwargs = {}
if not target:
infos = get_configured_provider()
if not infos:
return
target = infos['target']
laps = time.time()
cache = False
if fun in __CACHED_FUNS:
cache = True
laps = laps // __CACHED_FUNS[fun]
try:
sargs = salt.utils.json.dumps(args)
except TypeError:
sargs = ''
try:
skw = salt.utils.json.dumps(kw)
except TypeError:
skw = ''
try:
skwargs = salt.utils.json.dumps(kwargs)
except TypeError:
skwargs = ''
cache_key = (laps, target, fun, sargs, skw, skwargs)
if not cache or (cache and (cache_key not in __CACHED_CALLS)):
conn = _client()
runner = _runner()
rkwargs = kwargs.copy()
rkwargs['timeout'] = timeout
rkwargs.setdefault('tgt_type', 'list')
kwargs.setdefault('tgt_type', 'list')
ping_retries = 0
# the target(s) have environ one minute to respond
# we call 60 ping request, this prevent us
# from blindly send commands to unmatched minions
ping_max_retries = 60
ping = True
# do not check ping... if we are pinguing
if fun == 'test.ping':
ping_retries = ping_max_retries + 1
# be sure that the executors are alive
while ping_retries <= ping_max_retries:
try:
if ping_retries > 0:
time.sleep(1)
pings = conn.cmd(tgt=target,
timeout=10,
fun='test.ping')
values = list(pings.values())
if not values:
ping = False
for v in values:
if v is not True:
ping = False
if not ping:
raise ValueError('Unreachable')
break
except Exception:
ping = False
ping_retries += 1
log.error('%s unreachable, retrying', target)
if not ping:
raise SaltCloudSystemExit('Target {0} unreachable'.format(target))
jid = conn.cmd_async(tgt=target,
fun=fun,
arg=args,
kwarg=kw,
**rkwargs)
cret = conn.cmd(tgt=target,
fun='saltutil.find_job',
arg=[jid],
timeout=10,
**kwargs)
running = bool(cret.get(target, False))
endto = time.time() + timeout
while running:
rkwargs = {
'tgt': target,
'fun': 'saltutil.find_job',
'arg': [jid],
'timeout': 10
}
cret = conn.cmd(**rkwargs)
running = bool(cret.get(target, False))
if not running:
break
if running and (time.time() > endto):
raise Exception('Timeout {0}s for {1} is elapsed'.format(
timeout, pprint.pformat(rkwargs)))
time.sleep(poll)
# timeout for the master to return data about a specific job
wait_for_res = float({
'test.ping': '5',
}.get(fun, '120'))
while wait_for_res:
wait_for_res -= 0.5
cret = runner.cmd(
'jobs.lookup_jid',
[jid, {'__kwarg__': True}])
if target in cret:
ret = cret[target]
break
# recent changes
elif 'data' in cret and 'outputter' in cret:
ret = cret['data']
break
# special case, some answers may be crafted
# to handle the unresponsivness of a specific command
# which is also meaningful, e.g. a minion not yet provisioned
if fun in ['test.ping'] and not wait_for_res:
ret = {
'test.ping': False,
}.get(fun, False)
time.sleep(0.5)
try:
if 'is not available.' in ret:
raise SaltCloudSystemExit(
'module/function {0} is not available'.format(fun))
except SaltCloudSystemExit:
raise
except TypeError:
pass
if cache:
__CACHED_CALLS[cache_key] = ret
elif cache and cache_key in __CACHED_CALLS:
ret = __CACHED_CALLS[cache_key]
return ret
def avail_images():
return _salt('lxc.templates')
def list_nodes(conn=None, call=None):
hide = False
names = __opts__.get('names', [])
profiles = __opts__.get('profiles', {})
profile = __opts__.get('profile',
__opts__.get('internal_lxc_profile', []))
destroy_opt = __opts__.get('destroy', False)
action = __opts__.get('action', '')
for opt in ['full_query', 'select_query', 'query']:
if __opts__.get(opt, False):
call = 'full'
if destroy_opt:
call = 'full'
if action and not call:
call = 'action'
if profile and names and not destroy_opt:
hide = True
if not get_configured_provider():
return
path = None
if profile and profile in profiles:
path = profiles[profile].get('path', None)
lxclist = _salt('lxc.list', extra=True, path=path)
nodes = {}
for state, lxcs in six.iteritems(lxclist):
for lxcc, linfos in six.iteritems(lxcs):
info = {
'id': lxcc,
'name': lxcc, # required for cloud cache
'image': None,
'size': linfos['size'],
'state': state.lower(),
'public_ips': linfos['public_ips'],
'private_ips': linfos['private_ips'],
}
# in creation mode, we need to go inside the create method
# so we hide the running vm from being seen as already installed
# do not also mask half configured nodes which are explicitly asked
# to be acted on, on the command line
if (call in ['full'] or not hide) and ((lxcc in names and call in ['action']) or call in ['full']):
nodes[lxcc] = {
'id': lxcc,
'name': lxcc, # required for cloud cache
'image': None,
'size': linfos['size'],
'state': state.lower(),
'public_ips': linfos['public_ips'],
'private_ips': linfos['private_ips'],
}
else:
nodes[lxcc] = {'id': lxcc, 'state': state.lower()}
return nodes
def list_nodes_full(conn=None, call=None):
if not get_configured_provider():
return
if not call:
call = 'action'
return list_nodes(conn=conn, call=call)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if not get_configured_provider():
return
if not call:
call = 'action'
nodes = list_nodes_full(call=call)
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not call:
call = 'select'
if not get_configured_provider():
return
info = ['id', 'name', 'image', 'size', 'state', 'public_ips', 'private_ips']
return salt.utils.cloud.list_nodes_select(
list_nodes_full(call='action'),
__opts__.get('query.selection', info), call)
def _checkpoint(ret):
sret = '''
id: {name}
last message: {comment}'''.format(**ret)
keys = list(ret['changes'].items())
keys.sort()
for ch, comment in keys:
sret += (
'\n'
' {0}:\n'
' {1}'
).format(ch, comment.replace(
'\n',
'\n'
' '))
if not ret['result']:
if 'changes' in ret:
del ret['changes']
raise SaltCloudSystemExit(sret)
log.info(sret)
return sret
def create(vm_, call=None):
'''Create an lxc Container.
This function is idempotent and will try to either provision
or finish the provision of an lxc container.
NOTE: Most of the initialization code has been moved and merged
with the lxc runner and lxc.init functions
'''
prov = get_configured_provider(vm_)
if not prov:
return
# we cant use profile as a configuration key as it conflicts
# with salt cloud internals
profile = vm_.get(
'lxc_profile',
vm_.get('container_profile', None))
event_data = vm_.copy()
event_data['profile'] = profile
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', event_data, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
ret = {'name': vm_['name'], 'changes': {}, 'result': True, 'comment': ''}
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for %s', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value(
'keysize', vm_, __opts__))
# get the minion key pair to distribute back to the container
kwarg = copy.deepcopy(vm_)
kwarg['host'] = prov['target']
kwarg['profile'] = profile
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
cret = _runner().cmd('lxc.cloud_init', [vm_['name']], kwarg=kwarg)
ret['runner_return'] = cret
ret['result'] = cret['result']
if not ret['result']:
ret['Error'] = 'Error while creating {0},'.format(vm_['name'])
else:
ret['changes']['created'] = 'created'
# When using cloud states to manage LXC containers
# __opts__['profile'] is not implicitly reset between operations
# on different containers. However list_nodes will hide container
# if profile is set in opts assuming that it have to be created.
# But in cloud state we do want to check at first if it really
# exists hence the need to remove profile from global opts once
# current container is created.
if 'profile' in __opts__:
__opts__['internal_lxc_profile'] = __opts__['profile']
del __opts__['profile']
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def get_provider(name):
data = None
if name in __opts__['providers']:
data = __opts__['providers'][name]
if 'lxc' in data:
data = data['lxc']
else:
data = None
return data
def get_configured_provider(vm_=None):
'''
Return the contextual provider of None if no configured
one can be found.
'''
if vm_ is None:
vm_ = {}
dalias, driver = __active_provider_name__.split(':')
data = None
tgt = 'unknown'
img_provider = __opts__.get('list_images', '')
arg_providers = __opts__.get('names', [])
matched = False
# --list-images level
if img_provider:
tgt = 'provider: {0}'.format(img_provider)
if dalias == img_provider:
data = get_provider(img_provider)
matched = True
# providers are set in configuration
if not data and 'profile' not in __opts__ and arg_providers:
for name in arg_providers:
tgt = 'provider: {0}'.format(name)
if dalias == name:
data = get_provider(name)
if data:
matched = True
break
# -p is providen, get the uplinked provider
elif 'profile' in __opts__:
curprof = __opts__['profile']
profs = __opts__['profiles']
tgt = 'profile: {0}'.format(curprof)
if (
curprof in profs and
profs[curprof]['provider'] == __active_provider_name__
):
prov, cdriver = profs[curprof]['provider'].split(':')
tgt += ' provider: {0}'.format(prov)
data = get_provider(prov)
matched = True
# fallback if we have only __active_provider_name__
if (
(__opts__.get('destroy', False) and not data) or (
not matched and __active_provider_name__
)
):
data = __opts__.get('providers',
{}).get(dalias, {}).get(driver, {})
# in all cases, verify that the linked saltmaster is alive.
if data:
ret = _salt('test.ping', salt_target=data['target'])
if ret:
return data
else:
log.error(
'Configured provider %s minion: %s is unreachable',
__active_provider_name__, data['target']
)
return False
|
saltstack/salt
|
salt/cloud/clouds/lxc.py
|
create
|
python
|
def create(vm_, call=None):
'''Create an lxc Container.
This function is idempotent and will try to either provision
or finish the provision of an lxc container.
NOTE: Most of the initialization code has been moved and merged
with the lxc runner and lxc.init functions
'''
prov = get_configured_provider(vm_)
if not prov:
return
# we cant use profile as a configuration key as it conflicts
# with salt cloud internals
profile = vm_.get(
'lxc_profile',
vm_.get('container_profile', None))
event_data = vm_.copy()
event_data['profile'] = profile
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', event_data, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
ret = {'name': vm_['name'], 'changes': {}, 'result': True, 'comment': ''}
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for %s', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value(
'keysize', vm_, __opts__))
# get the minion key pair to distribute back to the container
kwarg = copy.deepcopy(vm_)
kwarg['host'] = prov['target']
kwarg['profile'] = profile
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
cret = _runner().cmd('lxc.cloud_init', [vm_['name']], kwarg=kwarg)
ret['runner_return'] = cret
ret['result'] = cret['result']
if not ret['result']:
ret['Error'] = 'Error while creating {0},'.format(vm_['name'])
else:
ret['changes']['created'] = 'created'
# When using cloud states to manage LXC containers
# __opts__['profile'] is not implicitly reset between operations
# on different containers. However list_nodes will hide container
# if profile is set in opts assuming that it have to be created.
# But in cloud state we do want to check at first if it really
# exists hence the need to remove profile from global opts once
# current container is created.
if 'profile' in __opts__:
__opts__['internal_lxc_profile'] = __opts__['profile']
del __opts__['profile']
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
|
Create an lxc Container.
This function is idempotent and will try to either provision
or finish the provision of an lxc container.
NOTE: Most of the initialization code has been moved and merged
with the lxc runner and lxc.init functions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/lxc.py#L420-L497
|
[
"def _runner():\n # opts = _master_opts()\n # opts['output'] = 'quiet'\n return salt.runner.RunnerClient(_master_opts())\n",
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def gen_keys(keysize=2048):\n '''\n Generate Salt minion keys and return them as PEM file strings\n '''\n # Mandate that keys are at least 2048 in size\n if keysize < 2048:\n keysize = 2048\n tdir = tempfile.mkdtemp()\n\n salt.crypt.gen_keys(tdir, 'minion', keysize)\n priv_path = os.path.join(tdir, 'minion.pem')\n pub_path = os.path.join(tdir, 'minion.pub')\n with salt.utils.files.fopen(priv_path) as fp_:\n priv = salt.utils.stringutils.to_unicode(fp_.read())\n with salt.utils.files.fopen(pub_path) as fp_:\n pub = salt.utils.stringutils.to_unicode(fp_.read())\n shutil.rmtree(tdir)\n return priv, pub\n",
"def get_configured_provider(vm_=None):\n '''\n Return the contextual provider of None if no configured\n one can be found.\n '''\n if vm_ is None:\n vm_ = {}\n dalias, driver = __active_provider_name__.split(':')\n data = None\n tgt = 'unknown'\n img_provider = __opts__.get('list_images', '')\n arg_providers = __opts__.get('names', [])\n matched = False\n # --list-images level\n if img_provider:\n tgt = 'provider: {0}'.format(img_provider)\n if dalias == img_provider:\n data = get_provider(img_provider)\n matched = True\n # providers are set in configuration\n if not data and 'profile' not in __opts__ and arg_providers:\n for name in arg_providers:\n tgt = 'provider: {0}'.format(name)\n if dalias == name:\n data = get_provider(name)\n if data:\n matched = True\n break\n # -p is providen, get the uplinked provider\n elif 'profile' in __opts__:\n curprof = __opts__['profile']\n profs = __opts__['profiles']\n tgt = 'profile: {0}'.format(curprof)\n if (\n curprof in profs and\n profs[curprof]['provider'] == __active_provider_name__\n ):\n prov, cdriver = profs[curprof]['provider'].split(':')\n tgt += ' provider: {0}'.format(prov)\n data = get_provider(prov)\n matched = True\n # fallback if we have only __active_provider_name__\n if (\n (__opts__.get('destroy', False) and not data) or (\n not matched and __active_provider_name__\n )\n ):\n data = __opts__.get('providers',\n {}).get(dalias, {}).get(driver, {})\n # in all cases, verify that the linked saltmaster is alive.\n if data:\n ret = _salt('test.ping', salt_target=data['target'])\n if ret:\n return data\n else:\n log.error(\n 'Configured provider %s minion: %s is unreachable',\n __active_provider_name__, data['target']\n )\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Install Salt on an LXC Container
================================
.. versionadded:: 2014.7.0
Please read :ref:`core config documentation <config_lxc>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import os
import pprint
import time
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.client
import salt.runner
# Import 3rd-party libs
from salt.ext import six
# Get logging started
log = logging.getLogger(__name__)
__FUN_TIMEOUT = {
'cmd.run': 60 * 60,
'test.ping': 10,
'lxc.info': 40,
'lxc.list': 300,
'lxc.templates': 100,
'grains.items': 100,
}
__CACHED_CALLS = {}
__CACHED_FUNS = {
'test.ping': 3 * 60, # cache ping for 3 minutes
'lxc.list': 2 # cache lxc.list for 2 seconds
}
def __virtual__():
'''
Needs no special configuration
'''
return True
def _get_grain_id(id_):
if not get_configured_provider():
return
infos = get_configured_provider()
return 'salt.cloud.lxc.{0}.{1}'.format(infos['target'], id_)
def _minion_opts(cfg='minion'):
if 'conf_file' in __opts__:
default_dir = os.path.dirname(__opts__['conf_file'])
else:
default_dir = __opts__['config_dir'],
cfg = os.environ.get(
'SALT_MINION_CONFIG', os.path.join(default_dir, cfg))
opts = config.minion_config(cfg)
return opts
def _master_opts(cfg='master'):
if 'conf_file' in __opts__:
default_dir = os.path.dirname(__opts__['conf_file'])
else:
default_dir = __opts__['config_dir'],
cfg = os.environ.get(
'SALT_MASTER_CONFIG', os.path.join(default_dir, cfg))
opts = config.master_config(cfg)
opts['output'] = 'quiet'
return opts
def _client():
return salt.client.get_local_client(mopts=_master_opts())
def _runner():
# opts = _master_opts()
# opts['output'] = 'quiet'
return salt.runner.RunnerClient(_master_opts())
def _salt(fun, *args, **kw):
'''Execute a salt function on a specific minion
Special kwargs:
salt_target
target to exec things on
salt_timeout
timeout for jobs
salt_job_poll
poll interval to wait for job finish result
'''
try:
poll = kw.pop('salt_job_poll')
except KeyError:
poll = 0.1
try:
target = kw.pop('salt_target')
except KeyError:
target = None
try:
timeout = int(kw.pop('salt_timeout'))
except (KeyError, ValueError):
# try to has some low timeouts for very basic commands
timeout = __FUN_TIMEOUT.get(
fun,
900 # wait up to 15 minutes for the default timeout
)
try:
kwargs = kw.pop('kwargs')
except KeyError:
kwargs = {}
if not target:
infos = get_configured_provider()
if not infos:
return
target = infos['target']
laps = time.time()
cache = False
if fun in __CACHED_FUNS:
cache = True
laps = laps // __CACHED_FUNS[fun]
try:
sargs = salt.utils.json.dumps(args)
except TypeError:
sargs = ''
try:
skw = salt.utils.json.dumps(kw)
except TypeError:
skw = ''
try:
skwargs = salt.utils.json.dumps(kwargs)
except TypeError:
skwargs = ''
cache_key = (laps, target, fun, sargs, skw, skwargs)
if not cache or (cache and (cache_key not in __CACHED_CALLS)):
conn = _client()
runner = _runner()
rkwargs = kwargs.copy()
rkwargs['timeout'] = timeout
rkwargs.setdefault('tgt_type', 'list')
kwargs.setdefault('tgt_type', 'list')
ping_retries = 0
# the target(s) have environ one minute to respond
# we call 60 ping request, this prevent us
# from blindly send commands to unmatched minions
ping_max_retries = 60
ping = True
# do not check ping... if we are pinguing
if fun == 'test.ping':
ping_retries = ping_max_retries + 1
# be sure that the executors are alive
while ping_retries <= ping_max_retries:
try:
if ping_retries > 0:
time.sleep(1)
pings = conn.cmd(tgt=target,
timeout=10,
fun='test.ping')
values = list(pings.values())
if not values:
ping = False
for v in values:
if v is not True:
ping = False
if not ping:
raise ValueError('Unreachable')
break
except Exception:
ping = False
ping_retries += 1
log.error('%s unreachable, retrying', target)
if not ping:
raise SaltCloudSystemExit('Target {0} unreachable'.format(target))
jid = conn.cmd_async(tgt=target,
fun=fun,
arg=args,
kwarg=kw,
**rkwargs)
cret = conn.cmd(tgt=target,
fun='saltutil.find_job',
arg=[jid],
timeout=10,
**kwargs)
running = bool(cret.get(target, False))
endto = time.time() + timeout
while running:
rkwargs = {
'tgt': target,
'fun': 'saltutil.find_job',
'arg': [jid],
'timeout': 10
}
cret = conn.cmd(**rkwargs)
running = bool(cret.get(target, False))
if not running:
break
if running and (time.time() > endto):
raise Exception('Timeout {0}s for {1} is elapsed'.format(
timeout, pprint.pformat(rkwargs)))
time.sleep(poll)
# timeout for the master to return data about a specific job
wait_for_res = float({
'test.ping': '5',
}.get(fun, '120'))
while wait_for_res:
wait_for_res -= 0.5
cret = runner.cmd(
'jobs.lookup_jid',
[jid, {'__kwarg__': True}])
if target in cret:
ret = cret[target]
break
# recent changes
elif 'data' in cret and 'outputter' in cret:
ret = cret['data']
break
# special case, some answers may be crafted
# to handle the unresponsivness of a specific command
# which is also meaningful, e.g. a minion not yet provisioned
if fun in ['test.ping'] and not wait_for_res:
ret = {
'test.ping': False,
}.get(fun, False)
time.sleep(0.5)
try:
if 'is not available.' in ret:
raise SaltCloudSystemExit(
'module/function {0} is not available'.format(fun))
except SaltCloudSystemExit:
raise
except TypeError:
pass
if cache:
__CACHED_CALLS[cache_key] = ret
elif cache and cache_key in __CACHED_CALLS:
ret = __CACHED_CALLS[cache_key]
return ret
def avail_images():
return _salt('lxc.templates')
def list_nodes(conn=None, call=None):
hide = False
names = __opts__.get('names', [])
profiles = __opts__.get('profiles', {})
profile = __opts__.get('profile',
__opts__.get('internal_lxc_profile', []))
destroy_opt = __opts__.get('destroy', False)
action = __opts__.get('action', '')
for opt in ['full_query', 'select_query', 'query']:
if __opts__.get(opt, False):
call = 'full'
if destroy_opt:
call = 'full'
if action and not call:
call = 'action'
if profile and names and not destroy_opt:
hide = True
if not get_configured_provider():
return
path = None
if profile and profile in profiles:
path = profiles[profile].get('path', None)
lxclist = _salt('lxc.list', extra=True, path=path)
nodes = {}
for state, lxcs in six.iteritems(lxclist):
for lxcc, linfos in six.iteritems(lxcs):
info = {
'id': lxcc,
'name': lxcc, # required for cloud cache
'image': None,
'size': linfos['size'],
'state': state.lower(),
'public_ips': linfos['public_ips'],
'private_ips': linfos['private_ips'],
}
# in creation mode, we need to go inside the create method
# so we hide the running vm from being seen as already installed
# do not also mask half configured nodes which are explicitly asked
# to be acted on, on the command line
if (call in ['full'] or not hide) and ((lxcc in names and call in ['action']) or call in ['full']):
nodes[lxcc] = {
'id': lxcc,
'name': lxcc, # required for cloud cache
'image': None,
'size': linfos['size'],
'state': state.lower(),
'public_ips': linfos['public_ips'],
'private_ips': linfos['private_ips'],
}
else:
nodes[lxcc] = {'id': lxcc, 'state': state.lower()}
return nodes
def list_nodes_full(conn=None, call=None):
if not get_configured_provider():
return
if not call:
call = 'action'
return list_nodes(conn=conn, call=call)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if not get_configured_provider():
return
if not call:
call = 'action'
nodes = list_nodes_full(call=call)
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not call:
call = 'select'
if not get_configured_provider():
return
info = ['id', 'name', 'image', 'size', 'state', 'public_ips', 'private_ips']
return salt.utils.cloud.list_nodes_select(
list_nodes_full(call='action'),
__opts__.get('query.selection', info), call)
def _checkpoint(ret):
sret = '''
id: {name}
last message: {comment}'''.format(**ret)
keys = list(ret['changes'].items())
keys.sort()
for ch, comment in keys:
sret += (
'\n'
' {0}:\n'
' {1}'
).format(ch, comment.replace(
'\n',
'\n'
' '))
if not ret['result']:
if 'changes' in ret:
del ret['changes']
raise SaltCloudSystemExit(sret)
log.info(sret)
return sret
def destroy(vm_, call=None):
'''Destroy a lxc container'''
destroy_opt = __opts__.get('destroy', False)
profiles = __opts__.get('profiles', {})
profile = __opts__.get('profile',
__opts__.get('internal_lxc_profile', []))
path = None
if profile and profile in profiles:
path = profiles[profile].get('path', None)
action = __opts__.get('action', '')
if action != 'destroy' and not destroy_opt:
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not get_configured_provider():
return
ret = {'comment': '{0} was not found'.format(vm_),
'result': False}
if _salt('lxc.info', vm_, path=path):
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(vm_),
args={'name': vm_, 'instance_id': vm_},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
cret = _salt('lxc.destroy', vm_, stop=True, path=path)
ret['result'] = cret['result']
if ret['result']:
ret['comment'] = '{0} was destroyed'.format(vm_)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(vm_),
args={'name': vm_, 'instance_id': vm_},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](vm_, __active_provider_name__.split(':')[0], __opts__)
return ret
def get_provider(name):
data = None
if name in __opts__['providers']:
data = __opts__['providers'][name]
if 'lxc' in data:
data = data['lxc']
else:
data = None
return data
def get_configured_provider(vm_=None):
'''
Return the contextual provider of None if no configured
one can be found.
'''
if vm_ is None:
vm_ = {}
dalias, driver = __active_provider_name__.split(':')
data = None
tgt = 'unknown'
img_provider = __opts__.get('list_images', '')
arg_providers = __opts__.get('names', [])
matched = False
# --list-images level
if img_provider:
tgt = 'provider: {0}'.format(img_provider)
if dalias == img_provider:
data = get_provider(img_provider)
matched = True
# providers are set in configuration
if not data and 'profile' not in __opts__ and arg_providers:
for name in arg_providers:
tgt = 'provider: {0}'.format(name)
if dalias == name:
data = get_provider(name)
if data:
matched = True
break
# -p is providen, get the uplinked provider
elif 'profile' in __opts__:
curprof = __opts__['profile']
profs = __opts__['profiles']
tgt = 'profile: {0}'.format(curprof)
if (
curprof in profs and
profs[curprof]['provider'] == __active_provider_name__
):
prov, cdriver = profs[curprof]['provider'].split(':')
tgt += ' provider: {0}'.format(prov)
data = get_provider(prov)
matched = True
# fallback if we have only __active_provider_name__
if (
(__opts__.get('destroy', False) and not data) or (
not matched and __active_provider_name__
)
):
data = __opts__.get('providers',
{}).get(dalias, {}).get(driver, {})
# in all cases, verify that the linked saltmaster is alive.
if data:
ret = _salt('test.ping', salt_target=data['target'])
if ret:
return data
else:
log.error(
'Configured provider %s minion: %s is unreachable',
__active_provider_name__, data['target']
)
return False
|
saltstack/salt
|
salt/cloud/clouds/lxc.py
|
get_configured_provider
|
python
|
def get_configured_provider(vm_=None):
'''
Return the contextual provider of None if no configured
one can be found.
'''
if vm_ is None:
vm_ = {}
dalias, driver = __active_provider_name__.split(':')
data = None
tgt = 'unknown'
img_provider = __opts__.get('list_images', '')
arg_providers = __opts__.get('names', [])
matched = False
# --list-images level
if img_provider:
tgt = 'provider: {0}'.format(img_provider)
if dalias == img_provider:
data = get_provider(img_provider)
matched = True
# providers are set in configuration
if not data and 'profile' not in __opts__ and arg_providers:
for name in arg_providers:
tgt = 'provider: {0}'.format(name)
if dalias == name:
data = get_provider(name)
if data:
matched = True
break
# -p is providen, get the uplinked provider
elif 'profile' in __opts__:
curprof = __opts__['profile']
profs = __opts__['profiles']
tgt = 'profile: {0}'.format(curprof)
if (
curprof in profs and
profs[curprof]['provider'] == __active_provider_name__
):
prov, cdriver = profs[curprof]['provider'].split(':')
tgt += ' provider: {0}'.format(prov)
data = get_provider(prov)
matched = True
# fallback if we have only __active_provider_name__
if (
(__opts__.get('destroy', False) and not data) or (
not matched and __active_provider_name__
)
):
data = __opts__.get('providers',
{}).get(dalias, {}).get(driver, {})
# in all cases, verify that the linked saltmaster is alive.
if data:
ret = _salt('test.ping', salt_target=data['target'])
if ret:
return data
else:
log.error(
'Configured provider %s minion: %s is unreachable',
__active_provider_name__, data['target']
)
return False
|
Return the contextual provider of None if no configured
one can be found.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/lxc.py#L511-L570
|
[
"def get_provider(name):\n data = None\n if name in __opts__['providers']:\n data = __opts__['providers'][name]\n if 'lxc' in data:\n data = data['lxc']\n else:\n data = None\n return data\n",
"def _salt(fun, *args, **kw):\n '''Execute a salt function on a specific minion\n\n Special kwargs:\n\n salt_target\n target to exec things on\n salt_timeout\n timeout for jobs\n salt_job_poll\n poll interval to wait for job finish result\n '''\n try:\n poll = kw.pop('salt_job_poll')\n except KeyError:\n poll = 0.1\n try:\n target = kw.pop('salt_target')\n except KeyError:\n target = None\n try:\n timeout = int(kw.pop('salt_timeout'))\n except (KeyError, ValueError):\n # try to has some low timeouts for very basic commands\n timeout = __FUN_TIMEOUT.get(\n fun,\n 900 # wait up to 15 minutes for the default timeout\n )\n try:\n kwargs = kw.pop('kwargs')\n except KeyError:\n kwargs = {}\n if not target:\n infos = get_configured_provider()\n if not infos:\n return\n target = infos['target']\n laps = time.time()\n cache = False\n if fun in __CACHED_FUNS:\n cache = True\n laps = laps // __CACHED_FUNS[fun]\n try:\n sargs = salt.utils.json.dumps(args)\n except TypeError:\n sargs = ''\n try:\n skw = salt.utils.json.dumps(kw)\n except TypeError:\n skw = ''\n try:\n skwargs = salt.utils.json.dumps(kwargs)\n except TypeError:\n skwargs = ''\n cache_key = (laps, target, fun, sargs, skw, skwargs)\n if not cache or (cache and (cache_key not in __CACHED_CALLS)):\n conn = _client()\n runner = _runner()\n rkwargs = kwargs.copy()\n rkwargs['timeout'] = timeout\n rkwargs.setdefault('tgt_type', 'list')\n kwargs.setdefault('tgt_type', 'list')\n ping_retries = 0\n # the target(s) have environ one minute to respond\n # we call 60 ping request, this prevent us\n # from blindly send commands to unmatched minions\n ping_max_retries = 60\n ping = True\n # do not check ping... if we are pinguing\n if fun == 'test.ping':\n ping_retries = ping_max_retries + 1\n # be sure that the executors are alive\n while ping_retries <= ping_max_retries:\n try:\n if ping_retries > 0:\n time.sleep(1)\n pings = conn.cmd(tgt=target,\n timeout=10,\n fun='test.ping')\n values = list(pings.values())\n if not values:\n ping = False\n for v in values:\n if v is not True:\n ping = False\n if not ping:\n raise ValueError('Unreachable')\n break\n except Exception:\n ping = False\n ping_retries += 1\n log.error('%s unreachable, retrying', target)\n if not ping:\n raise SaltCloudSystemExit('Target {0} unreachable'.format(target))\n jid = conn.cmd_async(tgt=target,\n fun=fun,\n arg=args,\n kwarg=kw,\n **rkwargs)\n cret = conn.cmd(tgt=target,\n fun='saltutil.find_job',\n arg=[jid],\n timeout=10,\n **kwargs)\n running = bool(cret.get(target, False))\n endto = time.time() + timeout\n while running:\n rkwargs = {\n 'tgt': target,\n 'fun': 'saltutil.find_job',\n 'arg': [jid],\n 'timeout': 10\n }\n cret = conn.cmd(**rkwargs)\n running = bool(cret.get(target, False))\n if not running:\n break\n if running and (time.time() > endto):\n raise Exception('Timeout {0}s for {1} is elapsed'.format(\n timeout, pprint.pformat(rkwargs)))\n time.sleep(poll)\n # timeout for the master to return data about a specific job\n wait_for_res = float({\n 'test.ping': '5',\n }.get(fun, '120'))\n while wait_for_res:\n wait_for_res -= 0.5\n cret = runner.cmd(\n 'jobs.lookup_jid',\n [jid, {'__kwarg__': True}])\n if target in cret:\n ret = cret[target]\n break\n # recent changes\n elif 'data' in cret and 'outputter' in cret:\n ret = cret['data']\n break\n # special case, some answers may be crafted\n # to handle the unresponsivness of a specific command\n # which is also meaningful, e.g. a minion not yet provisioned\n if fun in ['test.ping'] and not wait_for_res:\n ret = {\n 'test.ping': False,\n }.get(fun, False)\n time.sleep(0.5)\n try:\n if 'is not available.' in ret:\n raise SaltCloudSystemExit(\n 'module/function {0} is not available'.format(fun))\n except SaltCloudSystemExit:\n raise\n except TypeError:\n pass\n if cache:\n __CACHED_CALLS[cache_key] = ret\n elif cache and cache_key in __CACHED_CALLS:\n ret = __CACHED_CALLS[cache_key]\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Install Salt on an LXC Container
================================
.. versionadded:: 2014.7.0
Please read :ref:`core config documentation <config_lxc>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import os
import pprint
import time
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.client
import salt.runner
# Import 3rd-party libs
from salt.ext import six
# Get logging started
log = logging.getLogger(__name__)
__FUN_TIMEOUT = {
'cmd.run': 60 * 60,
'test.ping': 10,
'lxc.info': 40,
'lxc.list': 300,
'lxc.templates': 100,
'grains.items': 100,
}
__CACHED_CALLS = {}
__CACHED_FUNS = {
'test.ping': 3 * 60, # cache ping for 3 minutes
'lxc.list': 2 # cache lxc.list for 2 seconds
}
def __virtual__():
'''
Needs no special configuration
'''
return True
def _get_grain_id(id_):
if not get_configured_provider():
return
infos = get_configured_provider()
return 'salt.cloud.lxc.{0}.{1}'.format(infos['target'], id_)
def _minion_opts(cfg='minion'):
if 'conf_file' in __opts__:
default_dir = os.path.dirname(__opts__['conf_file'])
else:
default_dir = __opts__['config_dir'],
cfg = os.environ.get(
'SALT_MINION_CONFIG', os.path.join(default_dir, cfg))
opts = config.minion_config(cfg)
return opts
def _master_opts(cfg='master'):
if 'conf_file' in __opts__:
default_dir = os.path.dirname(__opts__['conf_file'])
else:
default_dir = __opts__['config_dir'],
cfg = os.environ.get(
'SALT_MASTER_CONFIG', os.path.join(default_dir, cfg))
opts = config.master_config(cfg)
opts['output'] = 'quiet'
return opts
def _client():
return salt.client.get_local_client(mopts=_master_opts())
def _runner():
# opts = _master_opts()
# opts['output'] = 'quiet'
return salt.runner.RunnerClient(_master_opts())
def _salt(fun, *args, **kw):
'''Execute a salt function on a specific minion
Special kwargs:
salt_target
target to exec things on
salt_timeout
timeout for jobs
salt_job_poll
poll interval to wait for job finish result
'''
try:
poll = kw.pop('salt_job_poll')
except KeyError:
poll = 0.1
try:
target = kw.pop('salt_target')
except KeyError:
target = None
try:
timeout = int(kw.pop('salt_timeout'))
except (KeyError, ValueError):
# try to has some low timeouts for very basic commands
timeout = __FUN_TIMEOUT.get(
fun,
900 # wait up to 15 minutes for the default timeout
)
try:
kwargs = kw.pop('kwargs')
except KeyError:
kwargs = {}
if not target:
infos = get_configured_provider()
if not infos:
return
target = infos['target']
laps = time.time()
cache = False
if fun in __CACHED_FUNS:
cache = True
laps = laps // __CACHED_FUNS[fun]
try:
sargs = salt.utils.json.dumps(args)
except TypeError:
sargs = ''
try:
skw = salt.utils.json.dumps(kw)
except TypeError:
skw = ''
try:
skwargs = salt.utils.json.dumps(kwargs)
except TypeError:
skwargs = ''
cache_key = (laps, target, fun, sargs, skw, skwargs)
if not cache or (cache and (cache_key not in __CACHED_CALLS)):
conn = _client()
runner = _runner()
rkwargs = kwargs.copy()
rkwargs['timeout'] = timeout
rkwargs.setdefault('tgt_type', 'list')
kwargs.setdefault('tgt_type', 'list')
ping_retries = 0
# the target(s) have environ one minute to respond
# we call 60 ping request, this prevent us
# from blindly send commands to unmatched minions
ping_max_retries = 60
ping = True
# do not check ping... if we are pinguing
if fun == 'test.ping':
ping_retries = ping_max_retries + 1
# be sure that the executors are alive
while ping_retries <= ping_max_retries:
try:
if ping_retries > 0:
time.sleep(1)
pings = conn.cmd(tgt=target,
timeout=10,
fun='test.ping')
values = list(pings.values())
if not values:
ping = False
for v in values:
if v is not True:
ping = False
if not ping:
raise ValueError('Unreachable')
break
except Exception:
ping = False
ping_retries += 1
log.error('%s unreachable, retrying', target)
if not ping:
raise SaltCloudSystemExit('Target {0} unreachable'.format(target))
jid = conn.cmd_async(tgt=target,
fun=fun,
arg=args,
kwarg=kw,
**rkwargs)
cret = conn.cmd(tgt=target,
fun='saltutil.find_job',
arg=[jid],
timeout=10,
**kwargs)
running = bool(cret.get(target, False))
endto = time.time() + timeout
while running:
rkwargs = {
'tgt': target,
'fun': 'saltutil.find_job',
'arg': [jid],
'timeout': 10
}
cret = conn.cmd(**rkwargs)
running = bool(cret.get(target, False))
if not running:
break
if running and (time.time() > endto):
raise Exception('Timeout {0}s for {1} is elapsed'.format(
timeout, pprint.pformat(rkwargs)))
time.sleep(poll)
# timeout for the master to return data about a specific job
wait_for_res = float({
'test.ping': '5',
}.get(fun, '120'))
while wait_for_res:
wait_for_res -= 0.5
cret = runner.cmd(
'jobs.lookup_jid',
[jid, {'__kwarg__': True}])
if target in cret:
ret = cret[target]
break
# recent changes
elif 'data' in cret and 'outputter' in cret:
ret = cret['data']
break
# special case, some answers may be crafted
# to handle the unresponsivness of a specific command
# which is also meaningful, e.g. a minion not yet provisioned
if fun in ['test.ping'] and not wait_for_res:
ret = {
'test.ping': False,
}.get(fun, False)
time.sleep(0.5)
try:
if 'is not available.' in ret:
raise SaltCloudSystemExit(
'module/function {0} is not available'.format(fun))
except SaltCloudSystemExit:
raise
except TypeError:
pass
if cache:
__CACHED_CALLS[cache_key] = ret
elif cache and cache_key in __CACHED_CALLS:
ret = __CACHED_CALLS[cache_key]
return ret
def avail_images():
return _salt('lxc.templates')
def list_nodes(conn=None, call=None):
hide = False
names = __opts__.get('names', [])
profiles = __opts__.get('profiles', {})
profile = __opts__.get('profile',
__opts__.get('internal_lxc_profile', []))
destroy_opt = __opts__.get('destroy', False)
action = __opts__.get('action', '')
for opt in ['full_query', 'select_query', 'query']:
if __opts__.get(opt, False):
call = 'full'
if destroy_opt:
call = 'full'
if action and not call:
call = 'action'
if profile and names and not destroy_opt:
hide = True
if not get_configured_provider():
return
path = None
if profile and profile in profiles:
path = profiles[profile].get('path', None)
lxclist = _salt('lxc.list', extra=True, path=path)
nodes = {}
for state, lxcs in six.iteritems(lxclist):
for lxcc, linfos in six.iteritems(lxcs):
info = {
'id': lxcc,
'name': lxcc, # required for cloud cache
'image': None,
'size': linfos['size'],
'state': state.lower(),
'public_ips': linfos['public_ips'],
'private_ips': linfos['private_ips'],
}
# in creation mode, we need to go inside the create method
# so we hide the running vm from being seen as already installed
# do not also mask half configured nodes which are explicitly asked
# to be acted on, on the command line
if (call in ['full'] or not hide) and ((lxcc in names and call in ['action']) or call in ['full']):
nodes[lxcc] = {
'id': lxcc,
'name': lxcc, # required for cloud cache
'image': None,
'size': linfos['size'],
'state': state.lower(),
'public_ips': linfos['public_ips'],
'private_ips': linfos['private_ips'],
}
else:
nodes[lxcc] = {'id': lxcc, 'state': state.lower()}
return nodes
def list_nodes_full(conn=None, call=None):
if not get_configured_provider():
return
if not call:
call = 'action'
return list_nodes(conn=conn, call=call)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if not get_configured_provider():
return
if not call:
call = 'action'
nodes = list_nodes_full(call=call)
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not call:
call = 'select'
if not get_configured_provider():
return
info = ['id', 'name', 'image', 'size', 'state', 'public_ips', 'private_ips']
return salt.utils.cloud.list_nodes_select(
list_nodes_full(call='action'),
__opts__.get('query.selection', info), call)
def _checkpoint(ret):
sret = '''
id: {name}
last message: {comment}'''.format(**ret)
keys = list(ret['changes'].items())
keys.sort()
for ch, comment in keys:
sret += (
'\n'
' {0}:\n'
' {1}'
).format(ch, comment.replace(
'\n',
'\n'
' '))
if not ret['result']:
if 'changes' in ret:
del ret['changes']
raise SaltCloudSystemExit(sret)
log.info(sret)
return sret
def destroy(vm_, call=None):
'''Destroy a lxc container'''
destroy_opt = __opts__.get('destroy', False)
profiles = __opts__.get('profiles', {})
profile = __opts__.get('profile',
__opts__.get('internal_lxc_profile', []))
path = None
if profile and profile in profiles:
path = profiles[profile].get('path', None)
action = __opts__.get('action', '')
if action != 'destroy' and not destroy_opt:
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not get_configured_provider():
return
ret = {'comment': '{0} was not found'.format(vm_),
'result': False}
if _salt('lxc.info', vm_, path=path):
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(vm_),
args={'name': vm_, 'instance_id': vm_},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
cret = _salt('lxc.destroy', vm_, stop=True, path=path)
ret['result'] = cret['result']
if ret['result']:
ret['comment'] = '{0} was destroyed'.format(vm_)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(vm_),
args={'name': vm_, 'instance_id': vm_},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](vm_, __active_provider_name__.split(':')[0], __opts__)
return ret
def create(vm_, call=None):
'''Create an lxc Container.
This function is idempotent and will try to either provision
or finish the provision of an lxc container.
NOTE: Most of the initialization code has been moved and merged
with the lxc runner and lxc.init functions
'''
prov = get_configured_provider(vm_)
if not prov:
return
# we cant use profile as a configuration key as it conflicts
# with salt cloud internals
profile = vm_.get(
'lxc_profile',
vm_.get('container_profile', None))
event_data = vm_.copy()
event_data['profile'] = profile
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', event_data, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
ret = {'name': vm_['name'], 'changes': {}, 'result': True, 'comment': ''}
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for %s', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value(
'keysize', vm_, __opts__))
# get the minion key pair to distribute back to the container
kwarg = copy.deepcopy(vm_)
kwarg['host'] = prov['target']
kwarg['profile'] = profile
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
cret = _runner().cmd('lxc.cloud_init', [vm_['name']], kwarg=kwarg)
ret['runner_return'] = cret
ret['result'] = cret['result']
if not ret['result']:
ret['Error'] = 'Error while creating {0},'.format(vm_['name'])
else:
ret['changes']['created'] = 'created'
# When using cloud states to manage LXC containers
# __opts__['profile'] is not implicitly reset between operations
# on different containers. However list_nodes will hide container
# if profile is set in opts assuming that it have to be created.
# But in cloud state we do want to check at first if it really
# exists hence the need to remove profile from global opts once
# current container is created.
if 'profile' in __opts__:
__opts__['internal_lxc_profile'] = __opts__['profile']
del __opts__['profile']
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def get_provider(name):
data = None
if name in __opts__['providers']:
data = __opts__['providers'][name]
if 'lxc' in data:
data = data['lxc']
else:
data = None
return data
|
saltstack/salt
|
salt/runners/launchd.py
|
write_launchd_plist
|
python
|
def write_launchd_plist(program):
'''
Write a launchd plist for managing salt-master or salt-minion
CLI Example:
.. code-block:: bash
salt-run launchd.write_launchd_plist salt-master
'''
plist_sample_text = '''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>org.saltstack.{program}</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>ProgramArguments</key>
<array>
<string>{script}</string>
</array>
<key>SoftResourceLimits</key>
<dict>
<key>NumberOfFiles</key>
<integer>100000</integer>
</dict>
<key>HardResourceLimits</key>
<dict>
<key>NumberOfFiles</key>
<integer>100000</integer>
</dict>
</dict>
</plist>
'''.strip()
supported_programs = ['salt-master', 'salt-minion']
if program not in supported_programs:
sys.stderr.write(
'Supported programs: \'{0}\'\n'.format(supported_programs)
)
sys.exit(-1)
return plist_sample_text.format(
program=program,
python=sys.executable,
script=os.path.join(os.path.dirname(sys.executable), program)
)
|
Write a launchd plist for managing salt-master or salt-minion
CLI Example:
.. code-block:: bash
salt-run launchd.write_launchd_plist salt-master
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/launchd.py#L12-L63
| null |
# -*- coding: utf-8 -*-
'''
Manage launchd plist files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import sys
|
saltstack/salt
|
salt/grains/core.py
|
_windows_cpudata
|
python
|
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
|
Return some CPU information on Windows minions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L110-L129
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_linux_cpudata
|
python
|
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
|
Return some CPU information for Linux minions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L132-L183
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_linux_gpu_data
|
python
|
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
|
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L186-L259
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_netbsd_gpu_data
|
python
|
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
|
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L262-L290
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_osx_gpudata
|
python
|
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
|
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L293-L318
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_bsd_cpudata
|
python
|
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
|
Return CPU information for BSD-like systems
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L321-L384
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_sunos_cpudata
|
python
|
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
|
Return the CPU information for Solaris-like systems
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L387-L414
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_aix_cpudata
|
python
|
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
|
Return CPU information for AIX systems
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L417-L440
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_linux_memdata
|
python
|
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
|
Return the memory information for Linux-like systems
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L443-L462
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n"
] |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_osx_memdata
|
python
|
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
|
Return the memory information for BSD-like systems
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L465-L485
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_bsd_memdata
|
python
|
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
|
Return the memory information for BSD-like systems
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L488-L511
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_sunos_memdata
|
python
|
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
|
Return the memory information for SunOS-like systems
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L514-L535
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_aix_memdata
|
python
|
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
|
Return the memory information for AIX systems
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L538-L563
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_memdata
|
python
|
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
|
Gather information about the system memory
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L578-L598
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_aix_get_machine_id
|
python
|
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
|
Parse the output of lsattr -El sys0 for os_uuid
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L601-L617
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_windows_virtual
|
python
|
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
|
Returns what type of virtual hardware is under the hood, kvm or physical
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L620-L674
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_virtual
|
python
|
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
|
Returns what type of virtual hardware is under the hood, kvm or physical
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L677-L1068
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_virtual_hv
|
python
|
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
|
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L1071-L1125
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_ps
|
python
|
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
|
Return the ps grain
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L1128-L1152
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_clean_value
|
python
|
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
|
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L1155-L1197
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_windows_platform_data
|
python
|
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
|
Use the platform module for as much as we can.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L1200-L1319
|
[
"def _clean_value(key, val):\n '''\n Clean out well-known bogus values.\n If it isn't clean (for example has value 'None'), return None.\n Otherwise, return the original value.\n\n NOTE: This logic also exists in the smbios module. This function is\n for use when not using smbios to retrieve the value.\n '''\n if (val is None or not val or\n re.match('none', val, flags=re.IGNORECASE)):\n return None\n elif 'uuid' in key:\n # Try each version (1-5) of RFC4122 to check if it's actually a UUID\n for uuidver in range(1, 5):\n try:\n uuid.UUID(val, version=uuidver)\n return val\n except ValueError:\n continue\n log.trace('HW %s value %s is an invalid UUID', key, val.replace('\\n', ' '))\n return None\n elif re.search('serial|part|version', key):\n # 'To be filled by O.E.M.\n # 'Not applicable' etc.\n # 'Not specified' etc.\n # 0000000, 1234567 etc.\n # begone!\n if (re.match(r'^[0]+$', val) or\n re.match(r'[0]?1234567[8]?[9]?[0]?', val) or\n re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):\n return None\n elif re.search('asset|manufacturer', key):\n # AssetTag0. Manufacturer04. Begone.\n if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):\n return None\n else:\n # map unspecified, undefined, unknown & whatever to None\n if (re.search(r'to be filled', val, flags=re.IGNORECASE) or\n re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',\n val, flags=re.IGNORECASE)):\n return None\n return val\n",
"def get_os_version_info():\n info = os_version_info_ex()\n ret = {'MajorVersion': info.dwMajorVersion,\n 'MinorVersion': info.dwMinorVersion,\n 'BuildNumber': info.dwBuildNumber,\n 'PlatformID': info.dwPlatformId,\n 'ServicePackMajor': info.wServicePackMajor,\n 'ServicePackMinor': info.wServicePackMinor,\n 'SuiteMask': info.wSuiteMask,\n 'ProductType': info.wProductType}\n\n return ret\n",
"def get_join_info():\n '''\n Gets information about the domain/workgroup. This will tell you if the\n system is joined to a domain or a workgroup\n\n .. version-added:: 2018.3.4\n\n Returns:\n dict: A dictionary containing the domain/workgroup and it's status\n '''\n info = win32net.NetGetJoinInformation()\n status = {win32netcon.NetSetupUnknown: 'Unknown',\n win32netcon.NetSetupUnjoined: 'Unjoined',\n win32netcon.NetSetupWorkgroupName: 'Workgroup',\n win32netcon.NetSetupDomainName: 'Domain'}\n return {'Domain': info[0],\n 'DomainType': status[info[1]]}\n"
] |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_osx_platform_data
|
python
|
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
|
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L1322-L1350
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_linux_bin_exists
|
python
|
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
|
Does a binary exist in linux (depends on which, type, or whereis)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L1483-L1500
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_parse_os_release
|
python
|
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
|
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L1532-L1556
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n"
] |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
_parse_cpe_name
|
python
|
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
|
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L1559-L1584
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
os_data
|
python
|
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
|
Return grains pertaining to the operating system
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L1587-L2084
|
[
"def _memdata(osdata):\n '''\n Gather information about the system memory\n '''\n # Provides:\n # mem_total\n # swap_total, for supported systems.\n grains = {'mem_total': 0}\n if osdata['kernel'] == 'Linux':\n grains.update(_linux_memdata())\n elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):\n grains.update(_bsd_memdata(osdata))\n elif osdata['kernel'] == 'Darwin':\n grains.update(_osx_memdata())\n elif osdata['kernel'] == 'SunOS':\n grains.update(_sunos_memdata())\n elif osdata['kernel'] == 'AIX':\n grains.update(_aix_memdata())\n elif osdata['kernel'] == 'Windows' and HAS_WMI:\n grains.update(_windows_memdata())\n return grains\n",
"def _netbsd_gpu_data():\n '''\n num_gpus: int\n gpus:\n - vendor: nvidia|amd|ati|...\n model: string\n '''\n known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']\n\n gpus = []\n try:\n pcictl_out = __salt__['cmd.run']('pcictl pci0 list')\n\n for line in pcictl_out.splitlines():\n for vendor in known_vendors:\n vendor_match = re.match(\n r'[0-9:]+ ({0}) (.+) \\(VGA .+\\)'.format(vendor),\n line,\n re.IGNORECASE\n )\n if vendor_match:\n gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})\n except OSError:\n pass\n\n grains = {}\n grains['num_gpus'] = len(gpus)\n grains['gpus'] = gpus\n return grains\n",
"def _bsd_cpudata(osdata):\n '''\n Return CPU information for BSD-like systems\n '''\n # Provides:\n # cpuarch\n # num_cpus\n # cpu_model\n # cpu_flags\n sysctl = salt.utils.path.which('sysctl')\n arch = salt.utils.path.which('arch')\n cmds = {}\n\n if sysctl:\n cmds.update({\n 'num_cpus': '{0} -n hw.ncpu'.format(sysctl),\n 'cpuarch': '{0} -n hw.machine'.format(sysctl),\n 'cpu_model': '{0} -n hw.model'.format(sysctl),\n })\n\n if arch and osdata['kernel'] == 'OpenBSD':\n cmds['cpuarch'] = '{0} -s'.format(arch)\n\n if osdata['kernel'] == 'Darwin':\n cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)\n cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)\n\n grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])\n\n if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):\n grains['cpu_flags'] = grains['cpu_flags'].split(' ')\n\n if osdata['kernel'] == 'NetBSD':\n grains['cpu_flags'] = []\n for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():\n cpu_match = re.match(r'cpu[0-9]:\\ features[0-9]?\\ .+<(.+)>', line)\n if cpu_match:\n flag = cpu_match.group(1).split(',')\n grains['cpu_flags'].extend(flag)\n\n if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):\n grains['cpu_flags'] = []\n # TODO: at least it needs to be tested for BSD other then FreeBSD\n with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:\n cpu_here = False\n for line in _fp:\n if line.startswith('CPU: '):\n cpu_here = True # starts CPU descr\n continue\n if cpu_here:\n if not line.startswith(' '):\n break # game over\n if 'Features' in line:\n start = line.find('<')\n end = line.find('>')\n if start > 0 and end > 0:\n flag = line[start + 1:end].split(',')\n grains['cpu_flags'].extend(flag)\n try:\n grains['num_cpus'] = int(grains['num_cpus'])\n except ValueError:\n grains['num_cpus'] = 1\n\n return grains\n",
"def _virtual(osdata):\n '''\n Returns what type of virtual hardware is under the hood, kvm or physical\n '''\n # This is going to be a monster, if you are running a vm you can test this\n # grain with please submit patches!\n # Provides:\n # virtual\n # virtual_subtype\n grains = {'virtual': 'physical'}\n\n # Skip the below loop on platforms which have none of the desired cmds\n # This is a temporary measure until we can write proper virtual hardware\n # detection.\n skip_cmds = ('AIX',)\n\n # list of commands to be executed to determine the 'virtual' grain\n _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']\n # test first for virt-what, which covers most of the desired functionality\n # on most platforms\n if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:\n if salt.utils.path.which('virt-what'):\n _cmds = ['virt-what']\n\n # Check if enable_lspci is True or False\n if __opts__.get('enable_lspci', True) is True:\n # /proc/bus/pci does not exists, lspci will fail\n if os.path.exists('/proc/bus/pci'):\n _cmds += ['lspci']\n\n # Add additional last resort commands\n if osdata['kernel'] in skip_cmds:\n _cmds = ()\n\n # Quick backout for BrandZ (Solaris LX Branded zones)\n # Don't waste time trying other commands to detect the virtual grain\n if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():\n grains['virtual'] = 'zone'\n return grains\n\n failed_commands = set()\n for command in _cmds:\n args = []\n if osdata['kernel'] == 'Darwin':\n command = 'system_profiler'\n args = ['SPDisplaysDataType']\n elif osdata['kernel'] == 'SunOS':\n virtinfo = salt.utils.path.which('virtinfo')\n if virtinfo:\n try:\n ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))\n except salt.exceptions.CommandExecutionError:\n if salt.log.is_logging_configured():\n failed_commands.add(virtinfo)\n else:\n if ret['stdout'].endswith('not supported'):\n command = 'prtdiag'\n else:\n command = 'virtinfo'\n else:\n command = 'prtdiag'\n\n cmd = salt.utils.path.which(command)\n\n if not cmd:\n continue\n\n cmd = '{0} {1}'.format(cmd, ' '.join(args))\n\n try:\n ret = __salt__['cmd.run_all'](cmd)\n\n if ret['retcode'] > 0:\n if salt.log.is_logging_configured():\n # systemd-detect-virt always returns > 0 on non-virtualized\n # systems\n # prtdiag only works in the global zone, skip if it fails\n if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:\n continue\n failed_commands.add(command)\n continue\n except salt.exceptions.CommandExecutionError:\n if salt.log.is_logging_configured():\n if salt.utils.platform.is_windows():\n continue\n failed_commands.add(command)\n continue\n\n output = ret['stdout']\n if command == \"system_profiler\":\n macoutput = output.lower()\n if '0x1ab8' in macoutput:\n grains['virtual'] = 'Parallels'\n if 'parallels' in macoutput:\n grains['virtual'] = 'Parallels'\n if 'vmware' in macoutput:\n grains['virtual'] = 'VMware'\n if '0x15ad' in macoutput:\n grains['virtual'] = 'VMware'\n if 'virtualbox' in macoutput:\n grains['virtual'] = 'VirtualBox'\n # Break out of the loop so the next log message is not issued\n break\n elif command == 'systemd-detect-virt':\n if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):\n grains['virtual'] = output\n break\n elif 'vmware' in output:\n grains['virtual'] = 'VMware'\n break\n elif 'microsoft' in output:\n grains['virtual'] = 'VirtualPC'\n break\n elif 'lxc' in output:\n grains['virtual'] = 'LXC'\n break\n elif 'systemd-nspawn' in output:\n grains['virtual'] = 'LXC'\n break\n elif command == 'virt-what':\n try:\n output = output.splitlines()[-1]\n except IndexError:\n pass\n if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):\n grains['virtual'] = output\n break\n elif 'vmware' in output:\n grains['virtual'] = 'VMware'\n break\n elif 'parallels' in output:\n grains['virtual'] = 'Parallels'\n break\n elif 'hyperv' in output:\n grains['virtual'] = 'HyperV'\n break\n elif command == 'dmidecode':\n # Product Name: VirtualBox\n if 'Vendor: QEMU' in output:\n # FIXME: Make this detect between kvm or qemu\n grains['virtual'] = 'kvm'\n if 'Manufacturer: QEMU' in output:\n grains['virtual'] = 'kvm'\n if 'Vendor: Bochs' in output:\n grains['virtual'] = 'kvm'\n if 'Manufacturer: Bochs' in output:\n grains['virtual'] = 'kvm'\n if 'BHYVE' in output:\n grains['virtual'] = 'bhyve'\n # Product Name: (oVirt) www.ovirt.org\n # Red Hat Community virtualization Project based on kvm\n elif 'Manufacturer: oVirt' in output:\n grains['virtual'] = 'kvm'\n grains['virtual_subtype'] = 'ovirt'\n # Red Hat Enterprise Virtualization\n elif 'Product Name: RHEV Hypervisor' in output:\n grains['virtual'] = 'kvm'\n grains['virtual_subtype'] = 'rhev'\n elif 'VirtualBox' in output:\n grains['virtual'] = 'VirtualBox'\n # Product Name: VMware Virtual Platform\n elif 'VMware' in output:\n grains['virtual'] = 'VMware'\n # Manufacturer: Microsoft Corporation\n # Product Name: Virtual Machine\n elif ': Microsoft' in output and 'Virtual Machine' in output:\n grains['virtual'] = 'VirtualPC'\n # Manufacturer: Parallels Software International Inc.\n elif 'Parallels Software' in output:\n grains['virtual'] = 'Parallels'\n elif 'Manufacturer: Google' in output:\n grains['virtual'] = 'kvm'\n # Proxmox KVM\n elif 'Vendor: SeaBIOS' in output:\n grains['virtual'] = 'kvm'\n # Break out of the loop, lspci parsing is not necessary\n break\n elif command == 'lspci':\n # dmidecode not available or the user does not have the necessary\n # permissions\n model = output.lower()\n if 'vmware' in model:\n grains['virtual'] = 'VMware'\n # 00:04.0 System peripheral: InnoTek Systemberatung GmbH\n # VirtualBox Guest Service\n elif 'virtualbox' in model:\n grains['virtual'] = 'VirtualBox'\n elif 'qemu' in model:\n grains['virtual'] = 'kvm'\n elif 'virtio' in model:\n grains['virtual'] = 'kvm'\n # Break out of the loop so the next log message is not issued\n break\n elif command == 'prtdiag':\n model = output.lower().split(\"\\n\")[0]\n if 'vmware' in model:\n grains['virtual'] = 'VMware'\n elif 'virtualbox' in model:\n grains['virtual'] = 'VirtualBox'\n elif 'qemu' in model:\n grains['virtual'] = 'kvm'\n elif 'joyent smartdc hvm' in model:\n grains['virtual'] = 'kvm'\n break\n elif command == 'virtinfo':\n grains['virtual'] = 'LDOM'\n break\n\n choices = ('Linux', 'HP-UX')\n isdir = os.path.isdir\n sysctl = salt.utils.path.which('sysctl')\n if osdata['kernel'] in choices:\n if os.path.isdir('/proc'):\n try:\n self_root = os.stat('/')\n init_root = os.stat('/proc/1/root/.')\n if self_root != init_root:\n grains['virtual_subtype'] = 'chroot'\n except (IOError, OSError):\n pass\n if isdir('/proc/vz'):\n if os.path.isfile('/proc/vz/version'):\n grains['virtual'] = 'openvzhn'\n elif os.path.isfile('/proc/vz/veinfo'):\n grains['virtual'] = 'openvzve'\n # a posteriori, it's expected for these to have failed:\n failed_commands.discard('lspci')\n failed_commands.discard('dmidecode')\n # Provide additional detection for OpenVZ\n if os.path.isfile('/proc/self/status'):\n with salt.utils.files.fopen('/proc/self/status') as status_file:\n vz_re = re.compile(r'^envID:\\s+(\\d+)$')\n for line in status_file:\n vz_match = vz_re.match(line.rstrip('\\n'))\n if vz_match and int(vz_match.groups()[0]) != 0:\n grains['virtual'] = 'openvzve'\n elif vz_match and int(vz_match.groups()[0]) == 0:\n grains['virtual'] = 'openvzhn'\n if isdir('/proc/sys/xen') or \\\n isdir('/sys/bus/xen') or isdir('/proc/xen'):\n if os.path.isfile('/proc/xen/xsd_kva'):\n # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen\n # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen\n grains['virtual_subtype'] = 'Xen Dom0'\n else:\n if osdata.get('productname', '') == 'HVM domU':\n # Requires dmidecode!\n grains['virtual_subtype'] = 'Xen HVM DomU'\n elif os.path.isfile('/proc/xen/capabilities') and \\\n os.access('/proc/xen/capabilities', os.R_OK):\n with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:\n if 'control_d' not in fhr.read():\n # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen\n grains['virtual_subtype'] = 'Xen PV DomU'\n else:\n # Shouldn't get to this, but just in case\n grains['virtual_subtype'] = 'Xen Dom0'\n # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen\n # Tested on Fedora 15 / 2.6.41.4-1 without running xen\n elif isdir('/sys/bus/xen'):\n if 'xen:' in __salt__['cmd.run']('dmesg').lower():\n grains['virtual_subtype'] = 'Xen PV DomU'\n elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):\n # An actual DomU will have the xenconsole driver\n grains['virtual_subtype'] = 'Xen PV DomU'\n # If a Dom0 or DomU was detected, obviously this is xen\n if 'dom' in grains.get('virtual_subtype', '').lower():\n grains['virtual'] = 'xen'\n # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.\n if os.path.isfile('/proc/1/cgroup'):\n try:\n with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:\n fhr_contents = fhr.read()\n if ':/lxc/' in fhr_contents:\n grains['virtual_subtype'] = 'LXC'\n elif ':/kubepods/' in fhr_contents:\n grains['virtual_subtype'] = 'kubernetes'\n elif ':/libpod_parent/' in fhr_contents:\n grains['virtual_subtype'] = 'libpod'\n else:\n if any(x in fhr_contents\n for x in (':/system.slice/docker', ':/docker/',\n ':/docker-ce/')):\n grains['virtual_subtype'] = 'Docker'\n except IOError:\n pass\n if os.path.isfile('/proc/cpuinfo'):\n with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:\n if 'QEMU Virtual CPU' in fhr.read():\n grains['virtual'] = 'kvm'\n if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):\n try:\n with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:\n output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')\n if 'VirtualBox' in output:\n grains['virtual'] = 'VirtualBox'\n elif 'RHEV Hypervisor' in output:\n grains['virtual'] = 'kvm'\n grains['virtual_subtype'] = 'rhev'\n elif 'oVirt Node' in output:\n grains['virtual'] = 'kvm'\n grains['virtual_subtype'] = 'ovirt'\n elif 'Google' in output:\n grains['virtual'] = 'gce'\n elif 'BHYVE' in output:\n grains['virtual'] = 'bhyve'\n except IOError:\n pass\n elif osdata['kernel'] == 'FreeBSD':\n kenv = salt.utils.path.which('kenv')\n if kenv:\n product = __salt__['cmd.run'](\n '{0} smbios.system.product'.format(kenv)\n )\n maker = __salt__['cmd.run'](\n '{0} smbios.system.maker'.format(kenv)\n )\n if product.startswith('VMware'):\n grains['virtual'] = 'VMware'\n if product.startswith('VirtualBox'):\n grains['virtual'] = 'VirtualBox'\n if maker.startswith('Xen'):\n grains['virtual_subtype'] = '{0} {1}'.format(maker, product)\n grains['virtual'] = 'xen'\n if maker.startswith('Microsoft') and product.startswith('Virtual'):\n grains['virtual'] = 'VirtualPC'\n if maker.startswith('OpenStack'):\n grains['virtual'] = 'OpenStack'\n if maker.startswith('Bochs'):\n grains['virtual'] = 'kvm'\n if sysctl:\n hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))\n model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))\n jail = __salt__['cmd.run'](\n '{0} -n security.jail.jailed'.format(sysctl)\n )\n if 'bhyve' in hv_vendor:\n grains['virtual'] = 'bhyve'\n if jail == '1':\n grains['virtual_subtype'] = 'jail'\n if 'QEMU Virtual CPU' in model:\n grains['virtual'] = 'kvm'\n elif osdata['kernel'] == 'OpenBSD':\n if 'manufacturer' in osdata:\n if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:\n grains['virtual'] = 'kvm'\n if osdata['manufacturer'] == 'OpenBSD':\n grains['virtual'] = 'vmm'\n elif osdata['kernel'] == 'SunOS':\n if grains['virtual'] == 'LDOM':\n roles = []\n for role in ('control', 'io', 'root', 'service'):\n subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)\n ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))\n if ret['stdout'] == 'true':\n roles.append(role)\n if roles:\n grains['virtual_subtype'] = roles\n else:\n # Check if it's a \"regular\" zone. (i.e. Solaris 10/11 zone)\n zonename = salt.utils.path.which('zonename')\n if zonename:\n zone = __salt__['cmd.run']('{0}'.format(zonename))\n if zone != 'global':\n grains['virtual'] = 'zone'\n # Check if it's a branded zone (i.e. Solaris 8/9 zone)\n if isdir('/.SUNWnative'):\n grains['virtual'] = 'zone'\n elif osdata['kernel'] == 'NetBSD':\n if sysctl:\n if 'QEMU Virtual CPU' in __salt__['cmd.run'](\n '{0} -n machdep.cpu_brand'.format(sysctl)):\n grains['virtual'] = 'kvm'\n elif 'invalid' not in __salt__['cmd.run'](\n '{0} -n machdep.xen.suspend'.format(sysctl)):\n grains['virtual'] = 'Xen PV DomU'\n elif 'VMware' in __salt__['cmd.run'](\n '{0} -n machdep.dmi.system-vendor'.format(sysctl)):\n grains['virtual'] = 'VMware'\n # NetBSD has Xen dom0 support\n elif __salt__['cmd.run'](\n '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':\n if os.path.isfile('/var/run/xenconsoled.pid'):\n grains['virtual_subtype'] = 'Xen Dom0'\n\n for command in failed_commands:\n log.info(\n \"Although '%s' was found in path, the current user \"\n 'cannot execute it. Grains output might not be '\n 'accurate.', command\n )\n return grains\n",
"def _virtual_hv(osdata):\n '''\n Returns detailed hypervisor information from sysfs\n Currently this seems to be used only by Xen\n '''\n grains = {}\n\n # Bail early if we're not running on Xen\n try:\n if 'xen' not in osdata['virtual']:\n return grains\n except KeyError:\n return grains\n\n # Try to get the exact hypervisor version from sysfs\n try:\n version = {}\n for fn in ('major', 'minor', 'extra'):\n with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:\n version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())\n grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])\n grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]\n except (IOError, OSError, KeyError):\n pass\n\n # Try to read and decode the supported feature set of the hypervisor\n # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py\n # Table data from include/xen/interface/features.h\n xen_feature_table = {0: 'writable_page_tables',\n 1: 'writable_descriptor_tables',\n 2: 'auto_translated_physmap',\n 3: 'supervisor_mode_kernel',\n 4: 'pae_pgdir_above_4gb',\n 5: 'mmu_pt_update_preserve_ad',\n 7: 'gnttab_map_avail_bits',\n 8: 'hvm_callback_vector',\n 9: 'hvm_safe_pvclock',\n 10: 'hvm_pirqs',\n 11: 'dom0',\n 12: 'grant_map_identity',\n 13: 'memory_op_vnode_supported',\n 14: 'ARM_SMCCC_supported'}\n try:\n with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:\n features = salt.utils.stringutils.to_unicode(fhr.read().strip())\n enabled_features = []\n for bit, feat in six.iteritems(xen_feature_table):\n if int(features, 16) & (1 << bit):\n enabled_features.append(feat)\n grains['virtual_hv_features'] = features\n grains['virtual_hv_features_list'] = enabled_features\n except (IOError, OSError, KeyError):\n pass\n\n return grains\n",
"def _ps(osdata):\n '''\n Return the ps grain\n '''\n grains = {}\n bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')\n if osdata['os'] in bsd_choices:\n grains['ps'] = 'ps auxwww'\n elif osdata['os_family'] == 'Solaris':\n grains['ps'] = '/usr/ucb/ps auxwww'\n elif osdata['os'] == 'Windows':\n grains['ps'] = 'tasklist.exe'\n elif osdata.get('virtual', '') == 'openvzhn':\n grains['ps'] = (\n 'ps -fH -p $(grep -l \\\"^envID:[[:space:]]*0\\\\$\\\" '\n '/proc/[0-9]*/status | sed -e \\\"s=/proc/\\\\([0-9]*\\\\)/.*=\\\\1=\\\") '\n '| awk \\'{ $7=\\\"\\\"; print }\\''\n )\n elif osdata['os_family'] == 'AIX':\n grains['ps'] = '/usr/bin/ps auxww'\n elif osdata['os_family'] == 'NILinuxRT':\n grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'\n else:\n grains['ps'] = 'ps -efHww'\n return grains\n",
"def _hw_data(osdata):\n '''\n Get system specific hardware data from dmidecode\n\n Provides\n biosversion\n productname\n manufacturer\n serialnumber\n biosreleasedate\n uuid\n\n .. versionadded:: 0.9.5\n '''\n\n if salt.utils.platform.is_proxy():\n return {}\n\n grains = {}\n if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):\n # On many Linux distributions basic firmware information is available via sysfs\n # requires CONFIG_DMIID to be enabled in the Linux kernel configuration\n sysfs_firmware_info = {\n 'biosversion': 'bios_version',\n 'productname': 'product_name',\n 'manufacturer': 'sys_vendor',\n 'biosreleasedate': 'bios_date',\n 'uuid': 'product_uuid',\n 'serialnumber': 'product_serial'\n }\n for key, fw_file in sysfs_firmware_info.items():\n contents_file = os.path.join('/sys/class/dmi/id', fw_file)\n if os.path.exists(contents_file):\n try:\n with salt.utils.files.fopen(contents_file, 'r') as ifile:\n grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')\n if key == 'uuid':\n grains['uuid'] = grains['uuid'].lower()\n except (IOError, OSError) as err:\n # PermissionError is new to Python 3, but corresponds to the EACESS and\n # EPERM error numbers. Use those instead here for PY2 compatibility.\n if err.errno == EACCES or err.errno == EPERM:\n # Skip the grain if non-root user has no access to the file.\n pass\n elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (\n salt.utils.platform.is_smartos() or\n ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'\n osdata['kernel'] == 'SunOS' and\n osdata['cpuarch'].startswith('sparc')\n )):\n # On SmartOS (possibly SunOS also) smbios only works in the global zone\n # smbios is also not compatible with linux's smbios (smbios -s = print summarized)\n grains = {\n 'biosversion': __salt__['smbios.get']('bios-version'),\n 'productname': __salt__['smbios.get']('system-product-name'),\n 'manufacturer': __salt__['smbios.get']('system-manufacturer'),\n 'biosreleasedate': __salt__['smbios.get']('bios-release-date'),\n 'uuid': __salt__['smbios.get']('system-uuid')\n }\n grains = dict([(key, val) for key, val in grains.items() if val is not None])\n uuid = __salt__['smbios.get']('system-uuid')\n if uuid is not None:\n grains['uuid'] = uuid.lower()\n for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):\n serial = __salt__['smbios.get'](serial)\n if serial is not None:\n grains['serialnumber'] = serial\n break\n elif salt.utils.path.which_bin(['fw_printenv']) is not None:\n # ARM Linux devices expose UBOOT env variables via fw_printenv\n hwdata = {\n 'manufacturer': 'manufacturer',\n 'serialnumber': 'serial#',\n 'productname': 'DeviceDesc',\n }\n for grain_name, cmd_key in six.iteritems(hwdata):\n result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))\n if result['retcode'] == 0:\n uboot_keyval = result['stdout'].split('=')\n grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])\n elif osdata['kernel'] == 'FreeBSD':\n # On FreeBSD /bin/kenv (already in base system)\n # can be used instead of dmidecode\n kenv = salt.utils.path.which('kenv')\n if kenv:\n # In theory, it will be easier to add new fields to this later\n fbsd_hwdata = {\n 'biosversion': 'smbios.bios.version',\n 'manufacturer': 'smbios.system.maker',\n 'serialnumber': 'smbios.system.serial',\n 'productname': 'smbios.system.product',\n 'biosreleasedate': 'smbios.bios.reldate',\n 'uuid': 'smbios.system.uuid',\n }\n for key, val in six.iteritems(fbsd_hwdata):\n value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))\n grains[key] = _clean_value(key, value)\n elif osdata['kernel'] == 'OpenBSD':\n sysctl = salt.utils.path.which('sysctl')\n hwdata = {'biosversion': 'hw.version',\n 'manufacturer': 'hw.vendor',\n 'productname': 'hw.product',\n 'serialnumber': 'hw.serialno',\n 'uuid': 'hw.uuid'}\n for key, oid in six.iteritems(hwdata):\n value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))\n if not value.endswith(' value is not available'):\n grains[key] = _clean_value(key, value)\n elif osdata['kernel'] == 'NetBSD':\n sysctl = salt.utils.path.which('sysctl')\n nbsd_hwdata = {\n 'biosversion': 'machdep.dmi.board-version',\n 'manufacturer': 'machdep.dmi.system-vendor',\n 'serialnumber': 'machdep.dmi.system-serial',\n 'productname': 'machdep.dmi.system-product',\n 'biosreleasedate': 'machdep.dmi.bios-date',\n 'uuid': 'machdep.dmi.system-uuid',\n }\n for key, oid in six.iteritems(nbsd_hwdata):\n result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))\n if result['retcode'] == 0:\n grains[key] = _clean_value(key, result['stdout'])\n elif osdata['kernel'] == 'Darwin':\n grains['manufacturer'] = 'Apple Inc.'\n sysctl = salt.utils.path.which('sysctl')\n hwdata = {'productname': 'hw.model'}\n for key, oid in hwdata.items():\n value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))\n if not value.endswith(' is invalid'):\n grains[key] = _clean_value(key, value)\n elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):\n # Depending on the hardware model, commands can report different bits\n # of information. With that said, consolidate the output from various\n # commands and attempt various lookups.\n data = \"\"\n for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):\n if salt.utils.path.which(cmd): # Also verifies that cmd is executable\n data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))\n data += '\\n'\n\n sn_regexes = [\n re.compile(r) for r in [\n r'(?im)^\\s*Chassis\\s+Serial\\s+Number\\n-+\\n(\\S+)', # prtdiag\n r'(?im)^\\s*chassis-sn:\\s*(\\S+)', # prtconf\n r'(?im)^\\s*Chassis\\s+Serial#:\\s*(\\S+)', # virtinfo\n ]\n ]\n\n obp_regexes = [\n re.compile(r) for r in [\n r'(?im)^\\s*System\\s+PROM\\s+revisions.*\\nVersion\\n-+\\nOBP\\s+(\\S+)\\s+(\\S+)', # prtdiag\n r'(?im)^\\s*version:\\s*\\'OBP\\s+(\\S+)\\s+(\\S+)', # prtconf\n ]\n ]\n\n fw_regexes = [\n re.compile(r) for r in [\n r'(?im)^\\s*Sun\\s+System\\s+Firmware\\s+(\\S+)\\s+(\\S+)', # prtdiag\n ]\n ]\n\n uuid_regexes = [\n re.compile(r) for r in [\n r'(?im)^\\s*Domain\\s+UUID:\\s*(\\S+)', # virtinfo\n ]\n ]\n\n manufacture_regexes = [\n re.compile(r) for r in [\n r'(?im)^\\s*System\\s+Configuration:\\s*(.*)(?=sun)', # prtdiag\n ]\n ]\n\n product_regexes = [\n re.compile(r) for r in [\n r'(?im)^\\s*System\\s+Configuration:\\s*.*?sun\\d\\S+[^\\S\\r\\n]*(.*)', # prtdiag\n r'(?im)^[^\\S\\r\\n]*banner-name:[^\\S\\r\\n]*(.*)', # prtconf\n r'(?im)^[^\\S\\r\\n]*product-name:[^\\S\\r\\n]*(.*)', # prtconf\n ]\n ]\n\n sn_regexes = [\n re.compile(r) for r in [\n r'(?im)Chassis\\s+Serial\\s+Number\\n-+\\n(\\S+)', # prtdiag\n r'(?i)Chassis\\s+Serial#:\\s*(\\S+)', # virtinfo\n r'(?i)chassis-sn:\\s*(\\S+)', # prtconf\n ]\n ]\n\n obp_regexes = [\n re.compile(r) for r in [\n r'(?im)System\\s+PROM\\s+revisions.*\\nVersion\\n-+\\nOBP\\s+(\\S+)\\s+(\\S+)', # prtdiag\n r'(?im)version:\\s*\\'OBP\\s+(\\S+)\\s+(\\S+)', # prtconf\n ]\n ]\n\n fw_regexes = [\n re.compile(r) for r in [\n r'(?i)Sun\\s+System\\s+Firmware\\s+(\\S+)\\s+(\\S+)', # prtdiag\n ]\n ]\n\n uuid_regexes = [\n re.compile(r) for r in [\n r'(?i)Domain\\s+UUID:\\s+(\\S+)', # virtinfo\n ]\n ]\n\n for regex in sn_regexes:\n res = regex.search(data)\n if res and len(res.groups()) >= 1:\n grains['serialnumber'] = res.group(1).strip().replace(\"'\", \"\")\n break\n\n for regex in obp_regexes:\n res = regex.search(data)\n if res and len(res.groups()) >= 1:\n obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places\n grains['biosversion'] = obp_rev.strip().replace(\"'\", \"\")\n grains['biosreleasedate'] = obp_date.strip().replace(\"'\", \"\")\n\n for regex in fw_regexes:\n res = regex.search(data)\n if res and len(res.groups()) >= 1:\n fw_rev, fw_date = res.groups()[0:2]\n grains['systemfirmware'] = fw_rev.strip().replace(\"'\", \"\")\n grains['systemfirmwaredate'] = fw_date.strip().replace(\"'\", \"\")\n break\n\n for regex in uuid_regexes:\n res = regex.search(data)\n if res and len(res.groups()) >= 1:\n grains['uuid'] = res.group(1).strip().replace(\"'\", \"\")\n break\n\n for regex in manufacture_regexes:\n res = regex.search(data)\n if res and len(res.groups()) >= 1:\n grains['manufacture'] = res.group(1).strip().replace(\"'\", \"\")\n break\n\n for regex in product_regexes:\n res = regex.search(data)\n if res and len(res.groups()) >= 1:\n t_productname = res.group(1).strip().replace(\"'\", \"\")\n if t_productname:\n grains['product'] = t_productname\n grains['productname'] = t_productname\n break\n elif osdata['kernel'] == 'AIX':\n cmd = salt.utils.path.which('prtconf')\n if cmd:\n data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep\n for dest, regstring in (('serialnumber', r'(?im)^\\s*Machine\\s+Serial\\s+Number:\\s+(\\S+)'),\n ('systemfirmware', r'(?im)^\\s*Firmware\\s+Version:\\s+(.*)')):\n for regex in [re.compile(r) for r in [regstring]]:\n res = regex.search(data)\n if res and len(res.groups()) >= 1:\n grains[dest] = res.group(1).strip().replace(\"'\", '')\n\n product_regexes = [re.compile(r'(?im)^\\s*System\\s+Model:\\s+(\\S+)')]\n for regex in product_regexes:\n res = regex.search(data)\n if res and len(res.groups()) >= 1:\n grains['manufacturer'], grains['productname'] = res.group(1).strip().replace(\"'\", \"\").split(\",\")\n break\n else:\n log.error('The \\'prtconf\\' binary was not found in $PATH.')\n\n elif osdata['kernel'] == 'AIX':\n cmd = salt.utils.path.which('prtconf')\n if data:\n data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep\n for dest, regstring in (('serialnumber', r'(?im)^\\s*Machine\\s+Serial\\s+Number:\\s+(\\S+)'),\n ('systemfirmware', r'(?im)^\\s*Firmware\\s+Version:\\s+(.*)')):\n for regex in [re.compile(r) for r in [regstring]]:\n res = regex.search(data)\n if res and len(res.groups()) >= 1:\n grains[dest] = res.group(1).strip().replace(\"'\", '')\n\n product_regexes = [re.compile(r'(?im)^\\s*System\\s+Model:\\s+(\\S+)')]\n for regex in product_regexes:\n res = regex.search(data)\n if res and len(res.groups()) >= 1:\n grains['manufacturer'], grains['productname'] = res.group(1).strip().replace(\"'\", \"\").split(\",\")\n break\n else:\n log.error('The \\'prtconf\\' binary was not found in $PATH.')\n\n return grains\n"
] |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
locale_info
|
python
|
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
|
Provides
defaultlanguage
defaultencoding
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2087-L2112
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
hostname
|
python
|
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
|
Return fqdn, hostname, domainname
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2115-L2146
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
append_domain
|
python
|
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
|
Return append_domain if set
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2149-L2161
| null |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
saltstack/salt
|
salt/grains/core.py
|
fqdns
|
python
|
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))}
|
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2164-L2191
|
[
"def _get_interfaces():\n '''\n Provide a dict of the connected interfaces and their ip addresses\n '''\n\n global _INTERFACES\n if not _INTERFACES:\n _INTERFACES = salt.utils.network.interfaces()\n return _INTERFACES\n",
"def ip_addrs(interface=None, include_loopback=False, interface_data=None):\n '''\n Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is\n ignored, unless 'include_loopback=True' is indicated. If 'interface' is\n provided, then only IP addresses from that interface will be returned.\n '''\n return _ip_addrs(interface, include_loopback, interface_data, 'inet')\n",
"def ip_addrs6(interface=None, include_loopback=False, interface_data=None):\n '''\n Returns a list of IPv6 addresses assigned to the host. ::1 is ignored,\n unless 'include_loopback=True' is indicated. If 'interface' is provided,\n then only IP addresses from that interface will be returned.\n '''\n return _ip_addrs(interface, include_loopback, interface_data, 'inet6')\n"
] |
# -*- coding: utf-8 -*-
'''
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import socket
import sys
import re
import platform
import logging
import locale
import uuid
import zlib
from errno import EACCES, EPERM
import datetime
import warnings
# pylint: disable=import-error
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
__proxyenabled__ = ['*']
__FQDN__ = None
# Extend the default list of supported distros. This will be used for the
# /etc/DISTRO-release checking that is part of linux_distribution()
from platform import _supported_dists
_supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64',
'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void')
# linux_distribution deprecated in py3.7
try:
from platform import linux_distribution as _deprecated_linux_distribution
def linux_distribution(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return _deprecated_linux_distribution(**kwargs)
except ImportError:
from distro import linux_distribution
# Import salt libs
import salt.exceptions
import salt.log
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.versions
from salt.ext import six
from salt.ext.six.moves import range
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.smbios
__salt__ = {
'cmd.run': salt.modules.cmdmod._run_quiet,
'cmd.retcode': salt.modules.cmdmod._retcode_quiet,
'cmd.run_all': salt.modules.cmdmod._run_all_quiet,
'smbios.records': salt.modules.smbios.records,
'smbios.get': salt.modules.smbios.get,
}
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
'Unable to import Python wmi module, some core grains '
'will be missing'
)
HAS_UNAME = True
if not hasattr(os, 'uname'):
HAS_UNAME = False
_INTERFACES = {}
def _windows_cpudata():
'''
Return some CPU information on Windows minions
'''
# Provides:
# num_cpus
# cpu_model
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains
def _linux_cpudata():
'''
Return some CPU information for Linux minions
'''
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
grains['num_cpus'] = 0
for line in _fp:
comps = line.split(':')
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == 'processor':
grains['num_cpus'] += 1
elif key == 'model name':
grains['cpu_model'] = val
elif key == 'flags':
grains['cpu_flags'] = val.split()
elif key == 'Features':
grains['cpu_flags'] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == 'Processor':
grains['cpu_model'] = val.split('-')[0]
grains['num_cpus'] = 1
if 'num_cpus' not in grains:
grains['num_cpus'] = 0
if 'cpu_model' not in grains:
grains['cpu_model'] = 'Unknown'
if 'cpu_flags' not in grains:
grains['cpu_flags'] = []
return grains
def _linux_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
if __opts__.get('enable_lspci', True) is False:
return {}
if __opts__.get('enable_gpu_grains', True) is False:
return {}
lspci = salt.utils.path.which('lspci')
if not lspci:
log.debug(
'The `lspci` binary is not available on the system. GPU grains '
'will not be available.'
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpu_classes = ('vga compatible controller', '3d controller')
devs = []
try:
lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append('')
for line in lspci_list:
# check for record-separating empty lines
if line == '':
if cur_dev.get('Class', '').lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r'^\w+:\s+.*', line):
key, val = line.split(':', 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug('Unexpected lspci output: \'%s\'', line)
if error:
log.warning(
'Error loading grains, unexpected linux_gpu_data output, '
'check that you have a valid shell configured and '
'permissions to run lspci command'
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = 'unknown'
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({'vendor': vendor, 'model': gpu['Device']})
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _netbsd_gpu_data():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed']
gpus = []
try:
pcictl_out = __salt__['cmd.run']('pcictl pci0 list')
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor),
line,
re.IGNORECASE
)
if vendor_match:
gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _osx_gpudata():
'''
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
'''
gpus = []
try:
pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType')
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(': ')
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(' ')
vendor = vendor.lower()
gpus.append({'vendor': vendor, 'model': model})
except OSError:
pass
grains = {}
grains['num_gpus'] = len(gpus)
grains['gpus'] = gpus
return grains
def _bsd_cpudata(osdata):
'''
Return CPU information for BSD-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which('sysctl')
arch = salt.utils.path.which('arch')
cmds = {}
if sysctl:
cmds.update({
'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
'cpuarch': '{0} -n hw.machine'.format(sysctl),
'cpu_model': '{0} -n hw.model'.format(sysctl),
})
if arch and osdata['kernel'] == 'OpenBSD':
cmds['cpuarch'] = '{0} -s'.format(arch)
if osdata['kernel'] == 'Darwin':
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])
if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if osdata['kernel'] == 'NetBSD':
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
grains['cpu_flags'] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(' '):
break # game over
if 'Features' in line:
start = line.find('<')
end = line.find('>')
if start > 0 and end > 0:
flag = line[start + 1:end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
def _sunos_cpudata():
'''
Return the CPU information for Solaris-like systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains['cpu_flags'] = []
grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
kstat_info = 'kstat -p cpu_info:*:*:brand'
for line in __salt__['cmd.run'](kstat_info).splitlines():
match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
if match:
grains['cpu_model'] = match.group(2)
isainfo = 'isainfo -n -v'
for line in __salt__['cmd.run'](isainfo).splitlines():
match = re.match(r'^\s+(.+)', line)
if match:
cpu_flags = match.group(1).split()
grains['cpu_flags'].extend(cpu_flags)
return grains
def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _linux_memdata():
'''
Return the memory information for Linux-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
# Use floor division to force output to be an integer
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
# Use floor division to force output to be an integer
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
if swap_total.endswith('K'):
_power = 2**10
elif swap_total.endswith('M'):
_power = 2**20
elif swap_total.endswith('G'):
_power = 2**30
swap_total = float(swap_total[:-1]) * _power
grains['mem_total'] = int(mem) // 1024 // 1024
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
grains['mem_total'] = int(mem) // 1024 // 1024
if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
swapctl = salt.utils.path.which('swapctl')
swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
if swap_data == 'no swap devices configured':
swap_total = 0
else:
swap_total = swap_data.split(' ')[1]
else:
swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
grains['swap_total'] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:':
grains['mem_total'] = int(comps[2].strip())
swap_cmd = salt.utils.path.which('swap')
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
return grains
def _aix_memdata():
'''
Return the memory information for AIX systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = salt.utils.path.which('prtconf')
if prtconf:
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(' ') if x]
if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]:
grains['mem_total'] = int(comps[2])
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
swap_cmd = salt.utils.path.which('swap')
if swap_cmd:
swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains['swap_total'] = swap_total
else:
log.error('The \'swap\' binary was not found in $PATH.')
return grains
def _windows_memdata():
'''
Return the memory information for Windows systems
'''
grains = {'mem_total': 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys']
# return memory info in gigabytes
grains['mem_total'] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
'''
Gather information about the system memory
'''
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {'mem_total': 0}
if osdata['kernel'] == 'Linux':
grains.update(_linux_memdata())
elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
grains.update(_bsd_memdata(osdata))
elif osdata['kernel'] == 'Darwin':
grains.update(_osx_memdata())
elif osdata['kernel'] == 'SunOS':
grains.update(_sunos_memdata())
elif osdata['kernel'] == 'AIX':
grains.update(_aix_memdata())
elif osdata['kernel'] == 'Windows' and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
'''
Parse the output of lsattr -El sys0 for os_uuid
'''
grains = {}
cmd = salt.utils.path.which('lsattr')
if cmd:
data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep
uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['machine_id'] = res.group(1).strip()
break
else:
log.error('The \'lsattr\' binary was not found in $PATH.')
return grains
def _windows_virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata['kernel'] != 'Windows':
return grains
grains['virtual'] = 'physical'
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get('manufacturer', '')
if manufacturer is None:
manufacturer = ''
productname = osdata.get('productname', '')
if productname is None:
productname = ''
if 'QEMU' in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Bochs' in manufacturer:
grains['virtual'] = 'kvm'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'oVirt' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'oVirt'
# Red Hat Enterprise Virtualization
elif 'RHEV Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
# Product Name: VirtualBox
elif 'VirtualBox' in productname:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware Virtual Platform' in productname:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif 'Microsoft' in manufacturer and \
'Virtual Machine' in productname:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in manufacturer:
grains['virtual'] = 'Parallels'
# Apache CloudStack
elif 'CloudStack KVM Hypervisor' in productname:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'cloudstack'
return grains
def _virtual(osdata):
'''
Returns what type of virtual hardware is under the hood, kvm or physical
'''
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {'virtual': 'physical'}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ('AIX',)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
if salt.utils.path.which('virt-what'):
_cmds = ['virt-what']
# Check if enable_lspci is True or False
if __opts__.get('enable_lspci', True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists('/proc/bus/pci'):
_cmds += ['lspci']
# Add additional last resort commands
if osdata['kernel'] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
grains['virtual'] = 'zone'
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata['kernel'] == 'Darwin':
command = 'system_profiler'
args = ['SPDisplaysDataType']
elif osdata['kernel'] == 'SunOS':
virtinfo = salt.utils.path.which('virtinfo')
if virtinfo:
try:
ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret['stdout'].endswith('not supported'):
command = 'prtdiag'
else:
command = 'virtinfo'
else:
command = 'prtdiag'
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = '{0} {1}'.format(cmd, ' '.join(args))
try:
ret = __salt__['cmd.run_all'](cmd)
if ret['retcode'] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret['stdout']
if command == "system_profiler":
macoutput = output.lower()
if '0x1ab8' in macoutput:
grains['virtual'] = 'Parallels'
if 'parallels' in macoutput:
grains['virtual'] = 'Parallels'
if 'vmware' in macoutput:
grains['virtual'] = 'VMware'
if '0x15ad' in macoutput:
grains['virtual'] = 'VMware'
if 'virtualbox' in macoutput:
grains['virtual'] = 'VirtualBox'
# Break out of the loop so the next log message is not issued
break
elif command == 'systemd-detect-virt':
if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'microsoft' in output:
grains['virtual'] = 'VirtualPC'
break
elif 'lxc' in output:
grains['virtual'] = 'LXC'
break
elif 'systemd-nspawn' in output:
grains['virtual'] = 'LXC'
break
elif command == 'virt-what':
try:
output = output.splitlines()[-1]
except IndexError:
pass
if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
grains['virtual'] = output
break
elif 'vmware' in output:
grains['virtual'] = 'VMware'
break
elif 'parallels' in output:
grains['virtual'] = 'Parallels'
break
elif 'hyperv' in output:
grains['virtual'] = 'HyperV'
break
elif command == 'dmidecode':
# Product Name: VirtualBox
if 'Vendor: QEMU' in output:
# FIXME: Make this detect between kvm or qemu
grains['virtual'] = 'kvm'
if 'Manufacturer: QEMU' in output:
grains['virtual'] = 'kvm'
if 'Vendor: Bochs' in output:
grains['virtual'] = 'kvm'
if 'Manufacturer: Bochs' in output:
grains['virtual'] = 'kvm'
if 'BHYVE' in output:
grains['virtual'] = 'bhyve'
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif 'Manufacturer: oVirt' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
# Red Hat Enterprise Virtualization
elif 'Product Name: RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
# Product Name: VMware Virtual Platform
elif 'VMware' in output:
grains['virtual'] = 'VMware'
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ': Microsoft' in output and 'Virtual Machine' in output:
grains['virtual'] = 'VirtualPC'
# Manufacturer: Parallels Software International Inc.
elif 'Parallels Software' in output:
grains['virtual'] = 'Parallels'
elif 'Manufacturer: Google' in output:
grains['virtual'] = 'kvm'
# Proxmox KVM
elif 'Vendor: SeaBIOS' in output:
grains['virtual'] = 'kvm'
# Break out of the loop, lspci parsing is not necessary
break
elif command == 'lspci':
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if 'vmware' in model:
grains['virtual'] = 'VMware'
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'virtio' in model:
grains['virtual'] = 'kvm'
# Break out of the loop so the next log message is not issued
break
elif command == 'prtdiag':
model = output.lower().split("\n")[0]
if 'vmware' in model:
grains['virtual'] = 'VMware'
elif 'virtualbox' in model:
grains['virtual'] = 'VirtualBox'
elif 'qemu' in model:
grains['virtual'] = 'kvm'
elif 'joyent smartdc hvm' in model:
grains['virtual'] = 'kvm'
break
elif command == 'virtinfo':
grains['virtual'] = 'LDOM'
break
choices = ('Linux', 'HP-UX')
isdir = os.path.isdir
sysctl = salt.utils.path.which('sysctl')
if osdata['kernel'] in choices:
if os.path.isdir('/proc'):
try:
self_root = os.stat('/')
init_root = os.stat('/proc/1/root/.')
if self_root != init_root:
grains['virtual_subtype'] = 'chroot'
except (IOError, OSError):
pass
if isdir('/proc/vz'):
if os.path.isfile('/proc/vz/version'):
grains['virtual'] = 'openvzhn'
elif os.path.isfile('/proc/vz/veinfo'):
grains['virtual'] = 'openvzve'
# a posteriori, it's expected for these to have failed:
failed_commands.discard('lspci')
failed_commands.discard('dmidecode')
# Provide additional detection for OpenVZ
if os.path.isfile('/proc/self/status'):
with salt.utils.files.fopen('/proc/self/status') as status_file:
vz_re = re.compile(r'^envID:\s+(\d+)$')
for line in status_file:
vz_match = vz_re.match(line.rstrip('\n'))
if vz_match and int(vz_match.groups()[0]) != 0:
grains['virtual'] = 'openvzve'
elif vz_match and int(vz_match.groups()[0]) == 0:
grains['virtual'] = 'openvzhn'
if isdir('/proc/sys/xen') or \
isdir('/sys/bus/xen') or isdir('/proc/xen'):
if os.path.isfile('/proc/xen/xsd_kva'):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains['virtual_subtype'] = 'Xen Dom0'
else:
if osdata.get('productname', '') == 'HVM domU':
# Requires dmidecode!
grains['virtual_subtype'] = 'Xen HVM DomU'
elif os.path.isfile('/proc/xen/capabilities') and \
os.access('/proc/xen/capabilities', os.R_OK):
with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
if 'control_d' not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains['virtual_subtype'] = 'Xen PV DomU'
else:
# Shouldn't get to this, but just in case
grains['virtual_subtype'] = 'Xen Dom0'
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir('/sys/bus/xen'):
if 'xen:' in __salt__['cmd.run']('dmesg').lower():
grains['virtual_subtype'] = 'Xen PV DomU'
elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
# An actual DomU will have the xenconsole driver
grains['virtual_subtype'] = 'Xen PV DomU'
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
fhr_contents = fhr.read()
if ':/lxc/' in fhr_contents:
grains['virtual_subtype'] = 'LXC'
elif ':/kubepods/' in fhr_contents:
grains['virtual_subtype'] = 'kubernetes'
elif ':/libpod_parent/' in fhr_contents:
grains['virtual_subtype'] = 'libpod'
else:
if any(x in fhr_contents
for x in (':/system.slice/docker', ':/docker/',
':/docker-ce/')):
grains['virtual_subtype'] = 'Docker'
except IOError:
pass
if os.path.isfile('/proc/cpuinfo'):
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
if 'QEMU Virtual CPU' in fhr.read():
grains['virtual'] = 'kvm'
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'rhev'
elif 'oVirt Node' in output:
grains['virtual'] = 'kvm'
grains['virtual_subtype'] = 'ovirt'
elif 'Google' in output:
grains['virtual'] = 'gce'
elif 'BHYVE' in output:
grains['virtual'] = 'bhyve'
except IOError:
pass
elif osdata['kernel'] == 'FreeBSD':
kenv = salt.utils.path.which('kenv')
if kenv:
product = __salt__['cmd.run'](
'{0} smbios.system.product'.format(kenv)
)
maker = __salt__['cmd.run'](
'{0} smbios.system.maker'.format(kenv)
)
if product.startswith('VMware'):
grains['virtual'] = 'VMware'
if product.startswith('VirtualBox'):
grains['virtual'] = 'VirtualBox'
if maker.startswith('Xen'):
grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
grains['virtual'] = 'xen'
if maker.startswith('Microsoft') and product.startswith('Virtual'):
grains['virtual'] = 'VirtualPC'
if maker.startswith('OpenStack'):
grains['virtual'] = 'OpenStack'
if maker.startswith('Bochs'):
grains['virtual'] = 'kvm'
if sysctl:
hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
jail = __salt__['cmd.run'](
'{0} -n security.jail.jailed'.format(sysctl)
)
if 'bhyve' in hv_vendor:
grains['virtual'] = 'bhyve'
if jail == '1':
grains['virtual_subtype'] = 'jail'
if 'QEMU Virtual CPU' in model:
grains['virtual'] = 'kvm'
elif osdata['kernel'] == 'OpenBSD':
if 'manufacturer' in osdata:
if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
grains['virtual'] = 'kvm'
if osdata['manufacturer'] == 'OpenBSD':
grains['virtual'] = 'vmm'
elif osdata['kernel'] == 'SunOS':
if grains['virtual'] == 'LDOM':
roles = []
for role in ('control', 'io', 'root', 'service'):
subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
if ret['stdout'] == 'true':
roles.append(role)
if roles:
grains['virtual_subtype'] = roles
else:
# Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
zonename = salt.utils.path.which('zonename')
if zonename:
zone = __salt__['cmd.run']('{0}'.format(zonename))
if zone != 'global':
grains['virtual'] = 'zone'
# Check if it's a branded zone (i.e. Solaris 8/9 zone)
if isdir('/.SUNWnative'):
grains['virtual'] = 'zone'
elif osdata['kernel'] == 'NetBSD':
if sysctl:
if 'QEMU Virtual CPU' in __salt__['cmd.run'](
'{0} -n machdep.cpu_brand'.format(sysctl)):
grains['virtual'] = 'kvm'
elif 'invalid' not in __salt__['cmd.run'](
'{0} -n machdep.xen.suspend'.format(sysctl)):
grains['virtual'] = 'Xen PV DomU'
elif 'VMware' in __salt__['cmd.run'](
'{0} -n machdep.dmi.system-vendor'.format(sysctl)):
grains['virtual'] = 'VMware'
# NetBSD has Xen dom0 support
elif __salt__['cmd.run'](
'{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
if os.path.isfile('/var/run/xenconsoled.pid'):
grains['virtual_subtype'] = 'Xen Dom0'
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
'cannot execute it. Grains output might not be '
'accurate.', command
)
return grains
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Windows':
grains['ps'] = 'tasklist.exe'
elif osdata.get('virtual', '') == 'openvzhn':
grains['ps'] = (
'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" '
'/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") '
'| awk \'{ $7=\"\"; print }\''
)
elif osdata['os_family'] == 'AIX':
grains['ps'] = '/usr/bin/ps auxww'
elif osdata['os_family'] == 'NILinuxRT':
grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'
else:
grains['ps'] = 'ps -efHww'
return grains
def _clean_value(key, val):
'''
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
'''
if (val is None or not val or
re.match('none', val, flags=re.IGNORECASE)):
return None
elif 'uuid' in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' '))
return None
elif re.search('serial|part|version', key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (re.match(r'^[0]+$', val) or
re.match(r'[0]?1234567[8]?[9]?[0]?', val) or
re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)):
return None
elif re.search('asset|manufacturer', key):
# AssetTag0. Manufacturer04. Begone.
if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if (re.search(r'to be filled', val, flags=re.IGNORECASE) or
re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)',
val, flags=re.IGNORECASE)):
return None
return val
def _windows_platform_data():
'''
Use the platform module for as much as we can.
'''
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {'product': None,
'serial': None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard['product'] = motherboardinfo.Product
motherboard['serial'] = motherboardinfo.SerialNumber
except IndexError:
log.debug('Motherboard info not available on this system')
os_release = platform.release()
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info['ServicePackMajor'] > 0:
service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])])
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = 'Unknown'
release = ''
if 'Server' in osinfo.Caption:
for item in osinfo.Caption.split(' '):
# If it's all digits, then it's version
if re.match(r'\d+', item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r'^R\d+$', item):
release = item
os_release = '{0}Server{1}'.format(version, release)
else:
for item in osinfo.Caption.split(' '):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
version = item
os_release = version
grains = {
'kernelrelease': _clean_value('kernelrelease', osinfo.Version),
'kernelversion': _clean_value('kernelversion', kernel_version),
'osversion': _clean_value('osversion', osinfo.Version),
'osrelease': _clean_value('osrelease', os_release),
'osservicepack': _clean_value('osservicepack', service_pack),
'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer),
'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer),
'productname': _clean_value('productname', systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
'biosversion': _clean_value('biosversion', biosinfo.Name.strip()),
'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber),
'osfullname': _clean_value('osfullname', osinfo.Caption),
'timezone': _clean_value('timezone', timeinfo.Description),
'windowsdomain': _clean_value('windowsdomain', net_info['Domain']),
'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']),
'motherboard': {
'productname': _clean_value('motherboard.productname', motherboard['product']),
'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']),
}
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if 'VRTUAL' in biosinfo.Version: # (not a typo)
grains['virtual'] = 'HyperV'
elif 'A M I' in biosinfo.Version:
grains['virtual'] = 'VirtualPC'
elif 'VMware' in systeminfo.Model:
grains['virtual'] = 'VMware'
elif 'VirtualBox' in systeminfo.Model:
grains['virtual'] = 'VirtualBox'
elif 'Xen' in biosinfo.Version:
grains['virtual'] = 'Xen'
if 'HVM domU' in systeminfo.Model:
grains['virtual_subtype'] = 'HVM domU'
elif 'OpenStack' in systeminfo.Model:
grains['virtual'] = 'OpenStack'
return grains
def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains
def id_():
'''
Return the id
'''
return {'id': __opts__.get('id', '')}
_REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
'redhatente': 'RedHat',
'gentoobase': 'Gentoo',
'archarm': 'Arch ARM',
'arch': 'Arch',
'debian': 'Debian',
'raspbian': 'Raspbian',
'fedoraremi': 'Fedora',
'chapeau': 'Chapeau',
'korora': 'Korora',
'amazonami': 'Amazon',
'alt': 'ALT',
'enterprise': 'OEL',
'oracleserv': 'OEL',
'cloudserve': 'CloudLinux',
'cloudlinux': 'CloudLinux',
'pidora': 'Fedora',
'scientific': 'ScientificLinux',
'synology': 'Synology',
'nilrt': 'NILinuxRT',
'poky': 'Poky',
'manjaro': 'Manjaro',
'manjarolin': 'Manjaro',
'univention': 'Univention',
'antergos': 'Antergos',
'sles': 'SUSE',
'void': 'Void',
'slesexpand': 'RES',
'linuxmint': 'Mint',
'neon': 'KDE neon',
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
'Ubuntu': 'Debian',
'Fedora': 'RedHat',
'Chapeau': 'RedHat',
'Korora': 'RedHat',
'FedBerry': 'RedHat',
'CentOS': 'RedHat',
'GoOSe': 'RedHat',
'Scientific': 'RedHat',
'Amazon': 'RedHat',
'CloudLinux': 'RedHat',
'OVS': 'RedHat',
'OEL': 'RedHat',
'XCP': 'RedHat',
'XCP-ng': 'RedHat',
'XenServer': 'RedHat',
'RES': 'RedHat',
'Sangoma': 'RedHat',
'Mandrake': 'Mandriva',
'ESXi': 'VMware',
'Mint': 'Debian',
'VMwareESX': 'VMware',
'Bluewhite64': 'Bluewhite',
'Slamd64': 'Slackware',
'SLES': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SUSE Enterprise Server': 'Suse',
'SLED': 'Suse',
'openSUSE': 'Suse',
'SUSE': 'Suse',
'openSUSE Leap': 'Suse',
'openSUSE Tumbleweed': 'Suse',
'SLES_SAP': 'Suse',
'Solaris': 'Solaris',
'SmartOS': 'Solaris',
'OmniOS': 'Solaris',
'OpenIndiana Development': 'Solaris',
'OpenIndiana': 'Solaris',
'OpenSolaris Development': 'Solaris',
'OpenSolaris': 'Solaris',
'Oracle Solaris': 'Solaris',
'Arch ARM': 'Arch',
'Manjaro': 'Arch',
'Antergos': 'Arch',
'ALT': 'RedHat',
'Trisquel': 'Debian',
'GCEL': 'Debian',
'Linaro': 'Debian',
'elementary OS': 'Debian',
'elementary': 'Debian',
'Univention': 'Debian',
'ScientificLinux': 'RedHat',
'Raspbian': 'Debian',
'Devuan': 'Debian',
'antiX': 'Debian',
'Kali': 'Debian',
'neon': 'Debian',
'Cumulus': 'Debian',
'Deepin': 'Debian',
'NILinuxRT': 'NILinuxRT',
'KDE neon': 'Debian',
'Void': 'Void',
'IDMS': 'Debian',
'Funtoo': 'Gentoo',
'AIX': 'AIX',
'TurnKey': 'Debian',
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile((
'^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?'
'([\\w\\s\\.\\-_]+)(?:\'|")?'
))
def _linux_bin_exists(binary):
'''
Does a binary exist in linux (depends on which, type, or whereis)
'''
for search_cmd in ('which', 'type -ap'):
try:
return __salt__['cmd.retcode'](
'{0} {1}'.format(search_cmd, binary)
) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return len(__salt__['cmd.run_all'](
'whereis -b {0}'.format(binary)
)['stdout'].split()) > 1
except salt.exceptions.CommandExecutionError:
return False
def _get_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
'''
global _INTERFACES
if not _INTERFACES:
_INTERFACES = salt.utils.network.interfaces()
return _INTERFACES
def _parse_lsb_release():
ret = {}
try:
log.trace('Attempting to parse /etc/lsb-release')
with salt.utils.files.fopen('/etc/lsb-release') as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret['lsb_{0}'.format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace('Failed to parse /etc/lsb-release: %s', exc)
return ret
def _parse_os_release(*os_release_files):
'''
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
'''
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$')
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r'\1', match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
'''
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
:param cpe:
:return:
'''
part = {
'o': 'operating system',
'h': 'hardware',
'a': 'application',
}
ret = {}
cpe = (cpe or '').split(':')
if len(cpe) > 4 and cpe[0] == 'cpe':
if cpe[1].startswith('/'): # WFN to URI
ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
ret['phase'] = cpe[5] if len(cpe) > 5 else None
ret['part'] = part.get(cpe[1][1:])
elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string
ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
ret['part'] = part.get(cpe[2])
return ret
def os_data():
'''
Return grains pertaining to the operating system
'''
grains = {
'num_gpus': 0,
'gpus': [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(grains['kernel'], grains['nodename'],
grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains['kernel'] = 'proxy'
grains['kernelrelease'] = 'proxy'
grains['kernelversion'] = 'proxy'
grains['osrelease'] = 'proxy'
grains['os'] = 'proxy'
grains['os_family'] = 'proxy'
grains['osfullname'] = 'proxy'
elif salt.utils.platform.is_windows():
grains['os'] = 'Windows'
grains['os_family'] = 'Windows'
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if 'Server' in grains['osrelease']:
osrelease_info = grains['osrelease'].split('Server', 1)
osrelease_info[1] = osrelease_info[1].lstrip('R')
else:
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
grains['osfinger'] = '{os}-{ver}'.format(
os=grains['os'],
ver=grains['osrelease'])
grains['init'] = 'Windows'
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists('selinuxenabled'):
log.trace('Adding selinux grains')
grains['selinux'] = {}
grains['selinux']['enabled'] = __salt__['cmd.retcode'](
'selinuxenabled'
) == 0
if _linux_bin_exists('getenforce'):
grains['selinux']['enforced'] = __salt__['cmd.run'](
'getenforce'
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
log.trace('Adding systemd grains')
grains['systemd'] = {}
systemd_info = __salt__['cmd.run'](
'systemctl --version'
).splitlines()
grains['systemd']['version'] = systemd_info[0].split()[1]
grains['systemd']['features'] = systemd_info[1]
# Add init grain
grains['init'] = 'unknown'
log.trace('Adding init grain')
try:
os.stat('/run/systemd/system')
grains['init'] = 'systemd'
except (OSError, IOError):
try:
with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
init_cmdline = fhr.read().replace('\x00', ' ').split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning('Unable to fetch data from /proc/1/cmdline')
if init_bin is not None and init_bin.endswith('bin/init'):
supported_inits = (b'upstart', b'sysvinit', b'systemd')
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__['file_buffer_size']
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, 'rb') as fp_:
edge = b''
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode('utf-8')
grains['init'] = item
buf = b''
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
'Unable to read from init_bin (%s): %s',
init_bin, exc
)
elif salt.utils.path.which('supervisord') in init_cmdline:
grains['init'] = 'supervisord'
elif salt.utils.path.which('dumb-init') in init_cmdline:
# https://github.com/Yelp/dumb-init
grains['init'] = 'dumb-init'
elif salt.utils.path.which('tini') in init_cmdline:
# https://github.com/krallin/tini
grains['init'] = 'tini'
elif init_cmdline == ['runit']:
grains['init'] = 'runit'
elif '/sbin/my_init' in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains['init'] = 'runit'
else:
log.debug(
'Could not determine init system from command line: (%s)',
' '.join(init_cmdline)
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace('Getting lsb_release distro information')
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = 'lsb_{0}{1}'.format(
'' if key.startswith('distrib_') else 'distrib_',
key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace('lsb_release python bindings not available')
grains.update(_parse_lsb_release())
if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains['osfullname'] = 'Antergos Linux'
elif 'lsb_distrib_id' not in grains:
log.trace(
'Failed to get lsb_distrib_id, trying to parse os-release'
)
os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
if os_release:
if 'NAME' in os_release:
grains['lsb_distrib_id'] = os_release['NAME'].strip()
if 'VERSION_ID' in os_release:
grains['lsb_distrib_release'] = os_release['VERSION_ID']
if 'VERSION_CODENAME' in os_release:
grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
elif 'PRETTY_NAME' in os_release:
codename = os_release['PRETTY_NAME']
# https://github.com/saltstack/salt/issues/44108
if os_release['ID'] == 'debian':
codename_match = re.search(r'\((\w+)\)$', codename)
if codename_match:
codename = codename_match.group(1)
grains['lsb_distrib_codename'] = codename
if 'CPE_NAME' in os_release:
cpe = _parse_cpe_name(os_release['CPE_NAME'])
if not cpe:
log.error('Broken CPE_NAME format in /etc/os-release!')
elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
grains['os'] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains['osfullname'] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains['osfullname'] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES
grains['lsb_distrib_release'] = cpe['version']
elif os.path.isfile('/etc/SuSE-release'):
log.trace('Parsing distrib info from /etc/SuSE-release')
grains['lsb_distrib_id'] = 'SUSE'
version = ''
patch = ''
with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
for line in fhr:
if 'enterprise' in line.lower():
grains['lsb_distrib_id'] = 'SLES'
grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
elif 'version' in line.lower():
version = re.sub(r'[^0-9]', '', line)
elif 'patchlevel' in line.lower():
patch = re.sub(r'[^0-9]', '', line)
grains['lsb_distrib_release'] = version
if patch:
grains['lsb_distrib_release'] += '.' + patch
patchstr = 'SP' + patch
if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
grains['lsb_distrib_codename'] += ' ' + patchstr
if not grains.get('lsb_distrib_codename'):
grains['lsb_distrib_codename'] = 'n.a'
elif os.path.isfile('/etc/altlinux-release'):
log.trace('Parsing distrib info from /etc/altlinux-release')
# ALT Linux
grains['lsb_distrib_id'] = 'altlinux'
with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == 'ALT':
grains['lsb_distrib_release'] = comps[2]
grains['lsb_distrib_codename'] = \
comps[3].replace('(', '').replace(')', '')
elif os.path.isfile('/etc/centos-release'):
log.trace('Parsing distrib info from /etc/centos-release')
# Maybe CentOS Linux; could also be SUSE Expanded Support.
# SUSE ES has both, centos-release and redhat-release.
if os.path.isfile('/etc/redhat-release'):
with salt.utils.files.fopen('/etc/redhat-release') as ifile:
for line in ifile:
if "red hat enterprise linux server" in line.lower():
# This is a SUSE Expanded Support Rhel installation
grains['lsb_distrib_id'] = 'RedHat'
break
grains.setdefault('lsb_distrib_id', 'CentOS')
with salt.utils.files.fopen('/etc/centos-release') as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r'\d+\.\d+')
find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains['lsb_distrib_release'] = release.group()
if codename is not None:
grains['lsb_distrib_codename'] = codename.group()
elif os.path.isfile('/etc.defaults/VERSION') \
and os.path.isfile('/etc.defaults/synoinfo.conf'):
grains['osfullname'] = 'Synology'
log.trace(
'Parsing Synology distrib info from /etc/.defaults/VERSION'
)
with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip('\n').split('=')
except ValueError:
continue
if key in ('majorversion', 'minorversion',
'buildnumber'):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
'Unable to determine Synology version info. '
'Please report this, as it is likely a bug.'
)
else:
grains['osrelease'] = (
'{majorversion}.{minorversion}-{buildnumber}'
.format(**synoinfo)
)
# Use the already intelligent platform module to get distro info
# (though apparently it's not intelligent enough to strip quotes)
log.trace(
'Getting OS name, release, and codename from '
'distro.linux_distribution()'
)
(osname, osrelease, oscodename) = \
[x.strip('"').strip("'") for x in
linux_distribution(supported_dists=_supported_dists)]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if 'osfullname' not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
grains['osfullname'] = 'nilrt'
else:
grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
if 'osrelease' not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
grains.pop('lsb_distrib_release', None)
grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
if 'Red Hat' in grains['oscodename']:
grains['oscodename'] = oscodename
distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(' ', '').lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if 'os' not in grains:
grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains['kernel'] == 'SunOS':
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index('_')+1:]
grains['os'] = grains['osfullname'] = 'SmartOS'
# store a parsed version of YYYY.MM.DD as osrelease
grains['osrelease'] = ".".join([
uname_v.split('T')[0][0:4],
uname_v.split('T')[0][4:6],
uname_v.split('T')[0][6:8],
])
# store a untouched copy of the timestamp in osrelease_stamp
grains['osrelease_stamp'] = uname_v
elif os.path.isfile('/etc/release'):
with salt.utils.files.fopen('/etc/release', 'r') as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
)
osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains['os'] = grains['osfullname'] = 'Solaris'
grains['osrelease'] = ''
else:
if development is not None:
osname = ' '.join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains['os'] = grains['osfullname'] = osname
if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
# Oracla Solars 11 and up have minor version in uname
grains['osrelease'] = uname_v
elif osname in ['OmniOS']:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains['osrelease'] = ".".join(osrelease)
grains['osrelease_stamp'] = uname_v
grains.update(_sunos_cpudata())
elif grains['kernel'] == 'VMkernel':
grains['os'] = 'ESXi'
elif grains['kernel'] == 'Darwin':
osrelease = __salt__['cmd.run']('sw_vers -productVersion')
osname = __salt__['cmd.run']('sw_vers -productName')
osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
grains['os'] = 'MacOS'
grains['os_family'] = 'MacOS'
grains['osfullname'] = "{0} {1}".format(osname, osrelease)
grains['osrelease'] = osrelease
grains['osbuild'] = osbuild
grains['init'] = 'launchd'
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains['kernel'] == 'AIX':
osrelease = __salt__['cmd.run']('oslevel')
osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
osname = __salt__['cmd.run']('uname')
grains['os'] = 'AIX'
grains['osfullname'] = osname
grains['osrelease'] = osrelease
grains['osrelease_techlevel'] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains['os'] = grains['kernel']
if grains['kernel'] == 'FreeBSD':
try:
grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
grains.update(_bsd_cpudata(grains))
if grains['kernel'] in ('OpenBSD', 'NetBSD'):
grains.update(_bsd_cpudata(grains))
grains['osrelease'] = grains['kernelrelease'].split('-')[0]
if grains['kernel'] == 'NetBSD':
grains.update(_netbsd_gpu_data())
if not grains['os']:
grains['os'] = 'Unknown {0}'.format(grains['kernel'])
grains['os_family'] = 'Unknown'
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
grains['os'])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get('os_family') == 'Debian':
osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
elif grains.get('os_family') in ['RedHat', 'Suse']:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
archinfo = {}
for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
if line.startswith('arch'):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains['cpuarch']
grains['osarch'] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get('osrelease', ''):
osrelease_info = grains['osrelease'].split('.')
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains['osrelease_info'] = tuple(osrelease_info)
try:
grains['osmajorrelease'] = int(grains['osrelease_info'][0])
except (IndexError, TypeError, ValueError):
log.debug(
'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
'The osmajorrelease grain will not be set.',
grains['osrelease_info']
)
os_name = grains['os' if grains.get('os') in (
'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
grains['osfinger'] = '{0}-{1}'.format(
os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])
return grains
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaultencoding']
) = locale.getdefaultlocale()
except Exception:
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains['locale_info']['defaultlanguage'] = 'unknown'
grains['locale_info']['defaultencoding'] = 'unknown'
grains['locale_info']['detectedencoding'] = __salt_system_encoding__
if _DATEUTIL_TZ:
grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
return grains
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')
__FQDN__ = 'localhost.localdomain'
grains['fqdn'] = __FQDN__
(grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]
return grains
def append_domain():
'''
Return append_domain if set
'''
grain = {}
if salt.utils.platform.is_proxy():
return grain
if 'append_domain' in __opts__:
grain['append_domain'] = __opts__['append_domain']
return grain
def ip_fqdn():
'''
Return ip address and FQDN grains
'''
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True)
ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()['fqdn']
for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')):
key = 'fqdn_ip' + ipv_num
if not ret['ipv' + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except socket.error:
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__['__role'] == 'master':
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
'second timeout when rendering grains. Set the dns or '
'/etc/hosts for IPv%s to clear this.',
ipv_num, _fqdn, timediff, ipv_num
)
ret[key] = []
return ret
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip_interfaces': ret}
def ip4_interfaces():
'''
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip4_interfaces': ret}
def ip6_interfaces():
'''
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get('inet6', []):
if 'address' in inet:
iface_ips.append(inet['address'])
for secondary in ifaces[face].get('secondary', []):
if 'address' in secondary:
iface_ips.append(secondary['address'])
ret[face] = iface_ips
return {'ip6_interfaces': ret}
def hwaddr_interfaces():
'''
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
'''
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if 'hwaddr' in ifaces[face]:
ret[face] = ifaces[face]['hwaddr']
return {'hwaddr_interfaces': ret}
def dns():
'''
Parse the resolver configuration file
.. versionadded:: 2016.3.0
'''
# Provides:
# dns
if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',
'sortlist'):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {'dns': resolv} if resolv else {}
def get_machine_id():
'''
Provide the machine-id for machine/virtualization combination
'''
# Provides:
# machine-id
if platform.system() == 'AIX':
return _aix_get_machine_id()
locations = ['/etc/machine-id', '/var/lib/dbus/machine-id']
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {'machine_id': machineid.read().strip()}
def cwd():
'''
Current working directory
'''
return {'cwd': os.getcwd()}
def path():
'''
Return the path
'''
# Provides:
# path
return {'path': os.environ.get('PATH', '').strip()}
def pythonversion():
'''
Return the Python version
'''
# Provides:
# pythonversion
return {'pythonversion': list(sys.version_info)}
def pythonpath():
'''
Return the Python path
'''
# Provides:
# pythonpath
return {'pythonpath': sys.path}
def pythonexecutable():
'''
Return the python executable in use
'''
# Provides:
# pythonexecutable
return {'pythonexecutable': sys.executable}
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
def saltversion():
'''
Return the version of salt
'''
# Provides:
# saltversion
from salt.version import __version__
return {'saltversion': __version__}
def zmqversion():
'''
Return the zeromq version
'''
# Provides:
# zmqversion
try:
import zmq
return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
'''
Return the version_info of salt
.. versionadded:: 0.17.0
'''
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {'saltversioninfo': list(__version_info__)}
def _hw_data(osdata):
'''
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
'''
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
'biosversion': 'bios_version',
'productname': 'product_name',
'manufacturer': 'sys_vendor',
'biosreleasedate': 'bios_date',
'uuid': 'product_uuid',
'serialnumber': 'product_serial'
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join('/sys/class/dmi/id', fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, 'r') as ifile:
grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
if key == 'uuid':
grains['uuid'] = grains['uuid'].lower()
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
salt.utils.platform.is_smartos() or
( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata['kernel'] == 'SunOS' and
osdata['cpuarch'].startswith('sparc')
)):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
'biosversion': __salt__['smbios.get']('bios-version'),
'productname': __salt__['smbios.get']('system-product-name'),
'manufacturer': __salt__['smbios.get']('system-manufacturer'),
'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
'uuid': __salt__['smbios.get']('system-uuid')
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__['smbios.get']('system-uuid')
if uuid is not None:
grains['uuid'] = uuid.lower()
for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
serial = __salt__['smbios.get'](serial)
if serial is not None:
grains['serialnumber'] = serial
break
elif salt.utils.path.which_bin(['fw_printenv']) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
'manufacturer': 'manufacturer',
'serialnumber': 'serial#',
'productname': 'DeviceDesc',
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
if result['retcode'] == 0:
uboot_keyval = result['stdout'].split('=')
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata['kernel'] == 'FreeBSD':
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which('kenv')
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
'biosversion': 'smbios.bios.version',
'manufacturer': 'smbios.system.maker',
'serialnumber': 'smbios.system.serial',
'productname': 'smbios.system.product',
'biosreleasedate': 'smbios.bios.reldate',
'uuid': 'smbios.system.uuid',
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'OpenBSD':
sysctl = salt.utils.path.which('sysctl')
hwdata = {'biosversion': 'hw.version',
'manufacturer': 'hw.vendor',
'productname': 'hw.product',
'serialnumber': 'hw.serialno',
'uuid': 'hw.uuid'}
for key, oid in six.iteritems(hwdata):
value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
if not value.endswith(' value is not available'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'NetBSD':
sysctl = salt.utils.path.which('sysctl')
nbsd_hwdata = {
'biosversion': 'machdep.dmi.board-version',
'manufacturer': 'machdep.dmi.system-vendor',
'serialnumber': 'machdep.dmi.system-serial',
'productname': 'machdep.dmi.system-product',
'biosreleasedate': 'machdep.dmi.bios-date',
'uuid': 'machdep.dmi.system-uuid',
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
if result['retcode'] == 0:
grains[key] = _clean_value(key, result['stdout'])
elif osdata['kernel'] == 'Darwin':
grains['manufacturer'] = 'Apple Inc.'
sysctl = salt.utils.path.which('sysctl')
hwdata = {'productname': 'hw.model'}
for key, oid in hwdata.items():
value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
if not value.endswith(' is invalid'):
grains[key] = _clean_value(key, value)
elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
data += '\n'
sn_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf
r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo
]
]
manufacture_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag
]
]
product_regexes = [
re.compile(r) for r in [
r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag
r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf
r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf
]
]
sn_regexes = [
re.compile(r) for r in [
r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag
r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo
r'(?i)chassis-sn:\s*(\S+)', # prtconf
]
]
obp_regexes = [
re.compile(r) for r in [
r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag
r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf
]
]
fw_regexes = [
re.compile(r) for r in [
r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag
]
]
uuid_regexes = [
re.compile(r) for r in [
r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo
]
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['serialnumber'] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places
grains['biosversion'] = obp_rev.strip().replace("'", "")
grains['biosreleasedate'] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains['systemfirmware'] = fw_rev.strip().replace("'", "")
grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['uuid'] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacture'] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains['product'] = t_productname
grains['productname'] = t_productname
break
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
elif osdata['kernel'] == 'AIX':
cmd = salt.utils.path.which('prtconf')
if data:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", '')
product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
break
else:
log.error('The \'prtconf\' binary was not found in $PATH.')
return grains
def _get_hash_by_shell():
'''
Shell-out Python 3 for compute reliable hash
:return:
'''
id_ = __opts__.get('id', '')
id_hash = None
py_ver = sys.version_info[:2]
if py_ver >= (3, 3):
# Python 3.3 enabled hash randomization, so we need to shell out to get
# a reliable hash.
id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
env={'PYTHONHASHSEED': '0'})
try:
id_hash = int(id_hash)
except (TypeError, ValueError):
log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
id_hash = None
if id_hash is None:
# Python < 3.3 or error encountered above
id_hash = hash(id_)
return abs(id_hash % (2 ** 31))
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts__.get('server_id_use_crc')
if bool(use_crc):
id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
else:
log.debug('This server_id is computed not by Adler32 nor by CRC32. '
'Please use "server_id_use_crc" option and define algorithm you '
'prefer (default "Adler32"). Starting with Sodium, the '
'server_id will be computed with Adler32 by default.')
id_hash = _get_hash_by_shell()
server_id = {'server_id': id_hash}
return server_id
def get_master():
'''
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
'''
# Provides:
# master
return {'master': __opts__.get('master', '')}
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
'''
grains = {}
ip_bin = salt.utils.path.which('ip')
if not ip_bin:
return {}
grains['ip_gw'] = False
grains['ip4_gw'] = False
grains['ip6_gw'] = False
for ip_version in ('4', '6'):
try:
out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show'])
for line in out.splitlines():
if line.startswith('default'):
grains['ip_gw'] = True
grains['ip{0}_gw'.format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == 'via':
grains['ip{0}_gw'.format(ip_version)] = gw_ip
break
except Exception:
continue
return grains
def kernelparams():
'''
Return the kernel boot parameters
'''
if salt.utils.platform.is_windows():
# TODO: add grains using `bcdedit /enum {current}`
return {}
else:
try:
with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr:
cmdline = fhr.read()
grains = {'kernelparams': []}
for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains['kernelparams'] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug('Failed to read /proc/cmdline: %s', exc)
return grains
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.