2013-10-31 21:52:37 +01:00
|
|
|
# Copyright (c), Michael DeHaan <michael.dehaan@gmail.com>, 2012-2013
|
2016-10-04 03:45:28 +02:00
|
|
|
# Copyright (c), Toshio Kuratomi <tkuratomi@ansible.com> 2016
|
2017-10-18 23:15:56 +02:00
|
|
|
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2018-05-13 23:12:12 +02:00
|
|
|
from __future__ import absolute_import, division, print_function
|
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
SIZE_RANGES = {
|
|
|
|
'Y': 1 << 80,
|
|
|
|
'Z': 1 << 70,
|
|
|
|
'E': 1 << 60,
|
|
|
|
'P': 1 << 50,
|
|
|
|
'T': 1 << 40,
|
|
|
|
'G': 1 << 30,
|
|
|
|
'M': 1 << 20,
|
|
|
|
'K': 1 << 10,
|
|
|
|
'B': 1,
|
|
|
|
}
|
2016-08-24 21:04:20 +02:00
|
|
|
|
2016-11-07 21:48:04 +01:00
|
|
|
FILE_ATTRIBUTES = {
|
2017-01-29 08:28:53 +01:00
|
|
|
'A': 'noatime',
|
|
|
|
'a': 'append',
|
|
|
|
'c': 'compressed',
|
|
|
|
'C': 'nocow',
|
|
|
|
'd': 'nodump',
|
|
|
|
'D': 'dirsync',
|
|
|
|
'e': 'extents',
|
|
|
|
'E': 'encrypted',
|
|
|
|
'h': 'blocksize',
|
|
|
|
'i': 'immutable',
|
|
|
|
'I': 'indexed',
|
|
|
|
'j': 'journalled',
|
|
|
|
'N': 'inline',
|
|
|
|
's': 'zero',
|
|
|
|
'S': 'synchronous',
|
|
|
|
't': 'notail',
|
|
|
|
'T': 'blockroot',
|
|
|
|
'u': 'undelete',
|
|
|
|
'X': 'compressedraw',
|
|
|
|
'Z': 'compresseddirty',
|
2016-11-07 21:48:04 +01:00
|
|
|
}
|
|
|
|
|
2018-01-16 06:15:04 +01:00
|
|
|
PASS_VARS = {
|
|
|
|
'check_mode': 'check_mode',
|
|
|
|
'debug': '_debug',
|
|
|
|
'diff': '_diff',
|
2018-05-15 01:31:21 +02:00
|
|
|
'keep_remote_files': '_keep_remote_files',
|
2018-01-16 06:15:04 +01:00
|
|
|
'module_name': '_name',
|
|
|
|
'no_log': 'no_log',
|
2018-05-15 01:31:21 +02:00
|
|
|
'remote_tmp': '_remote_tmp',
|
2018-01-16 06:15:04 +01:00
|
|
|
'selinux_special_fs': '_selinux_special_fs',
|
|
|
|
'shell_executable': '_shell',
|
|
|
|
'socket': '_socket_path',
|
|
|
|
'syslog_facility': '_syslog_facility',
|
2018-05-15 01:31:21 +02:00
|
|
|
'tmpdir': '_tmpdir',
|
2018-01-16 06:15:04 +01:00
|
|
|
'verbosity': '_verbosity',
|
|
|
|
'version': 'ansible_version',
|
|
|
|
}
|
|
|
|
|
|
|
|
PASS_BOOLS = ('no_log', 'debug', 'diff')
|
|
|
|
|
|
|
|
# Ansible modules can be written in any language.
|
|
|
|
# The functions available here can be used to do many common tasks,
|
|
|
|
# to simplify development of Python modules.
|
2013-10-31 21:52:37 +01:00
|
|
|
|
AnsiballZ improvements
Now that we don't need to worry about python-2.4 and 2.5, we can make
some improvements to the way AnsiballZ handles modules.
* Change AnsiballZ wrapper to use import to invoke the module
We need the module to think of itself as a script because it could be
coded as:
main()
or as:
if __name__ == '__main__':
main()
Or even as:
if __name__ == '__main__':
random_function_name()
A script will invoke all of those. Prior to this change, we invoked
a second Python interpreter on the module so that it really was
a script. However, this means that we have to run python twice (once
for the AnsiballZ wrapper and once for the module). This change makes
the module think that it is a script (because __name__ in the module ==
'__main__') but it's actually being invoked by us importing the module
code.
There's three ways we've come up to do this.
* The most elegant is to use zipimporter and tell the import mechanism
that the module being loaded is __main__:
* https://github.com/abadger/ansible/blob/5959f11c9ddb7b6eaa9c3214560bd85e631d4055/lib/ansible/executor/module_common.py#L175
* zipimporter is nice because we do not have to extract the module from
the zip file and save it to the disk when we do that. The import
machinery does it all for us.
* The drawback is that modules do not have a __file__ which points
to a real file when they do this. Modules could be using __file__
to for a variety of reasons, most of those probably have
replacements (the most common one is to find a writable directory
for temporary files. AnsibleModule.tmpdir should be used instead)
We can monkeypatch __file__ in fom AnsibleModule initialization
but that's kind of gross. There's no way I can see to do this
from the wrapper.
* Next, there's imp.load_module():
* https://github.com/abadger/ansible/blob/340edf7489/lib/ansible/executor/module_common.py#L151
* imp has the nice property of allowing us to set __name__ to
__main__ without changing the name of the file itself
* We also don't have to do anything special to set __file__ for
backwards compatibility (although the reason for that is the
drawback):
* Its drawback is that it requires the file to exist on disk so we
have to explicitly extract it from the zipfile and save it to
a temporary file
* The last choice is to use exec to execute the module:
* https://github.com/abadger/ansible/blob/f47a4ccc76/lib/ansible/executor/module_common.py#L175
* The code we would have to maintain for this looks pretty clean.
In the wrapper we create a ModuleType, set __file__ on it, read
the module's contents in from the zip file and then exec it.
* Drawbacks: We still have to explicitly extract the file's contents
from the zip archive instead of letting python's import mechanism
handle it.
* Exec also has hidden performance issues and breaks certain
assumptions that modules could be making about their own code:
http://lucumr.pocoo.org/2011/2/1/exec-in-python/
Our plan is to use imp.load_module() for now, deprecate the use of
__file__ in modules, and switch to zipimport once the deprecation
period for __file__ is over (without monkeypatching a fake __file__ in
via AnsibleModule).
* Rename the name of the AnsiBallZ wrapped module
This makes it obvious that the wrapped module isn't the module file that
we distribute. It's part of trying to mitigate the fact that the module
is now named __main)).py in tracebacks.
* Shield all wrapper symbols inside of a function
With the new import code, all symbols in the wrapper become visible in
the module. To mitigate the chance of collisions, move most symbols
into a toplevel function. The only symbols left in the global namespace
are now _ANSIBALLZ_WRAPPER and _ansiballz_main.
revised porting guide entry
Integrate code coverage collection into AnsiballZ.
ci_coverage
ci_complete
2018-06-20 20:23:59 +02:00
|
|
|
import __main__
|
2018-05-15 01:31:21 +02:00
|
|
|
import atexit
|
2014-05-19 17:26:06 +02:00
|
|
|
import locale
|
2013-10-31 21:52:37 +01:00
|
|
|
import os
|
|
|
|
import re
|
|
|
|
import shlex
|
2018-08-03 18:35:34 +02:00
|
|
|
import signal
|
2013-10-31 21:52:37 +01:00
|
|
|
import subprocess
|
|
|
|
import sys
|
|
|
|
import types
|
|
|
|
import time
|
2014-08-04 22:32:41 +02:00
|
|
|
import select
|
2013-10-31 21:52:37 +01:00
|
|
|
import shutil
|
|
|
|
import stat
|
2014-03-20 11:12:58 +01:00
|
|
|
import tempfile
|
2013-10-31 21:52:37 +01:00
|
|
|
import traceback
|
|
|
|
import grp
|
|
|
|
import pwd
|
|
|
|
import platform
|
|
|
|
import errno
|
2015-12-27 12:31:59 +01:00
|
|
|
import datetime
|
2018-09-17 12:28:41 +02:00
|
|
|
from collections import deque
|
2017-11-21 22:41:27 +01:00
|
|
|
from itertools import chain, repeat
|
2015-09-23 08:59:59 +02:00
|
|
|
|
2015-10-14 15:12:02 +02:00
|
|
|
try:
|
|
|
|
import syslog
|
2017-06-02 13:14:11 +02:00
|
|
|
HAS_SYSLOG = True
|
2015-10-14 15:12:02 +02:00
|
|
|
except ImportError:
|
2017-06-02 13:14:11 +02:00
|
|
|
HAS_SYSLOG = False
|
2015-10-14 15:12:02 +02:00
|
|
|
|
2015-09-23 08:59:59 +02:00
|
|
|
try:
|
2016-08-20 17:08:59 +02:00
|
|
|
from systemd import journal
|
|
|
|
has_journal = True
|
2015-09-23 08:59:59 +02:00
|
|
|
except ImportError:
|
2016-08-20 17:08:59 +02:00
|
|
|
has_journal = False
|
2016-03-01 22:55:01 +01:00
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
HAVE_SELINUX = False
|
2015-10-20 07:32:21 +02:00
|
|
|
try:
|
2016-08-20 17:08:59 +02:00
|
|
|
import selinux
|
2017-06-02 13:14:11 +02:00
|
|
|
HAVE_SELINUX = True
|
2016-08-20 17:08:59 +02:00
|
|
|
except ImportError:
|
|
|
|
pass
|
2015-10-20 07:32:21 +02:00
|
|
|
|
|
|
|
# Python2 & 3 way to get NoneType
|
|
|
|
NoneType = type(None)
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
try:
|
|
|
|
import json
|
2015-07-20 21:33:07 +02:00
|
|
|
# Detect the python-json library which is incompatible
|
|
|
|
try:
|
|
|
|
if not isinstance(json.loads, types.FunctionType) or not isinstance(json.dumps, types.FunctionType):
|
|
|
|
raise ImportError
|
|
|
|
except AttributeError:
|
|
|
|
raise ImportError
|
2013-10-31 21:52:37 +01:00
|
|
|
except ImportError:
|
2018-08-10 18:13:29 +02:00
|
|
|
print('\n{"msg": "Error: ansible requires the stdlib json and was not found!", "failed": true}')
|
|
|
|
sys.exit(1)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2015-08-06 23:39:31 +02:00
|
|
|
AVAILABLE_HASH_ALGORITHMS = dict()
|
|
|
|
try:
|
|
|
|
import hashlib
|
|
|
|
|
|
|
|
# python 2.7.9+ and 2.7.0+
|
|
|
|
for attribute in ('available_algorithms', 'algorithms'):
|
|
|
|
algorithms = getattr(hashlib, attribute, None)
|
|
|
|
if algorithms:
|
|
|
|
break
|
|
|
|
if algorithms is None:
|
|
|
|
# python 2.5+
|
|
|
|
algorithms = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
|
|
|
|
for algorithm in algorithms:
|
|
|
|
AVAILABLE_HASH_ALGORITHMS[algorithm] = getattr(hashlib, algorithm)
|
2018-08-23 08:34:50 +02:00
|
|
|
|
|
|
|
# we may have been able to import md5 but it could still not be available
|
|
|
|
try:
|
|
|
|
hashlib.md5()
|
|
|
|
except ValueError:
|
|
|
|
algorithms.pop('md5', None)
|
|
|
|
except Exception:
|
2015-08-06 23:39:31 +02:00
|
|
|
import sha
|
|
|
|
AVAILABLE_HASH_ALGORITHMS = {'sha1': sha.sha}
|
|
|
|
try:
|
|
|
|
import md5
|
|
|
|
AVAILABLE_HASH_ALGORITHMS['md5'] = md5.md5
|
2018-08-23 08:34:50 +02:00
|
|
|
except Exception:
|
2015-08-06 23:39:31 +02:00
|
|
|
pass
|
|
|
|
|
2018-05-22 20:46:36 +02:00
|
|
|
from ansible.module_utils.common._collections_compat import (
|
|
|
|
KeysView,
|
|
|
|
Mapping, MutableMapping,
|
|
|
|
Sequence, MutableSequence,
|
|
|
|
Set, MutableSet,
|
|
|
|
)
|
2018-07-31 19:04:05 +02:00
|
|
|
from ansible.module_utils.common.process import get_bin_path
|
2018-12-07 19:21:11 +01:00
|
|
|
from ansible.module_utils.common.file import (
|
|
|
|
_PERM_BITS as PERM_BITS,
|
|
|
|
_EXEC_PERM_BITS as EXEC_PERM_BITS,
|
|
|
|
_DEFAULT_PERM as DEFAULT_PERM,
|
|
|
|
is_executable,
|
|
|
|
format_attributes,
|
|
|
|
get_flags_from_attributes,
|
|
|
|
)
|
|
|
|
from ansible.module_utils.common.sys_info import (
|
|
|
|
get_platform,
|
|
|
|
get_distribution,
|
|
|
|
get_distribution_version,
|
|
|
|
load_platform_subclass,
|
|
|
|
get_all_subclasses,
|
|
|
|
)
|
2016-08-23 22:13:44 +02:00
|
|
|
from ansible.module_utils.pycompat24 import get_exception, literal_eval
|
2017-06-02 13:14:11 +02:00
|
|
|
from ansible.module_utils.six import (
|
|
|
|
PY2,
|
|
|
|
PY3,
|
|
|
|
b,
|
|
|
|
binary_type,
|
|
|
|
integer_types,
|
|
|
|
iteritems,
|
|
|
|
string_types,
|
|
|
|
text_type,
|
|
|
|
)
|
2017-04-18 15:53:54 +02:00
|
|
|
from ansible.module_utils.six.moves import map, reduce, shlex_quote
|
2016-08-26 10:30:46 +02:00
|
|
|
from ansible.module_utils._text import to_native, to_bytes, to_text
|
2018-07-02 16:27:16 +02:00
|
|
|
from ansible.module_utils.parsing.convert_bool import BOOLEANS, BOOLEANS_FALSE, BOOLEANS_TRUE, boolean
|
2017-07-15 01:44:58 +02:00
|
|
|
|
2016-05-14 16:51:13 +02:00
|
|
|
|
2018-05-22 20:46:36 +02:00
|
|
|
# Note: When getting Sequence from collections, it matches with strings. If
|
|
|
|
# this matters, make sure to check for strings before checking for sequencetype
|
|
|
|
SEQUENCETYPE = frozenset, KeysView, Sequence
|
|
|
|
|
2017-02-09 19:59:29 +01:00
|
|
|
PASSWORD_MATCH = re.compile(r'^(?:.+[-_\s])?pass(?:[-_\s]?(?:word|phrase|wrd|wd)?)(?:[-_\s].+)?$', re.I)
|
|
|
|
|
2016-08-20 17:08:59 +02:00
|
|
|
_NUMBERTYPES = tuple(list(integer_types) + [float])
|
|
|
|
|
|
|
|
# Deprecated compat. Only kept in case another module used these names Using
|
|
|
|
# ansible.module_utils.six is preferred
|
|
|
|
|
|
|
|
NUMBERTYPES = _NUMBERTYPES
|
|
|
|
|
|
|
|
imap = map
|
|
|
|
|
|
|
|
try:
|
|
|
|
# Python 2
|
|
|
|
unicode
|
|
|
|
except NameError:
|
|
|
|
# Python 3
|
|
|
|
unicode = text_type
|
|
|
|
|
|
|
|
try:
|
|
|
|
# Python 2
|
|
|
|
basestring
|
|
|
|
except NameError:
|
|
|
|
# Python 3
|
|
|
|
basestring = string_types
|
|
|
|
|
2016-08-23 22:13:44 +02:00
|
|
|
_literal_eval = literal_eval
|
|
|
|
|
2016-08-20 17:08:59 +02:00
|
|
|
# End of deprecated names
|
|
|
|
|
2016-05-18 19:50:55 +02:00
|
|
|
# Internal global holding passed in params. This is consulted in case
|
|
|
|
# multiple AnsibleModules are created. Otherwise each AnsibleModule would
|
|
|
|
# attempt to read from stdin. Other code should not use this directly as it
|
|
|
|
# is an internal implementation detail
|
2016-04-20 05:08:01 +02:00
|
|
|
_ANSIBLE_ARGS = None
|
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
FILE_COMMON_ARGUMENTS = dict(
|
2018-04-23 18:05:53 +02:00
|
|
|
# These are things we want. About setting metadata (mode, ownership, permissions in general) on
|
2018-05-11 05:28:27 +02:00
|
|
|
# created files (these are used by set_fs_attributes_if_different and included in
|
|
|
|
# load_file_common_arguments)
|
2017-06-02 13:14:11 +02:00
|
|
|
mode=dict(type='raw'),
|
|
|
|
owner=dict(),
|
|
|
|
group=dict(),
|
|
|
|
seuser=dict(),
|
|
|
|
serole=dict(),
|
|
|
|
selevel=dict(),
|
|
|
|
setype=dict(),
|
2018-04-23 18:05:53 +02:00
|
|
|
attributes=dict(aliases=['attr']),
|
|
|
|
|
|
|
|
# The following are not about perms and should not be in a rewritten file_common_args
|
|
|
|
src=dict(), # Maybe dest or path would be appropriate but src is not
|
2018-04-24 04:38:42 +02:00
|
|
|
follow=dict(type='bool', default=False), # Maybe follow is appropriate because it determines whether to follow symlinks for permission purposes too
|
2018-04-23 18:05:53 +02:00
|
|
|
force=dict(type='bool'),
|
|
|
|
|
|
|
|
# not taken by the file module, but other action plugins call the file module so this ignores
|
|
|
|
# them for now. In the future, the caller should take care of removing these from the module
|
2018-05-11 05:28:27 +02:00
|
|
|
# arguments before calling the file module.
|
2018-04-23 18:05:53 +02:00
|
|
|
content=dict(no_log=True), # used by copy
|
|
|
|
backup=dict(), # Used by a few modules to create a remote backup before updating the file
|
2017-06-02 13:14:11 +02:00
|
|
|
remote_src=dict(), # used by assemble
|
|
|
|
regexp=dict(), # used by assemble
|
|
|
|
delimiter=dict(), # used by assemble
|
|
|
|
directory_mode=dict(), # used by copy
|
|
|
|
unsafe_writes=dict(type='bool'), # should be available to any module using atomic_move
|
2013-10-31 21:52:37 +01:00
|
|
|
)
|
|
|
|
|
2015-02-09 19:13:13 +01:00
|
|
|
PASSWD_ARG_RE = re.compile(r'^[-]{0,2}pass[-]?(word|wd)?')
|
2014-03-10 22:06:52 +01:00
|
|
|
|
2017-07-22 15:47:57 +02:00
|
|
|
# Used for parsing symbolic file perms
|
|
|
|
MODE_OPERATOR_RE = re.compile(r'[+=-]')
|
|
|
|
USERS_RE = re.compile(r'[^ugo]')
|
|
|
|
PERMS_RE = re.compile(r'[^rwxXstugo]')
|
|
|
|
|
2018-01-09 23:17:55 +01:00
|
|
|
# Used for determining if the system is running a new enough python version
|
|
|
|
# and should only restrict on our documented minimum versions
|
|
|
|
_PY3_MIN = sys.version_info[:2] >= (3, 5)
|
|
|
|
_PY2_MIN = (2, 6) <= sys.version_info[:2] < (3,)
|
|
|
|
_PY_MIN = _PY3_MIN or _PY2_MIN
|
|
|
|
if not _PY_MIN:
|
|
|
|
print(
|
|
|
|
'\n{"failed": true, '
|
|
|
|
'"msg": "Ansible requires a minimum of Python2 version 2.6 or Python3 version 3.5. Current version: %s"}' % ''.join(sys.version.splitlines())
|
|
|
|
)
|
|
|
|
sys.exit(1)
|
|
|
|
|
2015-09-25 16:46:09 +02:00
|
|
|
|
2016-09-01 13:19:03 +02:00
|
|
|
def json_dict_unicode_to_bytes(d, encoding='utf-8', errors='surrogate_or_strict'):
|
2014-10-08 20:30:36 +02:00
|
|
|
''' Recursively convert dict keys and values to byte str
|
|
|
|
|
|
|
|
Specialized for json return because this only handles, lists, tuples,
|
|
|
|
and dict container types (the containers that the json module returns)
|
|
|
|
'''
|
|
|
|
|
2016-08-20 17:08:59 +02:00
|
|
|
if isinstance(d, text_type):
|
2016-09-01 13:19:03 +02:00
|
|
|
return to_bytes(d, encoding=encoding, errors=errors)
|
2014-10-08 20:30:36 +02:00
|
|
|
elif isinstance(d, dict):
|
2016-09-01 13:19:03 +02:00
|
|
|
return dict(map(json_dict_unicode_to_bytes, iteritems(d), repeat(encoding), repeat(errors)))
|
2014-10-08 20:30:36 +02:00
|
|
|
elif isinstance(d, list):
|
2016-09-01 13:19:03 +02:00
|
|
|
return list(map(json_dict_unicode_to_bytes, d, repeat(encoding), repeat(errors)))
|
2014-10-08 20:30:36 +02:00
|
|
|
elif isinstance(d, tuple):
|
2016-09-01 13:19:03 +02:00
|
|
|
return tuple(map(json_dict_unicode_to_bytes, d, repeat(encoding), repeat(errors)))
|
2014-10-08 20:30:36 +02:00
|
|
|
else:
|
|
|
|
return d
|
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
|
2016-09-01 13:19:03 +02:00
|
|
|
def json_dict_bytes_to_unicode(d, encoding='utf-8', errors='surrogate_or_strict'):
|
2015-01-27 05:37:20 +01:00
|
|
|
''' Recursively convert dict keys and values to byte str
|
|
|
|
|
|
|
|
Specialized for json return because this only handles, lists, tuples,
|
|
|
|
and dict container types (the containers that the json module returns)
|
|
|
|
'''
|
|
|
|
|
2016-08-20 17:08:59 +02:00
|
|
|
if isinstance(d, binary_type):
|
|
|
|
# Warning, can traceback
|
2016-09-01 13:19:03 +02:00
|
|
|
return to_text(d, encoding=encoding, errors=errors)
|
2015-01-27 05:37:20 +01:00
|
|
|
elif isinstance(d, dict):
|
2016-09-01 13:19:03 +02:00
|
|
|
return dict(map(json_dict_bytes_to_unicode, iteritems(d), repeat(encoding), repeat(errors)))
|
2015-01-27 05:37:20 +01:00
|
|
|
elif isinstance(d, list):
|
2016-09-01 13:19:03 +02:00
|
|
|
return list(map(json_dict_bytes_to_unicode, d, repeat(encoding), repeat(errors)))
|
2015-01-27 05:37:20 +01:00
|
|
|
elif isinstance(d, tuple):
|
2016-09-01 13:19:03 +02:00
|
|
|
return tuple(map(json_dict_bytes_to_unicode, d, repeat(encoding), repeat(errors)))
|
2015-01-27 05:37:20 +01:00
|
|
|
else:
|
|
|
|
return d
|
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
|
2015-10-21 03:51:34 +02:00
|
|
|
def return_values(obj):
|
2016-08-20 17:08:59 +02:00
|
|
|
""" Return native stringified values from datastructures.
|
|
|
|
|
|
|
|
For use with removing sensitive values pre-jsonification."""
|
|
|
|
if isinstance(obj, (text_type, binary_type)):
|
2015-10-21 03:51:34 +02:00
|
|
|
if obj:
|
2016-09-01 13:19:03 +02:00
|
|
|
yield to_native(obj, errors='surrogate_or_strict')
|
2015-10-21 03:51:34 +02:00
|
|
|
return
|
2016-05-23 21:17:28 +02:00
|
|
|
elif isinstance(obj, SEQUENCETYPE):
|
2015-10-21 03:51:34 +02:00
|
|
|
for element in obj:
|
|
|
|
for subelement in return_values(element):
|
|
|
|
yield subelement
|
|
|
|
elif isinstance(obj, Mapping):
|
|
|
|
for element in obj.items():
|
|
|
|
for subelement in return_values(element[1]):
|
|
|
|
yield subelement
|
|
|
|
elif isinstance(obj, (bool, NoneType)):
|
|
|
|
# This must come before int because bools are also ints
|
|
|
|
return
|
|
|
|
elif isinstance(obj, NUMBERTYPES):
|
2016-09-01 13:19:03 +02:00
|
|
|
yield to_native(obj, nonstring='simplerepr')
|
2015-10-21 03:51:34 +02:00
|
|
|
else:
|
|
|
|
raise TypeError('Unknown parameter type: %s, %s' % (type(obj), obj))
|
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
|
2017-05-21 15:18:35 +02:00
|
|
|
def _remove_values_conditions(value, no_log_strings, deferred_removals):
|
|
|
|
"""
|
|
|
|
Helper function for :meth:`remove_values`.
|
|
|
|
|
|
|
|
:arg value: The value to check for strings that need to be stripped
|
|
|
|
:arg no_log_strings: set of strings which must be stripped out of any values
|
|
|
|
:arg deferred_removals: List which holds information about nested
|
|
|
|
containers that have to be iterated for removals. It is passed into
|
|
|
|
this function so that more entries can be added to it if value is
|
|
|
|
a container type. The format of each entry is a 2-tuple where the first
|
|
|
|
element is the ``value`` parameter and the second value is a new
|
|
|
|
container to copy the elements of ``value`` into once iterated.
|
|
|
|
:returns: if ``value`` is a scalar, returns ``value`` with two exceptions:
|
|
|
|
1. :class:`~datetime.datetime` objects which are changed into a string representation.
|
|
|
|
2. objects which are in no_log_strings are replaced with a placeholder
|
|
|
|
so that no sensitive data is leaked.
|
|
|
|
If ``value`` is a container type, returns a new empty container.
|
|
|
|
|
|
|
|
``deferred_removals`` is added to as a side-effect of this function.
|
|
|
|
|
|
|
|
.. warning:: It is up to the caller to make sure the order in which value
|
|
|
|
is passed in is correct. For instance, higher level containers need
|
|
|
|
to be passed in before lower level containers. For example, given
|
|
|
|
``{'level1': {'level2': 'level3': [True]} }`` first pass in the
|
|
|
|
dictionary for ``level1``, then the dict for ``level2``, and finally
|
|
|
|
the list for ``level3``.
|
|
|
|
"""
|
2016-08-20 17:08:59 +02:00
|
|
|
if isinstance(value, (text_type, binary_type)):
|
|
|
|
# Need native str type
|
|
|
|
native_str_value = value
|
|
|
|
if isinstance(value, text_type):
|
|
|
|
value_is_text = True
|
|
|
|
if PY2:
|
2017-05-21 15:18:35 +02:00
|
|
|
native_str_value = to_bytes(value, errors='surrogate_or_strict')
|
2016-08-20 17:08:59 +02:00
|
|
|
elif isinstance(value, binary_type):
|
|
|
|
value_is_text = False
|
|
|
|
if PY3:
|
2017-05-21 15:18:35 +02:00
|
|
|
native_str_value = to_text(value, errors='surrogate_or_strict')
|
2016-08-20 17:08:59 +02:00
|
|
|
|
|
|
|
if native_str_value in no_log_strings:
|
2015-10-21 03:51:34 +02:00
|
|
|
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
|
|
|
|
for omit_me in no_log_strings:
|
2016-08-20 17:08:59 +02:00
|
|
|
native_str_value = native_str_value.replace(omit_me, '*' * 8)
|
|
|
|
|
|
|
|
if value_is_text and isinstance(native_str_value, binary_type):
|
2017-02-10 02:13:40 +01:00
|
|
|
value = to_text(native_str_value, encoding='utf-8', errors='surrogate_then_replace')
|
2016-08-20 17:08:59 +02:00
|
|
|
elif not value_is_text and isinstance(native_str_value, text_type):
|
2017-02-10 02:13:40 +01:00
|
|
|
value = to_bytes(native_str_value, encoding='utf-8', errors='surrogate_then_replace')
|
2015-12-03 05:52:58 +01:00
|
|
|
else:
|
2016-08-20 17:08:59 +02:00
|
|
|
value = native_str_value
|
2017-05-21 15:18:35 +02:00
|
|
|
|
|
|
|
elif isinstance(value, Sequence):
|
|
|
|
if isinstance(value, MutableSequence):
|
|
|
|
new_value = type(value)()
|
|
|
|
else:
|
|
|
|
new_value = [] # Need a mutable value
|
|
|
|
deferred_removals.append((value, new_value))
|
|
|
|
value = new_value
|
|
|
|
|
|
|
|
elif isinstance(value, Set):
|
|
|
|
if isinstance(value, MutableSet):
|
|
|
|
new_value = type(value)()
|
|
|
|
else:
|
|
|
|
new_value = set() # Need a mutable value
|
|
|
|
deferred_removals.append((value, new_value))
|
|
|
|
value = new_value
|
|
|
|
|
2015-10-21 03:51:34 +02:00
|
|
|
elif isinstance(value, Mapping):
|
2017-05-21 15:18:35 +02:00
|
|
|
if isinstance(value, MutableMapping):
|
|
|
|
new_value = type(value)()
|
|
|
|
else:
|
|
|
|
new_value = {} # Need a mutable value
|
|
|
|
deferred_removals.append((value, new_value))
|
|
|
|
value = new_value
|
|
|
|
|
2015-10-21 03:51:34 +02:00
|
|
|
elif isinstance(value, tuple(chain(NUMBERTYPES, (bool, NoneType)))):
|
2016-09-01 13:19:03 +02:00
|
|
|
stringy_value = to_native(value, encoding='utf-8', errors='surrogate_or_strict')
|
2015-10-21 03:51:34 +02:00
|
|
|
if stringy_value in no_log_strings:
|
|
|
|
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
|
|
|
|
for omit_me in no_log_strings:
|
|
|
|
if omit_me in stringy_value:
|
|
|
|
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
|
2017-05-21 15:18:35 +02:00
|
|
|
|
2015-12-27 12:31:59 +01:00
|
|
|
elif isinstance(value, datetime.datetime):
|
|
|
|
value = value.isoformat()
|
2015-10-21 03:51:34 +02:00
|
|
|
else:
|
|
|
|
raise TypeError('Value of unknown type: %s, %s' % (type(value), value))
|
2017-05-21 15:18:35 +02:00
|
|
|
|
2015-10-21 03:51:34 +02:00
|
|
|
return value
|
|
|
|
|
2015-12-27 12:31:59 +01:00
|
|
|
|
2017-05-21 15:18:35 +02:00
|
|
|
def remove_values(value, no_log_strings):
|
|
|
|
""" Remove strings in no_log_strings from value. If value is a container
|
|
|
|
type, then remove a lot more"""
|
|
|
|
deferred_removals = deque()
|
|
|
|
|
|
|
|
no_log_strings = [to_native(s, errors='surrogate_or_strict') for s in no_log_strings]
|
|
|
|
new_value = _remove_values_conditions(value, no_log_strings, deferred_removals)
|
|
|
|
|
|
|
|
while deferred_removals:
|
|
|
|
old_data, new_data = deferred_removals.popleft()
|
|
|
|
if isinstance(new_data, Mapping):
|
|
|
|
for old_key, old_elem in old_data.items():
|
|
|
|
new_elem = _remove_values_conditions(old_elem, no_log_strings, deferred_removals)
|
|
|
|
new_data[old_key] = new_elem
|
|
|
|
else:
|
|
|
|
for elem in old_data:
|
|
|
|
new_elem = _remove_values_conditions(elem, no_log_strings, deferred_removals)
|
|
|
|
if isinstance(new_data, MutableSequence):
|
|
|
|
new_data.append(new_elem)
|
|
|
|
elif isinstance(new_data, MutableSet):
|
|
|
|
new_data.add(new_elem)
|
|
|
|
else:
|
|
|
|
raise TypeError('Unknown container type encountered when removing private values from output')
|
|
|
|
|
|
|
|
return new_value
|
|
|
|
|
|
|
|
|
2015-10-21 03:51:34 +02:00
|
|
|
def heuristic_log_sanitize(data, no_log_values=None):
|
2015-02-09 19:13:13 +01:00
|
|
|
''' Remove strings that look like passwords from log messages '''
|
|
|
|
# Currently filters:
|
|
|
|
# user:pass@foo/whatever and http://username:pass@wherever/foo
|
|
|
|
# This code has false positives and consumes parts of logs that are
|
|
|
|
# not passwds
|
|
|
|
|
|
|
|
# begin: start of a passwd containing string
|
|
|
|
# end: end of a passwd containing string
|
|
|
|
# sep: char between user and passwd
|
|
|
|
# prev_begin: where in the overall string to start a search for
|
|
|
|
# a passwd
|
|
|
|
# sep_search_end: where in the string to end a search for the sep
|
Fix errors when using -vvvv with python 3 (#17186)
Traceback (most recent call last):
File "/tmp/ansible_tpehdgt7/ansible_module_setup.py", line 134, in <module>
main()
File "/tmp/ansible_tpehdgt7/ansible_module_setup.py", line 124, in main
supports_check_mode = True,
File "/tmp/ansible_tpehdgt7/ansible_modlib.zip/ansible/module_utils/basic.py", line 696, in __init__
File "/tmp/ansible_tpehdgt7/ansible_modlib.zip/ansible/module_utils/basic.py", line 1670, in _log_invocation
File "/tmp/ansible_tpehdgt7/ansible_modlib.zip/ansible/module_utils/basic.py", line 469, in heuristic_log_sanitize
TypeError: 'str' does not support the buffer interface
2016-08-23 15:38:04 +02:00
|
|
|
data = to_native(data)
|
|
|
|
|
2015-02-09 19:13:13 +01:00
|
|
|
output = []
|
|
|
|
begin = len(data)
|
|
|
|
prev_begin = begin
|
|
|
|
sep = 1
|
|
|
|
while sep:
|
|
|
|
# Find the potential end of a passwd
|
|
|
|
try:
|
|
|
|
end = data.rindex('@', 0, begin)
|
|
|
|
except ValueError:
|
|
|
|
# No passwd in the rest of the data
|
|
|
|
output.insert(0, data[0:begin])
|
|
|
|
break
|
|
|
|
|
|
|
|
# Search for the beginning of a passwd
|
|
|
|
sep = None
|
|
|
|
sep_search_end = end
|
|
|
|
while not sep:
|
|
|
|
# URL-style username+password
|
|
|
|
try:
|
|
|
|
begin = data.rindex('://', 0, sep_search_end)
|
|
|
|
except ValueError:
|
|
|
|
# No url style in the data, check for ssh style in the
|
|
|
|
# rest of the string
|
|
|
|
begin = 0
|
|
|
|
# Search for separator
|
|
|
|
try:
|
|
|
|
sep = data.index(':', begin + 3, end)
|
|
|
|
except ValueError:
|
|
|
|
# No separator; choices:
|
|
|
|
if begin == 0:
|
|
|
|
# Searched the whole string so there's no password
|
|
|
|
# here. Return the remaining data
|
|
|
|
output.insert(0, data[0:begin])
|
|
|
|
break
|
|
|
|
# Search for a different beginning of the password field.
|
|
|
|
sep_search_end = begin
|
|
|
|
continue
|
|
|
|
if sep:
|
|
|
|
# Password was found; remove it.
|
|
|
|
output.insert(0, data[end:prev_begin])
|
|
|
|
output.insert(0, '********')
|
|
|
|
output.insert(0, data[begin:sep + 1])
|
|
|
|
prev_begin = begin
|
|
|
|
|
2015-10-21 03:51:34 +02:00
|
|
|
output = ''.join(output)
|
|
|
|
if no_log_values:
|
|
|
|
output = remove_values(output, no_log_values)
|
|
|
|
return output
|
2014-10-08 20:30:36 +02:00
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
|
2016-08-24 21:04:20 +02:00
|
|
|
def bytes_to_human(size, isbits=False, unit=None):
|
|
|
|
|
|
|
|
base = 'Bytes'
|
|
|
|
if isbits:
|
|
|
|
base = 'bits'
|
|
|
|
suffix = ''
|
|
|
|
|
|
|
|
for suffix, limit in sorted(iteritems(SIZE_RANGES), key=lambda item: -item[1]):
|
|
|
|
if (unit is None and size >= limit) or unit is not None and unit.upper() == suffix[0]:
|
|
|
|
break
|
|
|
|
|
|
|
|
if limit != 1:
|
|
|
|
suffix += base[0]
|
|
|
|
else:
|
|
|
|
suffix = base
|
|
|
|
|
2018-05-13 23:12:12 +02:00
|
|
|
return '%.2f %s' % (size / limit, suffix)
|
2017-06-02 13:14:11 +02:00
|
|
|
|
2016-08-24 21:04:20 +02:00
|
|
|
|
|
|
|
def human_to_bytes(number, default_unit=None, isbits=False):
|
|
|
|
|
|
|
|
'''
|
|
|
|
Convert number in string format into bytes (ex: '2K' => 2048) or using unit argument
|
|
|
|
ex:
|
|
|
|
human_to_bytes('10M') <=> human_to_bytes(10, 'M')
|
|
|
|
'''
|
2017-11-21 04:08:30 +01:00
|
|
|
m = re.search(r'^\s*(\d*\.?\d*)\s*([A-Za-z]+)?', str(number), flags=re.IGNORECASE)
|
2016-08-24 21:04:20 +02:00
|
|
|
if m is None:
|
|
|
|
raise ValueError("human_to_bytes() can't interpret following string: %s" % str(number))
|
|
|
|
try:
|
|
|
|
num = float(m.group(1))
|
|
|
|
except:
|
|
|
|
raise ValueError("human_to_bytes() can't interpret following number: %s (original input string: %s)" % (m.group(1), number))
|
|
|
|
|
|
|
|
unit = m.group(2)
|
|
|
|
if unit is None:
|
|
|
|
unit = default_unit
|
|
|
|
|
|
|
|
if unit is None:
|
|
|
|
''' No unit given, returning raw number '''
|
|
|
|
return int(round(num))
|
|
|
|
range_key = unit[0].upper()
|
|
|
|
try:
|
|
|
|
limit = SIZE_RANGES[range_key]
|
|
|
|
except:
|
|
|
|
raise ValueError("human_to_bytes() failed to convert %s (unit = %s). The suffix must be one of %s" % (number, unit, ", ".join(SIZE_RANGES.keys())))
|
|
|
|
|
|
|
|
# default value
|
|
|
|
unit_class = 'B'
|
|
|
|
unit_class_name = 'byte'
|
|
|
|
# handling bits case
|
|
|
|
if isbits:
|
|
|
|
unit_class = 'b'
|
|
|
|
unit_class_name = 'bit'
|
|
|
|
# check unit value if more than one character (KB, MB)
|
|
|
|
if len(unit) > 1:
|
|
|
|
expect_message = 'expect %s%s or %s' % (range_key, unit_class, range_key)
|
|
|
|
if range_key == 'B':
|
|
|
|
expect_message = 'expect %s or %s' % (unit_class, unit_class_name)
|
|
|
|
|
|
|
|
if unit_class_name in unit.lower():
|
|
|
|
pass
|
|
|
|
elif unit[1] != unit_class:
|
|
|
|
raise ValueError("human_to_bytes() failed to convert %s. Value is not a valid string (%s)" % (number, expect_message))
|
|
|
|
|
|
|
|
return int(round(num * limit))
|
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
|
2016-05-18 19:50:55 +02:00
|
|
|
def _load_params():
|
|
|
|
''' read the modules parameters and store them globally.
|
2015-09-25 16:46:09 +02:00
|
|
|
|
2016-05-18 19:50:55 +02:00
|
|
|
This function may be needed for certain very dynamic custom modules which
|
|
|
|
want to process the parameters that are being handed the module. Since
|
|
|
|
this is so closely tied to the implementation of modules we cannot
|
|
|
|
guarantee API stability for it (it may change between versions) however we
|
|
|
|
will try not to break it gratuitously. It is certainly more future-proof
|
|
|
|
to call this function and consume its outputs than to implement the logic
|
|
|
|
inside it as a copy in your own code.
|
|
|
|
'''
|
|
|
|
global _ANSIBLE_ARGS
|
|
|
|
if _ANSIBLE_ARGS is not None:
|
|
|
|
buffer = _ANSIBLE_ARGS
|
|
|
|
else:
|
|
|
|
# debug overrides to read args from file or cmdline
|
|
|
|
|
|
|
|
# Avoid tracebacks when locale is non-utf8
|
|
|
|
# We control the args and we pass them as utf8
|
|
|
|
if len(sys.argv) > 1:
|
|
|
|
if os.path.isfile(sys.argv[1]):
|
|
|
|
fd = open(sys.argv[1], 'rb')
|
|
|
|
buffer = fd.read()
|
|
|
|
fd.close()
|
|
|
|
else:
|
|
|
|
buffer = sys.argv[1]
|
2016-06-05 01:19:57 +02:00
|
|
|
if PY3:
|
2016-05-18 19:50:55 +02:00
|
|
|
buffer = buffer.encode('utf-8', errors='surrogateescape')
|
|
|
|
# default case, read from stdin
|
|
|
|
else:
|
2016-06-05 01:19:57 +02:00
|
|
|
if PY2:
|
2016-05-18 19:50:55 +02:00
|
|
|
buffer = sys.stdin.read()
|
|
|
|
else:
|
|
|
|
buffer = sys.stdin.buffer.read()
|
|
|
|
_ANSIBLE_ARGS = buffer
|
|
|
|
|
|
|
|
try:
|
|
|
|
params = json.loads(buffer.decode('utf-8'))
|
|
|
|
except ValueError:
|
|
|
|
# This helper used too early for fail_json to work.
|
|
|
|
print('\n{"msg": "Error: Module unable to decode valid JSON on stdin. Unable to figure out what parameters were passed", "failed": true}')
|
|
|
|
sys.exit(1)
|
|
|
|
|
2016-06-05 01:19:57 +02:00
|
|
|
if PY2:
|
2016-05-18 19:50:55 +02:00
|
|
|
params = json_dict_unicode_to_bytes(params)
|
|
|
|
|
|
|
|
try:
|
|
|
|
return params['ANSIBLE_MODULE_ARGS']
|
|
|
|
except KeyError:
|
|
|
|
# This helper does not have access to fail_json so we have to print
|
|
|
|
# json output on our own.
|
2017-03-23 02:50:28 +01:00
|
|
|
print('\n{"msg": "Error: Module unable to locate ANSIBLE_MODULE_ARGS in json data from stdin. Unable to figure out what parameters were passed", '
|
|
|
|
'"failed": true}')
|
2016-05-18 19:50:55 +02:00
|
|
|
sys.exit(1)
|
2016-03-31 20:17:49 +02:00
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
|
2016-03-31 20:17:49 +02:00
|
|
|
def env_fallback(*args, **kwargs):
|
|
|
|
''' Load value from environment '''
|
|
|
|
for arg in args:
|
|
|
|
if arg in os.environ:
|
|
|
|
return os.environ[arg]
|
2017-09-19 08:20:32 +02:00
|
|
|
raise AnsibleFallbackNotFound
|
2016-03-31 20:17:49 +02:00
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
|
2016-08-05 15:49:34 +02:00
|
|
|
def _lenient_lowercase(lst):
|
|
|
|
"""Lowercase elements of a list.
|
|
|
|
|
|
|
|
If an element is not a string, pass it through untouched.
|
|
|
|
"""
|
|
|
|
lowered = []
|
|
|
|
for value in lst:
|
|
|
|
try:
|
|
|
|
lowered.append(value.lower())
|
|
|
|
except AttributeError:
|
|
|
|
lowered.append(value)
|
|
|
|
return lowered
|
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
|
2017-11-21 22:41:27 +01:00
|
|
|
def _json_encode_fallback(obj):
|
|
|
|
if isinstance(obj, Set):
|
|
|
|
return list(obj)
|
|
|
|
elif isinstance(obj, datetime.datetime):
|
|
|
|
return obj.isoformat()
|
|
|
|
raise TypeError("Cannot json serialize %s" % to_native(obj))
|
2016-05-18 19:50:55 +02:00
|
|
|
|
|
|
|
|
2017-11-21 22:41:27 +01:00
|
|
|
def jsonify(data, **kwargs):
|
|
|
|
for encoding in ("utf-8", "latin-1"):
|
|
|
|
try:
|
|
|
|
return json.dumps(data, encoding=encoding, default=_json_encode_fallback, **kwargs)
|
|
|
|
# Old systems using old simplejson module does not support encoding keyword.
|
|
|
|
except TypeError:
|
|
|
|
try:
|
|
|
|
new_data = json_dict_bytes_to_unicode(data, encoding=encoding)
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
continue
|
|
|
|
return json.dumps(new_data, default=_json_encode_fallback, **kwargs)
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
continue
|
|
|
|
raise UnicodeError('Invalid unicode encoding encountered')
|
|
|
|
|
|
|
|
|
2018-10-23 23:21:36 +02:00
|
|
|
def missing_required_lib(library):
|
|
|
|
hostname = platform.node()
|
|
|
|
return "Failed to import the required Python library (%s) on %s's Python %s. Please read module documentation " \
|
|
|
|
"and install in the appropriate location." % (library, hostname, sys.executable)
|
|
|
|
|
|
|
|
|
2017-11-21 22:41:27 +01:00
|
|
|
class AnsibleFallbackNotFound(Exception):
|
|
|
|
pass
|
2017-05-21 22:56:59 +02:00
|
|
|
|
|
|
|
|
2015-09-25 16:46:09 +02:00
|
|
|
class AnsibleModule(object):
|
2013-10-31 21:52:37 +01:00
|
|
|
def __init__(self, argument_spec, bypass_checks=False, no_log=False,
|
2017-12-19 23:36:02 +01:00
|
|
|
check_invalid_arguments=None, mutually_exclusive=None, required_together=None,
|
2017-03-22 03:19:40 +01:00
|
|
|
required_one_of=None, add_file_common_args=False, supports_check_mode=False,
|
|
|
|
required_if=None):
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
'''
|
|
|
|
common code for quickly building an ansible module in Python
|
|
|
|
(although you can write modules in anything that can return JSON)
|
|
|
|
see library/* for examples
|
|
|
|
'''
|
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
self._name = os.path.basename(__file__) # initialize name until we can parse from options
|
2013-10-31 21:52:37 +01:00
|
|
|
self.argument_spec = argument_spec
|
|
|
|
self.supports_check_mode = supports_check_mode
|
|
|
|
self.check_mode = False
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
self.bypass_checks = bypass_checks
|
2014-01-31 23:09:10 +01:00
|
|
|
self.no_log = no_log
|
2017-12-19 23:36:02 +01:00
|
|
|
|
|
|
|
# Check whether code set this explicitly for deprecation purposes
|
|
|
|
if check_invalid_arguments is None:
|
|
|
|
check_invalid_arguments = True
|
|
|
|
module_set_check_invalid_arguments = False
|
|
|
|
else:
|
|
|
|
module_set_check_invalid_arguments = True
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
self.check_invalid_arguments = check_invalid_arguments
|
2017-12-19 23:36:02 +01:00
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
self.mutually_exclusive = mutually_exclusive
|
|
|
|
self.required_together = required_together
|
|
|
|
self.required_one_of = required_one_of
|
|
|
|
self.required_if = required_if
|
2014-05-13 20:52:38 +02:00
|
|
|
self.cleanup_files = []
|
2015-10-01 06:09:15 +02:00
|
|
|
self._debug = False
|
2016-01-12 19:17:02 +01:00
|
|
|
self._diff = False
|
2017-02-09 20:05:54 +01:00
|
|
|
self._socket_path = None
|
2017-10-05 17:02:41 +02:00
|
|
|
self._shell = None
|
2016-01-12 19:17:02 +01:00
|
|
|
self._verbosity = 0
|
2016-02-07 21:45:03 +01:00
|
|
|
# May be used to set modifications to the environment for any
|
|
|
|
# run_command invocation
|
|
|
|
self.run_command_environ_update = {}
|
2016-11-17 03:29:30 +01:00
|
|
|
self._warnings = []
|
|
|
|
self._deprecations = []
|
2017-10-06 00:12:02 +02:00
|
|
|
self._clean = {}
|
2015-06-29 17:05:58 +02:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
self.aliases = {}
|
2018-01-16 06:15:04 +01:00
|
|
|
self._legal_inputs = ['_ansible_%s' % k for k in PASS_VARS]
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
self._options_context = list()
|
2018-05-15 01:31:21 +02:00
|
|
|
self._tmpdir = None
|
2015-06-29 17:05:58 +02:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
if add_file_common_args:
|
2015-09-30 08:09:25 +02:00
|
|
|
for k, v in FILE_COMMON_ARGUMENTS.items():
|
2013-10-31 21:52:37 +01:00
|
|
|
if k not in self.argument_spec:
|
|
|
|
self.argument_spec[k] = v
|
|
|
|
|
2016-04-05 20:06:17 +02:00
|
|
|
self._load_params()
|
2016-03-31 20:17:49 +02:00
|
|
|
self._set_fallbacks()
|
2015-10-21 03:51:34 +02:00
|
|
|
|
2015-12-22 23:15:58 +01:00
|
|
|
# append to legal_inputs and then possibly check against them
|
|
|
|
try:
|
|
|
|
self.aliases = self._handle_aliases()
|
2017-08-12 05:23:17 +02:00
|
|
|
except Exception as e:
|
2016-03-23 09:22:18 +01:00
|
|
|
# Use exceptions here because it isn't safe to call fail_json until no_log is processed
|
2017-08-12 05:23:17 +02:00
|
|
|
print('\n{"failed": true, "msg": "Module alias error: %s"}' % to_native(e))
|
2015-12-22 23:15:58 +01:00
|
|
|
sys.exit(1)
|
|
|
|
|
2015-10-21 03:51:34 +02:00
|
|
|
# Save parameter values that should never be logged
|
|
|
|
self.no_log_values = set()
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
self._handle_no_log_values()
|
2017-02-01 19:00:22 +01:00
|
|
|
|
2016-01-20 18:04:44 +01:00
|
|
|
# check the locale as set by the current environment, and reset to
|
|
|
|
# a known valid (LANG=C) if it's an invalid/unavailable locale
|
2014-05-19 17:26:06 +02:00
|
|
|
self._check_locale()
|
|
|
|
|
2015-09-26 05:57:03 +02:00
|
|
|
self._check_arguments(check_invalid_arguments)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2015-09-26 05:57:03 +02:00
|
|
|
# check exclusive early
|
2014-02-07 19:42:08 +01:00
|
|
|
if not bypass_checks:
|
|
|
|
self._check_mutually_exclusive(mutually_exclusive)
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
self._set_defaults(pre=True)
|
|
|
|
|
2015-06-29 17:05:58 +02:00
|
|
|
self._CHECK_ARGUMENT_TYPES_DISPATCHER = {
|
2017-01-29 08:28:53 +01:00
|
|
|
'str': self._check_type_str,
|
|
|
|
'list': self._check_type_list,
|
|
|
|
'dict': self._check_type_dict,
|
|
|
|
'bool': self._check_type_bool,
|
|
|
|
'int': self._check_type_int,
|
|
|
|
'float': self._check_type_float,
|
|
|
|
'path': self._check_type_path,
|
|
|
|
'raw': self._check_type_raw,
|
|
|
|
'jsonarg': self._check_type_jsonarg,
|
|
|
|
'json': self._check_type_jsonarg,
|
|
|
|
'bytes': self._check_type_bytes,
|
|
|
|
'bits': self._check_type_bits,
|
|
|
|
}
|
2013-10-31 21:52:37 +01:00
|
|
|
if not bypass_checks:
|
|
|
|
self._check_required_arguments()
|
|
|
|
self._check_argument_types()
|
2015-07-06 01:55:11 +02:00
|
|
|
self._check_argument_values()
|
2013-10-31 21:52:37 +01:00
|
|
|
self._check_required_together(required_together)
|
|
|
|
self._check_required_one_of(required_one_of)
|
2014-10-26 18:41:58 +01:00
|
|
|
self._check_required_if(required_if)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
self._set_defaults(pre=False)
|
2015-10-21 03:51:34 +02:00
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
# deal with options sub-spec
|
|
|
|
self._handle_options()
|
|
|
|
|
2016-11-29 22:43:29 +01:00
|
|
|
if not self.no_log:
|
2013-10-31 21:52:37 +01:00
|
|
|
self._log_invocation()
|
|
|
|
|
2014-03-18 16:17:44 +01:00
|
|
|
# finally, make sure we're in a sane working dir
|
|
|
|
self._set_cwd()
|
|
|
|
|
2017-12-19 23:36:02 +01:00
|
|
|
# Do this at the end so that logging parameters have been set up
|
|
|
|
# This is to warn third party module authors that the functionatlity is going away.
|
|
|
|
# We exclude uri and zfs as they have their own deprecation warnings for users and we'll
|
|
|
|
# make sure to update their code to stop using check_invalid_arguments when 2.9 rolls around
|
|
|
|
if module_set_check_invalid_arguments and self._name not in ('uri', 'zfs'):
|
|
|
|
self.deprecate('Setting check_invalid_arguments is deprecated and will be removed.'
|
|
|
|
' Update the code for this module In the future, AnsibleModule will'
|
|
|
|
' always check for invalid arguments.', version='2.9')
|
|
|
|
|
2018-05-15 01:31:21 +02:00
|
|
|
@property
|
|
|
|
def tmpdir(self):
|
2018-07-06 19:49:19 +02:00
|
|
|
# if _ansible_tmpdir was not set and we have a remote_tmp,
|
|
|
|
# the module needs to create it and clean it up once finished.
|
|
|
|
# otherwise we create our own module tmp dir from the system defaults
|
2018-05-15 01:31:21 +02:00
|
|
|
if self._tmpdir is None:
|
2018-07-06 19:49:19 +02:00
|
|
|
basedir = None
|
|
|
|
|
2018-05-15 01:31:21 +02:00
|
|
|
basedir = os.path.expanduser(os.path.expandvars(self._remote_tmp))
|
2018-05-17 01:52:46 +02:00
|
|
|
if not os.path.exists(basedir):
|
2018-07-06 19:49:19 +02:00
|
|
|
try:
|
|
|
|
os.makedirs(basedir, mode=0o700)
|
|
|
|
except (OSError, IOError) as e:
|
|
|
|
self.warn("Unable to use %s as temporary directory, "
|
|
|
|
"failing back to system: %s" % (basedir, to_native(e)))
|
|
|
|
basedir = None
|
|
|
|
else:
|
|
|
|
self.warn("Module remote_tmp %s did not exist and was "
|
|
|
|
"created with a mode of 0700, this may cause"
|
|
|
|
" issues when running as another user. To "
|
|
|
|
"avoid this, create the remote_tmp dir with "
|
|
|
|
"the correct permissions manually" % basedir)
|
2018-05-17 01:52:46 +02:00
|
|
|
|
2018-05-15 01:31:21 +02:00
|
|
|
basefile = "ansible-moduletmp-%s-" % time.time()
|
2018-07-06 19:49:19 +02:00
|
|
|
try:
|
|
|
|
tmpdir = tempfile.mkdtemp(prefix=basefile, dir=basedir)
|
|
|
|
except (OSError, IOError) as e:
|
|
|
|
self.fail_json(
|
|
|
|
msg="Failed to create remote module tmp path at dir %s "
|
|
|
|
"with prefix %s: %s" % (basedir, basefile, to_native(e))
|
|
|
|
)
|
2018-05-15 01:31:21 +02:00
|
|
|
if not self._keep_remote_files:
|
|
|
|
atexit.register(shutil.rmtree, tmpdir)
|
|
|
|
self._tmpdir = tmpdir
|
|
|
|
|
|
|
|
return self._tmpdir
|
|
|
|
|
2016-11-17 03:29:30 +01:00
|
|
|
def warn(self, warning):
|
|
|
|
|
|
|
|
if isinstance(warning, string_types):
|
|
|
|
self._warnings.append(warning)
|
|
|
|
self.log('[WARNING] %s' % warning)
|
|
|
|
else:
|
|
|
|
raise TypeError("warn requires a string not a %s" % type(warning))
|
|
|
|
|
2017-02-01 19:00:22 +01:00
|
|
|
def deprecate(self, msg, version=None):
|
|
|
|
if isinstance(msg, string_types):
|
|
|
|
self._deprecations.append({
|
|
|
|
'msg': msg,
|
|
|
|
'version': version
|
|
|
|
})
|
|
|
|
self.log('[DEPRECATION WARNING] %s %s' % (msg, version))
|
2016-11-17 03:29:30 +01:00
|
|
|
else:
|
2017-02-01 19:00:22 +01:00
|
|
|
raise TypeError("deprecate requires a string not a %s" % type(msg))
|
2016-11-17 03:29:30 +01:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
def load_file_common_arguments(self, params):
|
|
|
|
'''
|
|
|
|
many modules deal with files, this encapsulates common
|
|
|
|
options that the file module accepts such that it is directly
|
|
|
|
available to all modules and they can share code.
|
|
|
|
'''
|
|
|
|
|
|
|
|
path = params.get('path', params.get('dest', None))
|
|
|
|
if path is None:
|
|
|
|
return {}
|
|
|
|
else:
|
2016-09-01 13:19:03 +02:00
|
|
|
path = os.path.expanduser(os.path.expandvars(path))
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2016-09-01 13:19:03 +02:00
|
|
|
b_path = to_bytes(path, errors='surrogate_or_strict')
|
2014-09-16 19:03:40 +02:00
|
|
|
# if the path is a symlink, and we're following links, get
|
|
|
|
# the target of the link instead for testing
|
2016-09-01 13:19:03 +02:00
|
|
|
if params.get('follow', False) and os.path.islink(b_path):
|
|
|
|
b_path = os.path.realpath(b_path)
|
|
|
|
path = to_native(b_path)
|
2014-09-16 19:03:40 +02:00
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
mode = params.get('mode', None)
|
|
|
|
owner = params.get('owner', None)
|
|
|
|
group = params.get('group', None)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
# selinux related options
|
2017-06-02 13:14:11 +02:00
|
|
|
seuser = params.get('seuser', None)
|
|
|
|
serole = params.get('serole', None)
|
|
|
|
setype = params.get('setype', None)
|
|
|
|
selevel = params.get('selevel', None)
|
2013-10-31 21:52:37 +01:00
|
|
|
secontext = [seuser, serole, setype]
|
|
|
|
|
|
|
|
if self.selinux_mls_enabled():
|
|
|
|
secontext.append(selevel)
|
|
|
|
|
|
|
|
default_secontext = self.selinux_default_context(path)
|
|
|
|
for i in range(len(default_secontext)):
|
|
|
|
if i is not None and secontext[i] == '_default':
|
|
|
|
secontext[i] = default_secontext[i]
|
|
|
|
|
2016-11-07 21:48:04 +01:00
|
|
|
attributes = params.get('attributes', None)
|
2013-10-31 21:52:37 +01:00
|
|
|
return dict(
|
|
|
|
path=path, mode=mode, owner=owner, group=group,
|
|
|
|
seuser=seuser, serole=serole, setype=setype,
|
2016-11-07 21:48:04 +01:00
|
|
|
selevel=selevel, secontext=secontext, attributes=attributes,
|
2013-10-31 21:52:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
# Detect whether using selinux that is MLS-aware.
|
|
|
|
# While this means you can set the level/range with
|
|
|
|
# selinux.lsetfilecon(), it may or may not mean that you
|
|
|
|
# will get the selevel as part of the context returned
|
|
|
|
# by selinux.lgetfilecon().
|
|
|
|
|
|
|
|
def selinux_mls_enabled(self):
|
|
|
|
if not HAVE_SELINUX:
|
|
|
|
return False
|
|
|
|
if selinux.is_selinux_mls_enabled() == 1:
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
|
|
|
def selinux_enabled(self):
|
|
|
|
if not HAVE_SELINUX:
|
|
|
|
seenabled = self.get_bin_path('selinuxenabled')
|
|
|
|
if seenabled is not None:
|
2017-06-02 13:14:11 +02:00
|
|
|
(rc, out, err) = self.run_command(seenabled)
|
2013-10-31 21:52:37 +01:00
|
|
|
if rc == 0:
|
|
|
|
self.fail_json(msg="Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!")
|
|
|
|
return False
|
|
|
|
if selinux.is_selinux_enabled() == 1:
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
|
|
|
# Determine whether we need a placeholder for selevel/mls
|
|
|
|
def selinux_initial_context(self):
|
|
|
|
context = [None, None, None]
|
|
|
|
if self.selinux_mls_enabled():
|
|
|
|
context.append(None)
|
|
|
|
return context
|
|
|
|
|
|
|
|
# If selinux fails to find a default, return an array of None
|
|
|
|
def selinux_default_context(self, path, mode=0):
|
|
|
|
context = self.selinux_initial_context()
|
|
|
|
if not HAVE_SELINUX or not self.selinux_enabled():
|
|
|
|
return context
|
|
|
|
try:
|
2016-09-07 07:54:17 +02:00
|
|
|
ret = selinux.matchpathcon(to_native(path, errors='surrogate_or_strict'), mode)
|
2013-10-31 21:52:37 +01:00
|
|
|
except OSError:
|
|
|
|
return context
|
|
|
|
if ret[0] == -1:
|
|
|
|
return context
|
|
|
|
# Limit split to 4 because the selevel, the last in the list,
|
|
|
|
# may contain ':' characters
|
|
|
|
context = ret[1].split(':', 3)
|
|
|
|
return context
|
|
|
|
|
|
|
|
def selinux_context(self, path):
|
|
|
|
context = self.selinux_initial_context()
|
|
|
|
if not HAVE_SELINUX or not self.selinux_enabled():
|
|
|
|
return context
|
|
|
|
try:
|
2016-09-07 07:54:17 +02:00
|
|
|
ret = selinux.lgetfilecon_raw(to_native(path, errors='surrogate_or_strict'))
|
2017-08-12 05:23:17 +02:00
|
|
|
except OSError as e:
|
2013-10-31 21:52:37 +01:00
|
|
|
if e.errno == errno.ENOENT:
|
|
|
|
self.fail_json(path=path, msg='path %s does not exist' % path)
|
|
|
|
else:
|
|
|
|
self.fail_json(path=path, msg='failed to retrieve selinux context')
|
|
|
|
if ret[0] == -1:
|
|
|
|
return context
|
|
|
|
# Limit split to 4 because the selevel, the last in the list,
|
|
|
|
# may contain ':' characters
|
|
|
|
context = ret[1].split(':', 3)
|
|
|
|
return context
|
|
|
|
|
2017-02-24 01:12:55 +01:00
|
|
|
def user_and_group(self, path, expand=True):
|
2017-07-21 19:23:16 +02:00
|
|
|
b_path = to_bytes(path, errors='surrogate_or_strict')
|
2017-02-24 01:12:55 +01:00
|
|
|
if expand:
|
|
|
|
b_path = os.path.expanduser(os.path.expandvars(b_path))
|
|
|
|
st = os.lstat(b_path)
|
2013-10-31 21:52:37 +01:00
|
|
|
uid = st.st_uid
|
|
|
|
gid = st.st_gid
|
|
|
|
return (uid, gid)
|
|
|
|
|
2014-04-17 23:16:54 +02:00
|
|
|
def find_mount_point(self, path):
|
2017-04-18 00:05:10 +02:00
|
|
|
path_is_bytes = False
|
|
|
|
if isinstance(path, binary_type):
|
|
|
|
path_is_bytes = True
|
|
|
|
|
|
|
|
b_path = os.path.realpath(to_bytes(os.path.expanduser(os.path.expandvars(path)), errors='surrogate_or_strict'))
|
|
|
|
while not os.path.ismount(b_path):
|
|
|
|
b_path = os.path.dirname(b_path)
|
|
|
|
|
|
|
|
if path_is_bytes:
|
|
|
|
return b_path
|
|
|
|
|
|
|
|
return to_text(b_path, errors='surrogate_or_strict')
|
2014-04-17 23:16:54 +02:00
|
|
|
|
2015-05-14 16:50:22 +02:00
|
|
|
def is_special_selinux_path(self, path):
|
2014-04-17 23:16:54 +02:00
|
|
|
"""
|
2015-05-14 16:50:22 +02:00
|
|
|
Returns a tuple containing (True, selinux_context) if the given path is on a
|
|
|
|
NFS or other 'special' fs mount point, otherwise the return will be (False, None).
|
2014-04-17 23:16:54 +02:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
f = open('/proc/mounts', 'r')
|
|
|
|
mount_data = f.readlines()
|
|
|
|
f.close()
|
|
|
|
except:
|
|
|
|
return (False, None)
|
|
|
|
path_mount_point = self.find_mount_point(path)
|
|
|
|
for line in mount_data:
|
|
|
|
(device, mount_point, fstype, options, rest) = line.split(' ', 4)
|
2015-05-14 16:50:22 +02:00
|
|
|
|
|
|
|
if path_mount_point == mount_point:
|
2016-05-13 05:30:05 +02:00
|
|
|
for fs in self._selinux_special_fs:
|
2015-05-14 16:50:22 +02:00
|
|
|
if fs in fstype:
|
|
|
|
special_context = self.selinux_context(path_mount_point)
|
|
|
|
return (True, special_context)
|
|
|
|
|
2014-04-17 23:16:54 +02:00
|
|
|
return (False, None)
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
def set_default_selinux_context(self, path, changed):
|
|
|
|
if not HAVE_SELINUX or not self.selinux_enabled():
|
|
|
|
return changed
|
|
|
|
context = self.selinux_default_context(path)
|
|
|
|
return self.set_context_if_different(path, context, False)
|
|
|
|
|
2016-01-02 03:52:41 +01:00
|
|
|
def set_context_if_different(self, path, context, changed, diff=None):
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
if not HAVE_SELINUX or not self.selinux_enabled():
|
|
|
|
return changed
|
2018-01-05 05:33:14 +01:00
|
|
|
|
|
|
|
if self.check_file_absent_if_check_mode(path):
|
|
|
|
return True
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
cur_context = self.selinux_context(path)
|
|
|
|
new_context = list(cur_context)
|
|
|
|
# Iterate over the current context instead of the
|
|
|
|
# argument context, which may have selevel.
|
|
|
|
|
2015-05-14 16:50:22 +02:00
|
|
|
(is_special_se, sp_context) = self.is_special_selinux_path(path)
|
|
|
|
if is_special_se:
|
|
|
|
new_context = sp_context
|
2014-04-17 23:16:54 +02:00
|
|
|
else:
|
|
|
|
for i in range(len(cur_context)):
|
|
|
|
if len(context) > i:
|
|
|
|
if context[i] is not None and context[i] != cur_context[i]:
|
|
|
|
new_context[i] = context[i]
|
2015-05-28 08:26:04 +02:00
|
|
|
elif context[i] is None:
|
2014-04-17 23:16:54 +02:00
|
|
|
new_context[i] = cur_context[i]
|
2013-11-08 19:17:02 +01:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
if cur_context != new_context:
|
2016-01-02 03:52:41 +01:00
|
|
|
if diff is not None:
|
|
|
|
if 'before' not in diff:
|
|
|
|
diff['before'] = {}
|
|
|
|
diff['before']['secontext'] = cur_context
|
|
|
|
if 'after' not in diff:
|
|
|
|
diff['after'] = {}
|
|
|
|
diff['after']['secontext'] = new_context
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
try:
|
|
|
|
if self.check_mode:
|
|
|
|
return True
|
2017-08-12 05:23:17 +02:00
|
|
|
rc = selinux.lsetfilecon(to_native(path), ':'.join(new_context))
|
|
|
|
except OSError as e:
|
|
|
|
self.fail_json(path=path, msg='invalid selinux context: %s' % to_native(e),
|
|
|
|
new_context=new_context, cur_context=cur_context, input_was=context)
|
2013-10-31 21:52:37 +01:00
|
|
|
if rc != 0:
|
|
|
|
self.fail_json(path=path, msg='set selinux context failed')
|
|
|
|
changed = True
|
|
|
|
return changed
|
|
|
|
|
2017-02-24 01:12:55 +01:00
|
|
|
def set_owner_if_different(self, path, owner, changed, diff=None, expand=True):
|
2018-01-05 05:33:14 +01:00
|
|
|
|
|
|
|
if owner is None:
|
|
|
|
return changed
|
|
|
|
|
2017-07-21 19:23:16 +02:00
|
|
|
b_path = to_bytes(path, errors='surrogate_or_strict')
|
2017-02-24 01:12:55 +01:00
|
|
|
if expand:
|
|
|
|
b_path = os.path.expanduser(os.path.expandvars(b_path))
|
2018-01-05 05:33:14 +01:00
|
|
|
|
|
|
|
if self.check_file_absent_if_check_mode(b_path):
|
|
|
|
return True
|
|
|
|
|
2017-07-25 08:28:51 +02:00
|
|
|
orig_uid, orig_gid = self.user_and_group(b_path, expand)
|
2013-10-31 21:52:37 +01:00
|
|
|
try:
|
|
|
|
uid = int(owner)
|
|
|
|
except ValueError:
|
|
|
|
try:
|
|
|
|
uid = pwd.getpwnam(owner).pw_uid
|
|
|
|
except KeyError:
|
2017-07-25 08:28:51 +02:00
|
|
|
path = to_text(b_path)
|
2013-10-31 21:52:37 +01:00
|
|
|
self.fail_json(path=path, msg='chown failed: failed to look up user %s' % owner)
|
2016-01-02 03:52:41 +01:00
|
|
|
|
2017-07-25 08:28:51 +02:00
|
|
|
if orig_uid != uid:
|
2016-01-02 03:52:41 +01:00
|
|
|
if diff is not None:
|
|
|
|
if 'before' not in diff:
|
|
|
|
diff['before'] = {}
|
|
|
|
diff['before']['owner'] = orig_uid
|
|
|
|
if 'after' not in diff:
|
|
|
|
diff['after'] = {}
|
|
|
|
diff['after']['owner'] = uid
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
if self.check_mode:
|
|
|
|
return True
|
|
|
|
try:
|
2016-09-01 13:19:03 +02:00
|
|
|
os.lchown(b_path, uid, -1)
|
2017-10-02 21:51:40 +02:00
|
|
|
except (IOError, OSError) as e:
|
2017-07-25 08:28:51 +02:00
|
|
|
path = to_text(b_path)
|
2017-10-02 21:51:40 +02:00
|
|
|
self.fail_json(path=path, msg='chown failed: %s' % (to_text(e)))
|
2013-10-31 21:52:37 +01:00
|
|
|
changed = True
|
|
|
|
return changed
|
|
|
|
|
2017-02-24 01:12:55 +01:00
|
|
|
def set_group_if_different(self, path, group, changed, diff=None, expand=True):
|
2018-01-05 05:33:14 +01:00
|
|
|
|
|
|
|
if group is None:
|
|
|
|
return changed
|
|
|
|
|
2017-07-21 19:23:16 +02:00
|
|
|
b_path = to_bytes(path, errors='surrogate_or_strict')
|
2017-02-24 01:12:55 +01:00
|
|
|
if expand:
|
|
|
|
b_path = os.path.expanduser(os.path.expandvars(b_path))
|
2018-01-05 05:33:14 +01:00
|
|
|
|
|
|
|
if self.check_file_absent_if_check_mode(b_path):
|
|
|
|
return True
|
|
|
|
|
2017-02-24 01:12:55 +01:00
|
|
|
orig_uid, orig_gid = self.user_and_group(b_path, expand)
|
2013-10-31 21:52:37 +01:00
|
|
|
try:
|
|
|
|
gid = int(group)
|
|
|
|
except ValueError:
|
|
|
|
try:
|
|
|
|
gid = grp.getgrnam(group).gr_gid
|
|
|
|
except KeyError:
|
2017-07-25 08:28:51 +02:00
|
|
|
path = to_text(b_path)
|
2013-10-31 21:52:37 +01:00
|
|
|
self.fail_json(path=path, msg='chgrp failed: failed to look up group %s' % group)
|
2016-01-02 03:52:41 +01:00
|
|
|
|
2017-07-25 08:28:51 +02:00
|
|
|
if orig_gid != gid:
|
2016-01-02 03:52:41 +01:00
|
|
|
if diff is not None:
|
|
|
|
if 'before' not in diff:
|
|
|
|
diff['before'] = {}
|
|
|
|
diff['before']['group'] = orig_gid
|
|
|
|
if 'after' not in diff:
|
|
|
|
diff['after'] = {}
|
|
|
|
diff['after']['group'] = gid
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
if self.check_mode:
|
|
|
|
return True
|
|
|
|
try:
|
2016-09-01 13:19:03 +02:00
|
|
|
os.lchown(b_path, -1, gid)
|
2013-10-31 21:52:37 +01:00
|
|
|
except OSError:
|
2017-07-25 08:28:51 +02:00
|
|
|
path = to_text(b_path)
|
2013-10-31 21:52:37 +01:00
|
|
|
self.fail_json(path=path, msg='chgrp failed')
|
|
|
|
changed = True
|
|
|
|
return changed
|
|
|
|
|
2017-02-24 01:12:55 +01:00
|
|
|
def set_mode_if_different(self, path, mode, changed, diff=None, expand=True):
|
2018-01-05 05:33:14 +01:00
|
|
|
|
|
|
|
if mode is None:
|
|
|
|
return changed
|
|
|
|
|
2017-07-21 19:23:16 +02:00
|
|
|
b_path = to_bytes(path, errors='surrogate_or_strict')
|
2017-02-24 01:12:55 +01:00
|
|
|
if expand:
|
|
|
|
b_path = os.path.expanduser(os.path.expandvars(b_path))
|
2016-08-29 18:11:40 +02:00
|
|
|
path_stat = os.lstat(b_path)
|
2013-12-07 03:06:35 +01:00
|
|
|
|
2018-01-05 05:33:14 +01:00
|
|
|
if self.check_file_absent_if_check_mode(b_path):
|
|
|
|
return True
|
2013-12-07 03:06:35 +01:00
|
|
|
|
|
|
|
if not isinstance(mode, int):
|
|
|
|
try:
|
2013-10-31 21:52:37 +01:00
|
|
|
mode = int(mode, 8)
|
2013-12-07 03:06:35 +01:00
|
|
|
except Exception:
|
|
|
|
try:
|
|
|
|
mode = self._symbolic_mode_to_octal(path_stat, mode)
|
2017-08-12 05:23:17 +02:00
|
|
|
except Exception as e:
|
2017-07-25 08:28:51 +02:00
|
|
|
path = to_text(b_path)
|
2013-12-07 03:06:35 +01:00
|
|
|
self.fail_json(path=path,
|
|
|
|
msg="mode must be in octal or symbolic form",
|
2017-08-12 05:23:17 +02:00
|
|
|
details=to_native(e))
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2016-03-04 20:41:35 +01:00
|
|
|
if mode != stat.S_IMODE(mode):
|
|
|
|
# prevent mode from having extra info orbeing invalid long number
|
2017-07-25 08:28:51 +02:00
|
|
|
path = to_text(b_path)
|
2016-03-04 20:44:03 +01:00
|
|
|
self.fail_json(path=path, msg="Invalid mode supplied, only permission info is allowed", details=mode)
|
2016-03-04 20:41:35 +01:00
|
|
|
|
2013-12-07 03:06:35 +01:00
|
|
|
prev_mode = stat.S_IMODE(path_stat.st_mode)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
if prev_mode != mode:
|
2016-01-02 03:52:41 +01:00
|
|
|
|
|
|
|
if diff is not None:
|
|
|
|
if 'before' not in diff:
|
|
|
|
diff['before'] = {}
|
2016-08-25 23:58:35 +02:00
|
|
|
diff['before']['mode'] = '0%03o' % prev_mode
|
2016-01-02 03:52:41 +01:00
|
|
|
if 'after' not in diff:
|
|
|
|
diff['after'] = {}
|
2016-08-25 23:58:35 +02:00
|
|
|
diff['after']['mode'] = '0%03o' % mode
|
2016-01-02 03:52:41 +01:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
if self.check_mode:
|
|
|
|
return True
|
|
|
|
# FIXME: comparison against string above will cause this to be executed
|
|
|
|
# every time
|
|
|
|
try:
|
2015-02-16 16:07:58 +01:00
|
|
|
if hasattr(os, 'lchmod'):
|
2016-08-29 18:11:40 +02:00
|
|
|
os.lchmod(b_path, mode)
|
2013-10-31 21:52:37 +01:00
|
|
|
else:
|
2016-08-29 18:11:40 +02:00
|
|
|
if not os.path.islink(b_path):
|
|
|
|
os.chmod(b_path, mode)
|
2015-02-16 16:07:58 +01:00
|
|
|
else:
|
|
|
|
# Attempt to set the perms of the symlink but be
|
|
|
|
# careful not to change the perms of the underlying
|
|
|
|
# file while trying
|
2016-08-29 18:11:40 +02:00
|
|
|
underlying_stat = os.stat(b_path)
|
|
|
|
os.chmod(b_path, mode)
|
|
|
|
new_underlying_stat = os.stat(b_path)
|
2015-02-16 16:07:58 +01:00
|
|
|
if underlying_stat.st_mode != new_underlying_stat.st_mode:
|
2016-08-29 18:11:40 +02:00
|
|
|
os.chmod(b_path, stat.S_IMODE(underlying_stat.st_mode))
|
2017-08-12 05:23:17 +02:00
|
|
|
except OSError as e:
|
2016-08-29 18:11:40 +02:00
|
|
|
if os.path.islink(b_path) and e.errno == errno.EPERM: # Can't set mode on symbolic links
|
2013-10-31 21:52:37 +01:00
|
|
|
pass
|
2017-06-02 13:14:11 +02:00
|
|
|
elif e.errno in (errno.ENOENT, errno.ELOOP): # Can't set mode on broken symbolic links
|
2013-10-31 21:52:37 +01:00
|
|
|
pass
|
|
|
|
else:
|
2017-08-12 05:23:17 +02:00
|
|
|
raise
|
|
|
|
except Exception as e:
|
2017-07-25 08:28:51 +02:00
|
|
|
path = to_text(b_path)
|
2017-08-12 05:23:17 +02:00
|
|
|
self.fail_json(path=path, msg='chmod failed', details=to_native(e),
|
|
|
|
exception=traceback.format_exc())
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2016-08-29 18:11:40 +02:00
|
|
|
path_stat = os.lstat(b_path)
|
2013-12-07 03:06:35 +01:00
|
|
|
new_mode = stat.S_IMODE(path_stat.st_mode)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
if new_mode != prev_mode:
|
|
|
|
changed = True
|
|
|
|
return changed
|
|
|
|
|
2017-02-24 01:12:55 +01:00
|
|
|
def set_attributes_if_different(self, path, attributes, changed, diff=None, expand=True):
|
2016-11-07 21:48:04 +01:00
|
|
|
|
|
|
|
if attributes is None:
|
|
|
|
return changed
|
|
|
|
|
2017-07-21 19:23:16 +02:00
|
|
|
b_path = to_bytes(path, errors='surrogate_or_strict')
|
2017-02-24 01:12:55 +01:00
|
|
|
if expand:
|
|
|
|
b_path = os.path.expanduser(os.path.expandvars(b_path))
|
2016-11-07 21:48:04 +01:00
|
|
|
|
2018-01-05 05:33:14 +01:00
|
|
|
if self.check_file_absent_if_check_mode(b_path):
|
|
|
|
return True
|
|
|
|
|
2017-03-20 15:56:35 +01:00
|
|
|
existing = self.get_file_attributes(b_path)
|
|
|
|
|
2018-06-14 15:31:14 +02:00
|
|
|
attr_mod = '='
|
|
|
|
if attributes.startswith(('-', '+')):
|
|
|
|
attr_mod = attributes[0]
|
|
|
|
attributes = attributes[1:]
|
|
|
|
|
|
|
|
if existing.get('attr_flags', '') != attributes or attr_mod == '-':
|
2016-11-07 21:48:04 +01:00
|
|
|
attrcmd = self.get_bin_path('chattr')
|
|
|
|
if attrcmd:
|
2018-06-14 15:31:14 +02:00
|
|
|
attrcmd = [attrcmd, '%s%s' % (attr_mod, attributes), b_path]
|
2016-11-07 21:48:04 +01:00
|
|
|
changed = True
|
|
|
|
|
|
|
|
if diff is not None:
|
|
|
|
if 'before' not in diff:
|
|
|
|
diff['before'] = {}
|
|
|
|
diff['before']['attributes'] = existing.get('attr_flags')
|
|
|
|
if 'after' not in diff:
|
|
|
|
diff['after'] = {}
|
2018-06-14 15:31:14 +02:00
|
|
|
diff['after']['attributes'] = '%s%s' % (attr_mod, attributes)
|
2016-11-07 21:48:04 +01:00
|
|
|
|
|
|
|
if not self.check_mode:
|
|
|
|
try:
|
|
|
|
rc, out, err = self.run_command(attrcmd)
|
|
|
|
if rc != 0 or err:
|
|
|
|
raise Exception("Error while setting attributes: %s" % (out + err))
|
2017-08-12 05:23:17 +02:00
|
|
|
except Exception as e:
|
2016-12-03 17:48:51 +01:00
|
|
|
self.fail_json(path=to_text(b_path), msg='chattr failed',
|
|
|
|
details=to_native(e), exception=traceback.format_exc())
|
2016-11-07 21:48:04 +01:00
|
|
|
return changed
|
|
|
|
|
|
|
|
def get_file_attributes(self, path):
|
|
|
|
output = {}
|
|
|
|
attrcmd = self.get_bin_path('lsattr', False)
|
|
|
|
if attrcmd:
|
|
|
|
attrcmd = [attrcmd, '-vd', path]
|
|
|
|
try:
|
|
|
|
rc, out, err = self.run_command(attrcmd)
|
|
|
|
if rc == 0:
|
2016-12-03 17:48:51 +01:00
|
|
|
res = out.split()
|
2017-06-02 13:14:11 +02:00
|
|
|
output['attr_flags'] = res[1].replace('-', '').strip()
|
2016-11-07 21:48:04 +01:00
|
|
|
output['version'] = res[0].strip()
|
|
|
|
output['attributes'] = format_attributes(output['attr_flags'])
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
return output
|
|
|
|
|
2017-07-22 15:47:57 +02:00
|
|
|
@classmethod
|
|
|
|
def _symbolic_mode_to_octal(cls, path_stat, symbolic_mode):
|
|
|
|
"""
|
|
|
|
This enables symbolic chmod string parsing as stated in the chmod man-page
|
2013-12-07 03:06:35 +01:00
|
|
|
|
2017-07-22 15:47:57 +02:00
|
|
|
This includes things like: "u=rw-x+X,g=r-x+X,o=r-x+X"
|
|
|
|
"""
|
|
|
|
|
|
|
|
new_mode = stat.S_IMODE(path_stat.st_mode)
|
2017-07-24 15:33:56 +02:00
|
|
|
|
|
|
|
# Now parse all symbolic modes
|
2013-12-07 03:06:35 +01:00
|
|
|
for mode in symbolic_mode.split(','):
|
2017-07-24 15:33:56 +02:00
|
|
|
# Per single mode. This always contains a '+', '-' or '='
|
|
|
|
# Split it on that
|
2017-07-22 15:47:57 +02:00
|
|
|
permlist = MODE_OPERATOR_RE.split(mode)
|
2017-07-24 15:33:56 +02:00
|
|
|
|
|
|
|
# And find all the operators
|
2017-07-22 15:47:57 +02:00
|
|
|
opers = MODE_OPERATOR_RE.findall(mode)
|
2017-07-24 15:33:56 +02:00
|
|
|
|
|
|
|
# The user(s) where it's all about is the first element in the
|
|
|
|
# 'permlist' list. Take that and remove it from the list.
|
|
|
|
# An empty user or 'a' means 'all'.
|
|
|
|
users = permlist.pop(0)
|
|
|
|
use_umask = (users == '')
|
|
|
|
if users == 'a' or users == '':
|
|
|
|
users = 'ugo'
|
|
|
|
|
|
|
|
# Check if there are illegal characters in the user list
|
|
|
|
# They can end up in 'users' because they are not split
|
2017-07-22 15:47:57 +02:00
|
|
|
if USERS_RE.match(users):
|
2017-07-24 15:33:56 +02:00
|
|
|
raise ValueError("bad symbolic permission for mode: %s" % mode)
|
2013-12-07 03:06:35 +01:00
|
|
|
|
2017-07-24 15:33:56 +02:00
|
|
|
# Now we have two list of equal length, one contains the requested
|
|
|
|
# permissions and one with the corresponding operators.
|
|
|
|
for idx, perms in enumerate(permlist):
|
|
|
|
# Check if there are illegal characters in the permissions
|
2017-07-22 15:47:57 +02:00
|
|
|
if PERMS_RE.match(perms):
|
2017-07-24 15:33:56 +02:00
|
|
|
raise ValueError("bad symbolic permission for mode: %s" % mode)
|
2013-12-07 03:06:35 +01:00
|
|
|
|
|
|
|
for user in users:
|
2017-07-22 15:47:57 +02:00
|
|
|
mode_to_apply = cls._get_octal_mode_from_symbolic_perms(path_stat, user, perms, use_umask)
|
|
|
|
new_mode = cls._apply_operation_to_mode(user, opers[idx], mode_to_apply, new_mode)
|
2017-07-24 15:33:56 +02:00
|
|
|
|
2013-12-07 03:06:35 +01:00
|
|
|
return new_mode
|
2016-02-04 22:54:03 +01:00
|
|
|
|
2017-07-22 15:47:57 +02:00
|
|
|
@staticmethod
|
|
|
|
def _apply_operation_to_mode(user, operator, mode_to_apply, current_mode):
|
2017-06-02 13:14:11 +02:00
|
|
|
if operator == '=':
|
2017-01-28 09:12:11 +01:00
|
|
|
if user == 'u':
|
|
|
|
mask = stat.S_IRWXU | stat.S_ISUID
|
|
|
|
elif user == 'g':
|
|
|
|
mask = stat.S_IRWXG | stat.S_ISGID
|
|
|
|
elif user == 'o':
|
|
|
|
mask = stat.S_IRWXO | stat.S_ISVTX
|
2016-02-04 22:54:03 +01:00
|
|
|
|
|
|
|
# mask out u, g, or o permissions from current_mode and apply new permissions
|
2015-09-23 08:50:46 +02:00
|
|
|
inverse_mask = mask ^ PERM_BITS
|
2013-12-07 03:06:35 +01:00
|
|
|
new_mode = (current_mode & inverse_mask) | mode_to_apply
|
|
|
|
elif operator == '+':
|
|
|
|
new_mode = current_mode | mode_to_apply
|
|
|
|
elif operator == '-':
|
|
|
|
new_mode = current_mode - (current_mode & mode_to_apply)
|
|
|
|
return new_mode
|
2016-02-04 22:54:03 +01:00
|
|
|
|
2017-07-22 15:47:57 +02:00
|
|
|
@staticmethod
|
|
|
|
def _get_octal_mode_from_symbolic_perms(path_stat, user, perms, use_umask):
|
2013-12-07 03:06:35 +01:00
|
|
|
prev_mode = stat.S_IMODE(path_stat.st_mode)
|
2016-02-04 22:54:03 +01:00
|
|
|
|
2013-12-07 03:06:35 +01:00
|
|
|
is_directory = stat.S_ISDIR(path_stat.st_mode)
|
2015-09-23 08:50:46 +02:00
|
|
|
has_x_permissions = (prev_mode & EXEC_PERM_BITS) > 0
|
2013-12-07 03:06:35 +01:00
|
|
|
apply_X_permission = is_directory or has_x_permissions
|
|
|
|
|
2017-07-24 15:33:56 +02:00
|
|
|
# Get the umask, if the 'user' part is empty, the effect is as if (a) were
|
|
|
|
# given, but bits that are set in the umask are not affected.
|
|
|
|
# We also need the "reversed umask" for masking
|
|
|
|
umask = os.umask(0)
|
|
|
|
os.umask(umask)
|
2017-07-22 15:47:57 +02:00
|
|
|
rev_umask = umask ^ PERM_BITS
|
2017-07-24 15:33:56 +02:00
|
|
|
|
2013-12-07 03:06:35 +01:00
|
|
|
# Permission bits constants documented at:
|
|
|
|
# http://docs.python.org/2/library/stat.html#stat.S_ISUID
|
2014-08-28 02:15:57 +02:00
|
|
|
if apply_X_permission:
|
|
|
|
X_perms = {
|
|
|
|
'u': {'X': stat.S_IXUSR},
|
|
|
|
'g': {'X': stat.S_IXGRP},
|
2017-06-02 13:14:11 +02:00
|
|
|
'o': {'X': stat.S_IXOTH},
|
2014-08-28 02:15:57 +02:00
|
|
|
}
|
|
|
|
else:
|
|
|
|
X_perms = {
|
|
|
|
'u': {'X': 0},
|
|
|
|
'g': {'X': 0},
|
2017-06-02 13:14:11 +02:00
|
|
|
'o': {'X': 0},
|
2014-08-28 02:15:57 +02:00
|
|
|
}
|
|
|
|
|
2013-12-07 03:06:35 +01:00
|
|
|
user_perms_to_modes = {
|
|
|
|
'u': {
|
2017-07-22 15:47:57 +02:00
|
|
|
'r': rev_umask & stat.S_IRUSR if use_umask else stat.S_IRUSR,
|
|
|
|
'w': rev_umask & stat.S_IWUSR if use_umask else stat.S_IWUSR,
|
|
|
|
'x': rev_umask & stat.S_IXUSR if use_umask else stat.S_IXUSR,
|
2013-12-07 03:06:35 +01:00
|
|
|
's': stat.S_ISUID,
|
|
|
|
't': 0,
|
|
|
|
'u': prev_mode & stat.S_IRWXU,
|
|
|
|
'g': (prev_mode & stat.S_IRWXG) << 3,
|
2017-07-24 15:33:56 +02:00
|
|
|
'o': (prev_mode & stat.S_IRWXO) << 6},
|
2013-12-07 03:06:35 +01:00
|
|
|
'g': {
|
2017-07-22 15:47:57 +02:00
|
|
|
'r': rev_umask & stat.S_IRGRP if use_umask else stat.S_IRGRP,
|
|
|
|
'w': rev_umask & stat.S_IWGRP if use_umask else stat.S_IWGRP,
|
|
|
|
'x': rev_umask & stat.S_IXGRP if use_umask else stat.S_IXGRP,
|
2013-12-07 03:06:35 +01:00
|
|
|
's': stat.S_ISGID,
|
|
|
|
't': 0,
|
|
|
|
'u': (prev_mode & stat.S_IRWXU) >> 3,
|
|
|
|
'g': prev_mode & stat.S_IRWXG,
|
2017-07-24 15:33:56 +02:00
|
|
|
'o': (prev_mode & stat.S_IRWXO) << 3},
|
2013-12-07 03:06:35 +01:00
|
|
|
'o': {
|
2017-07-22 15:47:57 +02:00
|
|
|
'r': rev_umask & stat.S_IROTH if use_umask else stat.S_IROTH,
|
|
|
|
'w': rev_umask & stat.S_IWOTH if use_umask else stat.S_IWOTH,
|
|
|
|
'x': rev_umask & stat.S_IXOTH if use_umask else stat.S_IXOTH,
|
2013-12-07 03:06:35 +01:00
|
|
|
's': 0,
|
|
|
|
't': stat.S_ISVTX,
|
|
|
|
'u': (prev_mode & stat.S_IRWXU) >> 6,
|
|
|
|
'g': (prev_mode & stat.S_IRWXG) >> 3,
|
2017-07-24 15:33:56 +02:00
|
|
|
'o': prev_mode & stat.S_IRWXO},
|
2013-12-07 03:06:35 +01:00
|
|
|
}
|
|
|
|
|
2014-08-28 02:15:57 +02:00
|
|
|
# Insert X_perms into user_perms_to_modes
|
|
|
|
for key, value in X_perms.items():
|
|
|
|
user_perms_to_modes[key].update(value)
|
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
def or_reduce(mode, perm):
|
|
|
|
return mode | user_perms_to_modes[user][perm]
|
|
|
|
|
2013-12-07 03:06:35 +01:00
|
|
|
return reduce(or_reduce, perms, 0)
|
|
|
|
|
2017-02-24 01:12:55 +01:00
|
|
|
def set_fs_attributes_if_different(self, file_args, changed, diff=None, expand=True):
|
2013-10-31 21:52:37 +01:00
|
|
|
# set modes owners and context as needed
|
|
|
|
changed = self.set_context_if_different(
|
2016-01-02 03:52:41 +01:00
|
|
|
file_args['path'], file_args['secontext'], changed, diff
|
2013-10-31 21:52:37 +01:00
|
|
|
)
|
|
|
|
changed = self.set_owner_if_different(
|
2017-02-24 01:12:55 +01:00
|
|
|
file_args['path'], file_args['owner'], changed, diff, expand
|
2013-10-31 21:52:37 +01:00
|
|
|
)
|
|
|
|
changed = self.set_group_if_different(
|
2017-02-24 01:12:55 +01:00
|
|
|
file_args['path'], file_args['group'], changed, diff, expand
|
2013-10-31 21:52:37 +01:00
|
|
|
)
|
|
|
|
changed = self.set_mode_if_different(
|
2017-02-24 01:12:55 +01:00
|
|
|
file_args['path'], file_args['mode'], changed, diff, expand
|
2013-10-31 21:52:37 +01:00
|
|
|
)
|
2016-11-07 21:48:04 +01:00
|
|
|
changed = self.set_attributes_if_different(
|
2017-02-24 01:12:55 +01:00
|
|
|
file_args['path'], file_args['attributes'], changed, diff, expand
|
2016-11-07 21:48:04 +01:00
|
|
|
)
|
2013-10-31 21:52:37 +01:00
|
|
|
return changed
|
|
|
|
|
2018-01-05 05:33:14 +01:00
|
|
|
def check_file_absent_if_check_mode(self, file_path):
|
|
|
|
return self.check_mode and not os.path.exists(file_path)
|
|
|
|
|
2017-02-24 01:12:55 +01:00
|
|
|
def set_directory_attributes_if_different(self, file_args, changed, diff=None, expand=True):
|
|
|
|
return self.set_fs_attributes_if_different(file_args, changed, diff, expand)
|
2014-03-14 04:07:35 +01:00
|
|
|
|
2017-02-24 01:12:55 +01:00
|
|
|
def set_file_attributes_if_different(self, file_args, changed, diff=None, expand=True):
|
|
|
|
return self.set_fs_attributes_if_different(file_args, changed, diff, expand)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
def add_path_info(self, kwargs):
|
|
|
|
'''
|
|
|
|
for results that are files, supplement the info about the file
|
|
|
|
in the return path with stats about the file path.
|
|
|
|
'''
|
|
|
|
|
|
|
|
path = kwargs.get('path', kwargs.get('dest', None))
|
|
|
|
if path is None:
|
|
|
|
return kwargs
|
2016-09-01 13:19:03 +02:00
|
|
|
b_path = to_bytes(path, errors='surrogate_or_strict')
|
|
|
|
if os.path.exists(b_path):
|
2013-10-31 21:52:37 +01:00
|
|
|
(uid, gid) = self.user_and_group(path)
|
|
|
|
kwargs['uid'] = uid
|
|
|
|
kwargs['gid'] = gid
|
|
|
|
try:
|
|
|
|
user = pwd.getpwuid(uid)[0]
|
|
|
|
except KeyError:
|
|
|
|
user = str(uid)
|
|
|
|
try:
|
|
|
|
group = grp.getgrgid(gid)[0]
|
|
|
|
except KeyError:
|
|
|
|
group = str(gid)
|
|
|
|
kwargs['owner'] = user
|
|
|
|
kwargs['group'] = group
|
2016-09-01 13:19:03 +02:00
|
|
|
st = os.lstat(b_path)
|
2016-08-25 16:44:31 +02:00
|
|
|
kwargs['mode'] = '0%03o' % stat.S_IMODE(st[stat.ST_MODE])
|
2013-10-31 21:52:37 +01:00
|
|
|
# secontext not yet supported
|
2016-09-01 13:19:03 +02:00
|
|
|
if os.path.islink(b_path):
|
2013-10-31 21:52:37 +01:00
|
|
|
kwargs['state'] = 'link'
|
2016-09-01 13:19:03 +02:00
|
|
|
elif os.path.isdir(b_path):
|
2013-10-31 21:52:37 +01:00
|
|
|
kwargs['state'] = 'directory'
|
2016-09-01 13:19:03 +02:00
|
|
|
elif os.stat(b_path).st_nlink > 1:
|
2013-11-01 14:41:22 +01:00
|
|
|
kwargs['state'] = 'hard'
|
2013-10-31 21:52:37 +01:00
|
|
|
else:
|
|
|
|
kwargs['state'] = 'file'
|
|
|
|
if HAVE_SELINUX and self.selinux_enabled():
|
|
|
|
kwargs['secontext'] = ':'.join(self.selinux_context(path))
|
|
|
|
kwargs['size'] = st[stat.ST_SIZE]
|
|
|
|
else:
|
|
|
|
kwargs['state'] = 'absent'
|
|
|
|
return kwargs
|
|
|
|
|
2014-05-19 17:26:06 +02:00
|
|
|
def _check_locale(self):
|
|
|
|
'''
|
|
|
|
Uses the locale module to test the currently set locale
|
|
|
|
(per the LANG and LC_CTYPE environment settings)
|
|
|
|
'''
|
|
|
|
try:
|
|
|
|
# setting the locale to '' uses the default locale
|
|
|
|
# as it would be returned by locale.getdefaultlocale()
|
|
|
|
locale.setlocale(locale.LC_ALL, '')
|
2015-09-23 08:43:17 +02:00
|
|
|
except locale.Error:
|
2014-05-19 17:26:06 +02:00
|
|
|
# fallback to the 'C' locale, which may cause unicode
|
|
|
|
# issues but is preferable to simply failing because
|
|
|
|
# of an unknown locale
|
|
|
|
locale.setlocale(locale.LC_ALL, 'C')
|
2015-10-21 19:59:51 +02:00
|
|
|
os.environ['LANG'] = 'C'
|
2015-10-19 21:25:30 +02:00
|
|
|
os.environ['LC_ALL'] = 'C'
|
2014-11-26 10:35:45 +01:00
|
|
|
os.environ['LC_MESSAGES'] = 'C'
|
2017-08-12 05:23:17 +02:00
|
|
|
except Exception as e:
|
|
|
|
self.fail_json(msg="An unknown error was encountered while attempting to validate the locale: %s" %
|
|
|
|
to_native(e), exception=traceback.format_exc())
|
2013-10-31 21:52:37 +01:00
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
def _handle_aliases(self, spec=None, param=None):
|
2015-12-22 23:15:58 +01:00
|
|
|
# this uses exceptions as it happens before we can safely call fail_json
|
2017-06-02 13:14:11 +02:00
|
|
|
aliases_results = {} # alias:canon
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if param is None:
|
|
|
|
param = self.params
|
|
|
|
|
2017-02-09 00:45:11 +01:00
|
|
|
if spec is None:
|
|
|
|
spec = self.argument_spec
|
2017-06-02 13:14:11 +02:00
|
|
|
for (k, v) in spec.items():
|
2013-10-31 21:52:37 +01:00
|
|
|
self._legal_inputs.append(k)
|
|
|
|
aliases = v.get('aliases', None)
|
|
|
|
default = v.get('default', None)
|
|
|
|
required = v.get('required', False)
|
|
|
|
if default is not None and required:
|
|
|
|
# not alias specific but this is a good place to check this
|
2015-12-22 23:15:58 +01:00
|
|
|
raise Exception("internal error: required and default are mutually exclusive for %s" % k)
|
2013-10-31 21:52:37 +01:00
|
|
|
if aliases is None:
|
|
|
|
continue
|
2016-09-01 13:19:03 +02:00
|
|
|
if not isinstance(aliases, SEQUENCETYPE) or isinstance(aliases, (binary_type, text_type)):
|
|
|
|
raise Exception('internal error: aliases must be a list or tuple')
|
2013-10-31 21:52:37 +01:00
|
|
|
for alias in aliases:
|
|
|
|
self._legal_inputs.append(alias)
|
|
|
|
aliases_results[alias] = k
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if alias in param:
|
|
|
|
param[k] = param[alias]
|
2015-09-26 05:57:03 +02:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
return aliases_results
|
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
def _handle_no_log_values(self, spec=None, param=None):
|
|
|
|
if spec is None:
|
|
|
|
spec = self.argument_spec
|
|
|
|
if param is None:
|
|
|
|
param = self.params
|
|
|
|
|
|
|
|
# Use the argspec to determine which args are no_log
|
|
|
|
for arg_name, arg_opts in spec.items():
|
|
|
|
if arg_opts.get('no_log', False):
|
|
|
|
# Find the value for the no_log'd param
|
|
|
|
no_log_object = param.get(arg_name, None)
|
|
|
|
if no_log_object:
|
|
|
|
self.no_log_values.update(return_values(no_log_object))
|
|
|
|
|
|
|
|
if arg_opts.get('removed_in_version') is not None and arg_name in param:
|
|
|
|
self._deprecations.append({
|
|
|
|
'msg': "Param '%s' is deprecated. See the module docs for more information" % arg_name,
|
|
|
|
'version': arg_opts.get('removed_in_version')
|
|
|
|
})
|
|
|
|
|
|
|
|
def _check_arguments(self, check_invalid_arguments, spec=None, param=None, legal_inputs=None):
|
2016-05-13 05:30:05 +02:00
|
|
|
self._syslog_facility = 'LOG_USER'
|
2016-12-19 23:55:12 +01:00
|
|
|
unsupported_parameters = set()
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if spec is None:
|
|
|
|
spec = self.argument_spec
|
|
|
|
if param is None:
|
|
|
|
param = self.params
|
|
|
|
if legal_inputs is None:
|
|
|
|
legal_inputs = self._legal_inputs
|
|
|
|
|
|
|
|
for (k, v) in list(param.items()):
|
2015-09-26 05:57:03 +02:00
|
|
|
|
2018-01-16 06:15:04 +01:00
|
|
|
if check_invalid_arguments and k not in legal_inputs:
|
2016-12-19 23:55:12 +01:00
|
|
|
unsupported_parameters.add(k)
|
2018-01-16 06:15:04 +01:00
|
|
|
elif k.startswith('_ansible_'):
|
|
|
|
# handle setting internal properties from internal ansible vars
|
|
|
|
key = k.replace('_ansible_', '')
|
|
|
|
if key in PASS_BOOLS:
|
|
|
|
setattr(self, PASS_VARS[key], self.boolean(v))
|
|
|
|
else:
|
|
|
|
setattr(self, PASS_VARS[key], v)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2018-01-16 06:15:04 +01:00
|
|
|
# clean up internal params:
|
2016-02-01 21:17:23 +01:00
|
|
|
del self.params[k]
|
|
|
|
|
2016-12-19 23:55:12 +01:00
|
|
|
if unsupported_parameters:
|
2017-02-01 21:37:08 +01:00
|
|
|
msg = "Unsupported parameters for (%s) module: %s" % (self._name, ', '.join(sorted(list(unsupported_parameters))))
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if self._options_context:
|
|
|
|
msg += " found in %s." % " -> ".join(self._options_context)
|
2017-02-01 21:37:08 +01:00
|
|
|
msg += " Supported parameters include: %s" % (', '.join(sorted(spec.keys())))
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
self.fail_json(msg=msg)
|
2016-06-10 17:48:54 +02:00
|
|
|
if self.check_mode and not self.supports_check_mode:
|
2017-01-31 00:01:47 +01:00
|
|
|
self.exit_json(skipped=True, msg="remote module (%s) does not support check mode" % self._name)
|
2016-06-10 17:48:54 +02:00
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
def _count_terms(self, check, param=None):
|
2013-10-31 21:52:37 +01:00
|
|
|
count = 0
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if param is None:
|
|
|
|
param = self.params
|
2013-10-31 21:52:37 +01:00
|
|
|
for term in check:
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if term in param:
|
2013-11-01 00:47:05 +01:00
|
|
|
count += 1
|
2013-10-31 21:52:37 +01:00
|
|
|
return count
|
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
def _check_mutually_exclusive(self, spec, param=None):
|
2013-10-31 21:52:37 +01:00
|
|
|
if spec is None:
|
|
|
|
return
|
|
|
|
for check in spec:
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
count = self._count_terms(check, param)
|
2013-10-31 21:52:37 +01:00
|
|
|
if count > 1:
|
2017-02-01 21:37:08 +01:00
|
|
|
msg = "parameters are mutually exclusive: %s" % ', '.join(check)
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if self._options_context:
|
|
|
|
msg += " found in %s" % " -> ".join(self._options_context)
|
|
|
|
self.fail_json(msg=msg)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
def _check_required_one_of(self, spec, param=None):
|
2013-10-31 21:52:37 +01:00
|
|
|
if spec is None:
|
|
|
|
return
|
|
|
|
for check in spec:
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
count = self._count_terms(check, param)
|
2013-10-31 21:52:37 +01:00
|
|
|
if count == 0:
|
2017-02-01 21:37:08 +01:00
|
|
|
msg = "one of the following is required: %s" % ', '.join(check)
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if self._options_context:
|
|
|
|
msg += " found in %s" % " -> ".join(self._options_context)
|
|
|
|
self.fail_json(msg=msg)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
def _check_required_together(self, spec, param=None):
|
2013-10-31 21:52:37 +01:00
|
|
|
if spec is None:
|
|
|
|
return
|
|
|
|
for check in spec:
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
counts = [self._count_terms([field], param) for field in check]
|
2017-06-02 13:14:11 +02:00
|
|
|
non_zero = [c for c in counts if c > 0]
|
2013-10-31 21:52:37 +01:00
|
|
|
if len(non_zero) > 0:
|
|
|
|
if 0 in counts:
|
2017-02-01 21:37:08 +01:00
|
|
|
msg = "parameters are required together: %s" % ', '.join(check)
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if self._options_context:
|
|
|
|
msg += " found in %s" % " -> ".join(self._options_context)
|
|
|
|
self.fail_json(msg=msg)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
def _check_required_arguments(self, spec=None, param=None):
|
2013-10-31 21:52:37 +01:00
|
|
|
''' ensure all required arguments are present '''
|
|
|
|
missing = []
|
2017-02-09 00:45:11 +01:00
|
|
|
if spec is None:
|
|
|
|
spec = self.argument_spec
|
2017-02-09 00:53:54 +01:00
|
|
|
if param is None:
|
|
|
|
param = self.params
|
2017-06-02 13:14:11 +02:00
|
|
|
for (k, v) in spec.items():
|
2013-10-31 21:52:37 +01:00
|
|
|
required = v.get('required', False)
|
2017-02-09 00:53:54 +01:00
|
|
|
if required and k not in param:
|
2013-10-31 21:52:37 +01:00
|
|
|
missing.append(k)
|
|
|
|
if len(missing) > 0:
|
2017-02-01 21:37:08 +01:00
|
|
|
msg = "missing required arguments: %s" % ", ".join(missing)
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if self._options_context:
|
|
|
|
msg += " found in %s" % " -> ".join(self._options_context)
|
|
|
|
self.fail_json(msg=msg)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
def _check_required_if(self, spec, param=None):
|
2014-10-26 18:41:58 +01:00
|
|
|
''' ensure that parameters which conditionally required are present '''
|
|
|
|
if spec is None:
|
|
|
|
return
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if param is None:
|
|
|
|
param = self.params
|
2017-02-01 05:01:29 +01:00
|
|
|
for sp in spec:
|
2014-10-26 18:41:58 +01:00
|
|
|
missing = []
|
2017-02-01 05:01:29 +01:00
|
|
|
max_missing_count = 0
|
|
|
|
is_one_of = False
|
|
|
|
if len(sp) == 4:
|
|
|
|
key, val, requirements, is_one_of = sp
|
|
|
|
else:
|
|
|
|
key, val, requirements = sp
|
|
|
|
|
|
|
|
# is_one_of is True at least one requirement should be
|
|
|
|
# present, else all requirements should be present.
|
|
|
|
if is_one_of:
|
|
|
|
max_missing_count = len(requirements)
|
2017-02-01 21:37:08 +01:00
|
|
|
term = 'any'
|
|
|
|
else:
|
|
|
|
term = 'all'
|
2017-02-01 05:01:29 +01:00
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if key in param and param[key] == val:
|
2014-10-26 18:41:58 +01:00
|
|
|
for check in requirements:
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
count = self._count_terms((check,), param)
|
2014-10-26 18:41:58 +01:00
|
|
|
if count == 0:
|
|
|
|
missing.append(check)
|
2017-02-01 05:01:29 +01:00
|
|
|
if len(missing) and len(missing) >= max_missing_count:
|
2017-09-29 07:18:17 +02:00
|
|
|
msg = "%s is %s but %s of the following are missing: %s" % (key, val, term, ', '.join(missing))
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if self._options_context:
|
|
|
|
msg += " found in %s" % " -> ".join(self._options_context)
|
|
|
|
self.fail_json(msg=msg)
|
2014-10-26 18:41:58 +01:00
|
|
|
|
2017-02-09 00:53:54 +01:00
|
|
|
def _check_argument_values(self, spec=None, param=None):
|
2013-10-31 21:52:37 +01:00
|
|
|
''' ensure all arguments have the requested values, and there are no stray arguments '''
|
2017-02-09 00:45:11 +01:00
|
|
|
if spec is None:
|
|
|
|
spec = self.argument_spec
|
2017-02-09 00:53:54 +01:00
|
|
|
if param is None:
|
|
|
|
param = self.params
|
2017-06-02 13:14:11 +02:00
|
|
|
for (k, v) in spec.items():
|
|
|
|
choices = v.get('choices', None)
|
2013-10-31 21:52:37 +01:00
|
|
|
if choices is None:
|
|
|
|
continue
|
2016-09-01 13:19:03 +02:00
|
|
|
if isinstance(choices, SEQUENCETYPE) and not isinstance(choices, (binary_type, text_type)):
|
2017-02-09 00:53:54 +01:00
|
|
|
if k in param:
|
2018-02-08 07:59:21 +01:00
|
|
|
# Allow one or more when type='list' param with choices
|
|
|
|
if isinstance(param[k], list):
|
|
|
|
diff_list = ", ".join([item for item in param[k] if item not in choices])
|
|
|
|
if diff_list:
|
|
|
|
choices_str = ", ".join([to_native(c) for c in choices])
|
|
|
|
msg = "value of %s must be one or more of: %s. Got no match for: %s" % (k, choices_str, diff_list)
|
|
|
|
if self._options_context:
|
|
|
|
msg += " found in %s" % " -> ".join(self._options_context)
|
|
|
|
self.fail_json(msg=msg)
|
|
|
|
elif param[k] not in choices:
|
2016-09-01 13:19:03 +02:00
|
|
|
# PyYaml converts certain strings to bools. If we can unambiguously convert back, do so before checking
|
|
|
|
# the value. If we can't figure this out, module author is responsible.
|
2016-08-05 15:49:34 +02:00
|
|
|
lowered_choices = None
|
2017-02-09 00:53:54 +01:00
|
|
|
if param[k] == 'False':
|
2016-08-05 15:49:34 +02:00
|
|
|
lowered_choices = _lenient_lowercase(choices)
|
2017-07-15 01:44:58 +02:00
|
|
|
overlap = BOOLEANS_FALSE.intersection(choices)
|
2016-08-05 15:49:34 +02:00
|
|
|
if len(overlap) == 1:
|
|
|
|
# Extract from a set
|
2017-02-09 00:53:54 +01:00
|
|
|
(param[k],) = overlap
|
2016-08-05 15:49:34 +02:00
|
|
|
|
2017-02-09 00:53:54 +01:00
|
|
|
if param[k] == 'True':
|
2016-08-05 15:49:34 +02:00
|
|
|
if lowered_choices is None:
|
|
|
|
lowered_choices = _lenient_lowercase(choices)
|
2017-07-15 01:44:58 +02:00
|
|
|
overlap = BOOLEANS_TRUE.intersection(choices)
|
2016-08-05 15:49:34 +02:00
|
|
|
if len(overlap) == 1:
|
2017-02-09 00:53:54 +01:00
|
|
|
(param[k],) = overlap
|
2016-08-05 15:49:34 +02:00
|
|
|
|
2017-02-09 00:53:54 +01:00
|
|
|
if param[k] not in choices:
|
2017-02-01 21:37:08 +01:00
|
|
|
choices_str = ", ".join([to_native(c) for c in choices])
|
2017-06-02 13:14:11 +02:00
|
|
|
msg = "value of %s must be one of: %s, got: %s" % (k, choices_str, param[k])
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if self._options_context:
|
|
|
|
msg += " found in %s" % " -> ".join(self._options_context)
|
2016-08-05 15:49:34 +02:00
|
|
|
self.fail_json(msg=msg)
|
2013-10-31 21:52:37 +01:00
|
|
|
else:
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
msg = "internal error: choices for argument %s are not iterable: %s" % (k, choices)
|
|
|
|
if self._options_context:
|
|
|
|
msg += " found in %s" % " -> ".join(self._options_context)
|
|
|
|
self.fail_json(msg=msg)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2016-08-20 17:08:59 +02:00
|
|
|
def safe_eval(self, value, locals=None, include_exceptions=False):
|
2013-10-31 23:44:13 +01:00
|
|
|
|
|
|
|
# do not allow method calls to modules
|
2016-08-20 17:08:59 +02:00
|
|
|
if not isinstance(value, string_types):
|
|
|
|
# already templated to a datavaluestructure, perhaps?
|
2013-10-31 23:44:13 +01:00
|
|
|
if include_exceptions:
|
2016-08-20 17:08:59 +02:00
|
|
|
return (value, None)
|
|
|
|
return value
|
|
|
|
if re.search(r'\w\.\w+\(', value):
|
2013-10-31 23:44:13 +01:00
|
|
|
if include_exceptions:
|
2016-08-20 17:08:59 +02:00
|
|
|
return (value, None)
|
|
|
|
return value
|
2013-10-31 23:44:13 +01:00
|
|
|
# do not allow imports
|
2016-08-20 17:08:59 +02:00
|
|
|
if re.search(r'import \w+', value):
|
2013-10-31 23:44:13 +01:00
|
|
|
if include_exceptions:
|
2016-08-20 17:08:59 +02:00
|
|
|
return (value, None)
|
|
|
|
return value
|
2013-10-31 23:44:13 +01:00
|
|
|
try:
|
2016-08-20 17:08:59 +02:00
|
|
|
result = literal_eval(value)
|
2013-10-31 23:44:13 +01:00
|
|
|
if include_exceptions:
|
|
|
|
return (result, None)
|
|
|
|
else:
|
|
|
|
return result
|
2017-08-12 05:23:17 +02:00
|
|
|
except Exception as e:
|
2013-10-31 23:44:13 +01:00
|
|
|
if include_exceptions:
|
2016-08-20 17:08:59 +02:00
|
|
|
return (value, e)
|
|
|
|
return value
|
2013-10-31 23:44:13 +01:00
|
|
|
|
2015-06-29 17:05:58 +02:00
|
|
|
def _check_type_str(self, value):
|
2016-08-20 17:08:59 +02:00
|
|
|
if isinstance(value, string_types):
|
2015-06-29 17:05:58 +02:00
|
|
|
return value
|
|
|
|
# Note: This could throw a unicode error if value's __str__() method
|
|
|
|
# returns non-ascii. Have to port utils.to_bytes() if that happens
|
|
|
|
return str(value)
|
|
|
|
|
|
|
|
def _check_type_list(self, value):
|
|
|
|
if isinstance(value, list):
|
|
|
|
return value
|
|
|
|
|
2016-08-20 17:08:59 +02:00
|
|
|
if isinstance(value, string_types):
|
2015-06-29 17:05:58 +02:00
|
|
|
return value.split(",")
|
|
|
|
elif isinstance(value, int) or isinstance(value, float):
|
2017-06-02 13:14:11 +02:00
|
|
|
return [str(value)]
|
2015-06-29 17:05:58 +02:00
|
|
|
|
|
|
|
raise TypeError('%s cannot be converted to a list' % type(value))
|
|
|
|
|
|
|
|
def _check_type_dict(self, value):
|
|
|
|
if isinstance(value, dict):
|
|
|
|
return value
|
|
|
|
|
2016-08-20 17:08:59 +02:00
|
|
|
if isinstance(value, string_types):
|
2015-06-29 17:05:58 +02:00
|
|
|
if value.startswith("{"):
|
|
|
|
try:
|
|
|
|
return json.loads(value)
|
|
|
|
except:
|
|
|
|
(result, exc) = self.safe_eval(value, dict(), include_exceptions=True)
|
|
|
|
if exc is not None:
|
|
|
|
raise TypeError('unable to evaluate string as dictionary')
|
|
|
|
return result
|
|
|
|
elif '=' in value:
|
2014-12-22 19:30:36 +01:00
|
|
|
fields = []
|
|
|
|
field_buffer = []
|
|
|
|
in_quote = False
|
|
|
|
in_escape = False
|
|
|
|
for c in value.strip():
|
|
|
|
if in_escape:
|
|
|
|
field_buffer.append(c)
|
|
|
|
in_escape = False
|
|
|
|
elif c == '\\':
|
|
|
|
in_escape = True
|
|
|
|
elif not in_quote and c in ('\'', '"'):
|
|
|
|
in_quote = c
|
|
|
|
elif in_quote and in_quote == c:
|
|
|
|
in_quote = False
|
|
|
|
elif not in_quote and c in (',', ' '):
|
|
|
|
field = ''.join(field_buffer)
|
|
|
|
if field:
|
|
|
|
fields.append(field)
|
|
|
|
field_buffer = []
|
|
|
|
else:
|
|
|
|
field_buffer.append(c)
|
|
|
|
|
|
|
|
field = ''.join(field_buffer)
|
|
|
|
if field:
|
|
|
|
fields.append(field)
|
|
|
|
return dict(x.split("=", 1) for x in fields)
|
2015-06-29 17:05:58 +02:00
|
|
|
else:
|
|
|
|
raise TypeError("dictionary requested, could not parse JSON or key=value")
|
|
|
|
|
|
|
|
raise TypeError('%s cannot be converted to a dict' % type(value))
|
|
|
|
|
|
|
|
def _check_type_bool(self, value):
|
|
|
|
if isinstance(value, bool):
|
|
|
|
return value
|
|
|
|
|
2016-08-20 17:08:59 +02:00
|
|
|
if isinstance(value, string_types) or isinstance(value, int):
|
2015-06-29 17:05:58 +02:00
|
|
|
return self.boolean(value)
|
|
|
|
|
|
|
|
raise TypeError('%s cannot be converted to a bool' % type(value))
|
|
|
|
|
|
|
|
def _check_type_int(self, value):
|
|
|
|
if isinstance(value, int):
|
|
|
|
return value
|
|
|
|
|
2016-08-20 17:08:59 +02:00
|
|
|
if isinstance(value, string_types):
|
2015-06-29 17:05:58 +02:00
|
|
|
return int(value)
|
|
|
|
|
|
|
|
raise TypeError('%s cannot be converted to an int' % type(value))
|
|
|
|
|
|
|
|
def _check_type_float(self, value):
|
|
|
|
if isinstance(value, float):
|
|
|
|
return value
|
|
|
|
|
2016-08-31 17:57:47 +02:00
|
|
|
if isinstance(value, (binary_type, text_type, int)):
|
2015-06-29 17:05:58 +02:00
|
|
|
return float(value)
|
|
|
|
|
|
|
|
raise TypeError('%s cannot be converted to a float' % type(value))
|
|
|
|
|
|
|
|
def _check_type_path(self, value):
|
|
|
|
value = self._check_type_str(value)
|
2016-04-06 23:07:48 +02:00
|
|
|
return os.path.expanduser(os.path.expandvars(value))
|
2015-06-29 17:05:58 +02:00
|
|
|
|
2016-05-03 16:21:00 +02:00
|
|
|
def _check_type_jsonarg(self, value):
|
|
|
|
# Return a jsonified string. Sometimes the controller turns a json
|
|
|
|
# string into a dict/list so transform it back into json here
|
2016-08-20 17:08:59 +02:00
|
|
|
if isinstance(value, (text_type, binary_type)):
|
2016-05-09 17:14:08 +02:00
|
|
|
return value.strip()
|
2016-05-03 16:21:00 +02:00
|
|
|
else:
|
2016-07-28 21:54:09 +02:00
|
|
|
if isinstance(value, (list, tuple, dict)):
|
2017-05-21 22:56:59 +02:00
|
|
|
return self.jsonify(value)
|
2016-05-03 16:21:00 +02:00
|
|
|
raise TypeError('%s cannot be converted to a json string' % type(value))
|
|
|
|
|
2016-02-10 19:51:12 +01:00
|
|
|
def _check_type_raw(self, value):
|
|
|
|
return value
|
|
|
|
|
2016-08-16 19:45:41 +02:00
|
|
|
def _check_type_bytes(self, value):
|
|
|
|
try:
|
|
|
|
self.human_to_bytes(value)
|
|
|
|
except ValueError:
|
|
|
|
raise TypeError('%s cannot be converted to a Byte value' % type(value))
|
|
|
|
|
|
|
|
def _check_type_bits(self, value):
|
|
|
|
try:
|
2016-08-24 21:04:20 +02:00
|
|
|
self.human_to_bytes(value, isbits=True)
|
2016-08-16 19:45:41 +02:00
|
|
|
except ValueError:
|
|
|
|
raise TypeError('%s cannot be converted to a Bit value' % type(value))
|
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
def _handle_options(self, argument_spec=None, params=None):
|
|
|
|
''' deal with options to create sub spec '''
|
|
|
|
if argument_spec is None:
|
|
|
|
argument_spec = self.argument_spec
|
|
|
|
if params is None:
|
|
|
|
params = self.params
|
|
|
|
|
|
|
|
for (k, v) in argument_spec.items():
|
|
|
|
wanted = v.get('type', None)
|
|
|
|
if wanted == 'dict' or (wanted == 'list' and v.get('elements', '') == 'dict'):
|
|
|
|
spec = v.get('options', None)
|
2018-05-07 18:23:13 +02:00
|
|
|
if v.get('apply_defaults', False):
|
|
|
|
if spec is not None:
|
|
|
|
if params.get(k) is None:
|
|
|
|
params[k] = {}
|
|
|
|
else:
|
|
|
|
continue
|
|
|
|
elif spec is None or k not in params or params[k] is None:
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
continue
|
|
|
|
|
|
|
|
self._options_context.append(k)
|
|
|
|
|
|
|
|
if isinstance(params[k], dict):
|
|
|
|
elements = [params[k]]
|
|
|
|
else:
|
|
|
|
elements = params[k]
|
|
|
|
|
2017-12-13 08:37:52 +01:00
|
|
|
for param in elements:
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if not isinstance(param, dict):
|
2017-12-13 08:37:52 +01:00
|
|
|
self.fail_json(msg="value of %s must be of type dict or list of dict" % k)
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
|
|
|
|
self._set_fallbacks(spec, param)
|
|
|
|
options_aliases = self._handle_aliases(spec, param)
|
|
|
|
|
|
|
|
self._handle_no_log_values(spec, param)
|
|
|
|
options_legal_inputs = list(spec.keys()) + list(options_aliases.keys())
|
|
|
|
|
|
|
|
self._check_arguments(self.check_invalid_arguments, spec, param, options_legal_inputs)
|
|
|
|
|
|
|
|
# check exclusive early
|
|
|
|
if not self.bypass_checks:
|
2017-08-04 15:40:38 +02:00
|
|
|
self._check_mutually_exclusive(v.get('mutually_exclusive', None), param)
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
|
|
|
|
self._set_defaults(pre=True, spec=spec, param=param)
|
|
|
|
|
|
|
|
if not self.bypass_checks:
|
|
|
|
self._check_required_arguments(spec, param)
|
|
|
|
self._check_argument_types(spec, param)
|
|
|
|
self._check_argument_values(spec, param)
|
|
|
|
|
2017-08-04 15:40:38 +02:00
|
|
|
self._check_required_together(v.get('required_together', None), param)
|
|
|
|
self._check_required_one_of(v.get('required_one_of', None), param)
|
|
|
|
self._check_required_if(v.get('required_if', None), param)
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
|
|
|
|
self._set_defaults(pre=False, spec=spec, param=param)
|
|
|
|
|
|
|
|
# handle multi level options (sub argspec)
|
|
|
|
self._handle_options(spec, param)
|
|
|
|
self._options_context.pop()
|
|
|
|
|
2017-02-09 00:53:54 +01:00
|
|
|
def _check_argument_types(self, spec=None, param=None):
|
2013-10-31 21:52:37 +01:00
|
|
|
''' ensure all arguments have the requested type '''
|
2017-02-09 00:45:11 +01:00
|
|
|
|
|
|
|
if spec is None:
|
|
|
|
spec = self.argument_spec
|
2017-02-09 00:53:54 +01:00
|
|
|
if param is None:
|
2017-05-31 18:37:39 +02:00
|
|
|
param = self.params
|
|
|
|
|
2017-02-09 00:45:11 +01:00
|
|
|
for (k, v) in spec.items():
|
2013-10-31 21:52:37 +01:00
|
|
|
wanted = v.get('type', None)
|
2017-02-09 00:53:54 +01:00
|
|
|
if k not in param:
|
2013-10-31 21:52:37 +01:00
|
|
|
continue
|
|
|
|
|
2017-05-31 18:37:12 +02:00
|
|
|
value = param[k]
|
2016-03-24 20:49:03 +01:00
|
|
|
if value is None:
|
|
|
|
continue
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2017-07-27 01:12:50 +02:00
|
|
|
if not callable(wanted):
|
|
|
|
if wanted is None:
|
|
|
|
# Mostly we want to default to str.
|
|
|
|
# For values set to None explicitly, return None instead as
|
|
|
|
# that allows a user to unset a parameter
|
|
|
|
if param[k] is None:
|
|
|
|
continue
|
|
|
|
wanted = 'str'
|
|
|
|
try:
|
|
|
|
type_checker = self._CHECK_ARGUMENT_TYPES_DISPATCHER[wanted]
|
|
|
|
except KeyError:
|
|
|
|
self.fail_json(msg="implementation error: unknown type %s requested for %s" % (wanted, k))
|
|
|
|
else:
|
|
|
|
# set the type_checker to the callable, and reset wanted to the callable's name (or type if it doesn't have one, ala MagicMock)
|
|
|
|
type_checker = wanted
|
|
|
|
wanted = getattr(wanted, '__name__', to_native(type(wanted)))
|
|
|
|
|
2015-06-29 17:05:58 +02:00
|
|
|
try:
|
2017-05-31 18:37:39 +02:00
|
|
|
param[k] = type_checker(value)
|
2017-08-12 05:23:17 +02:00
|
|
|
except (TypeError, ValueError) as e:
|
|
|
|
self.fail_json(msg="argument %s is of type %s and we were unable to convert to %s: %s" %
|
|
|
|
(k, type(value), wanted, to_native(e)))
|
2013-10-31 21:52:37 +01:00
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
def _set_defaults(self, pre=True, spec=None, param=None):
|
|
|
|
if spec is None:
|
|
|
|
spec = self.argument_spec
|
|
|
|
if param is None:
|
|
|
|
param = self.params
|
|
|
|
for (k, v) in spec.items():
|
2013-11-01 00:47:05 +01:00
|
|
|
default = v.get('default', None)
|
2017-02-24 23:49:43 +01:00
|
|
|
if pre is True:
|
2013-11-01 00:47:05 +01:00
|
|
|
# this prevents setting defaults on required items
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if default is not None and k not in param:
|
|
|
|
param[k] = default
|
2013-11-01 00:47:05 +01:00
|
|
|
else:
|
|
|
|
# make sure things without a default still get set None
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if k not in param:
|
|
|
|
param[k] = default
|
2013-10-31 21:52:37 +01:00
|
|
|
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
def _set_fallbacks(self, spec=None, param=None):
|
|
|
|
if spec is None:
|
|
|
|
spec = self.argument_spec
|
|
|
|
if param is None:
|
|
|
|
param = self.params
|
|
|
|
|
|
|
|
for (k, v) in spec.items():
|
2016-03-31 20:17:49 +02:00
|
|
|
fallback = v.get('fallback', (None,))
|
|
|
|
fallback_strategy = fallback[0]
|
|
|
|
fallback_args = []
|
|
|
|
fallback_kwargs = {}
|
Add options sub spec validation (#27119)
* Add aggregate parameter validation
aggregate parameter validation will support checking each individual dict
to resolve conditions for aliases, no_log, mutually_exclusive,
required, type check, values, required_together, required_one_of
and required_if conditions in argspec. It will also set default values.
eg:
tasks:
- name: Configure interface attribute with aggregate
net_interface:
aggregate:
- {name: ge-0/0/1, description: test-interface-1, duplex: full, state: present}
- {name: ge-0/0/2, description: test-interface-2, active: False}
register: response
purge: Yes
Usage:
```
from ansible.module_utils.network_common import AggregateCollection
transform = AggregateCollection(module)
param = transform(module.params.get('aggregate'))
```
Aggregate allows supports for `purge` parameter, it will instruct the module
to remove resources from remote device that hasn’t been explicitly
defined in aggregate. This is not supported by with_* iterators
Also, it improves performace as compared to with_* iterator for network device
that has seperate candidate and running datastore.
For with_* iteration the sequence of operartion is
load-config-1 (candidate db) -> commit (running db) -> load_config-2
(candidate db) -> commit (running db) ...
With aggregate the sequence of operation is
load-config-1 (candidate db) -> load-config-2 (candidate db) -> commit
(running db)
As commit is executed only once per task for aggregate it has
huge perfomance benefit for large configurations.
* Fix CI issues
* Fix review comments
* Add support for options validation for aliases, no_log,
mutually_exclusive, required, type check, value check,
required_together, required_one_of and required_if
conditions in sub-argspec.
* Add unit test for options in argspec.
* Reverted aggregate implementaion.
* Minor change
* Add multi-level argspec support
* Multi-level argspec support with module's top most
conditionals options.
* Fix unit test failure
* Add parent context in errors for sub options
* Resolve merge conflict
* Fix CI issue
2017-08-01 18:32:18 +02:00
|
|
|
if k not in param and fallback_strategy is not None:
|
2016-03-31 20:17:49 +02:00
|
|
|
for item in fallback[1:]:
|
|
|
|
if isinstance(item, dict):
|
|
|
|
fallback_kwargs = item
|
|
|
|
else:
|
|
|
|
fallback_args = item
|
|
|
|
try:
|
2017-08-10 21:10:18 +02:00
|
|
|
param[k] = fallback_strategy(*fallback_args, **fallback_kwargs)
|
2016-03-31 20:17:49 +02:00
|
|
|
except AnsibleFallbackNotFound:
|
|
|
|
continue
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
def _load_params(self):
|
2016-05-18 19:50:55 +02:00
|
|
|
''' read the input and set the params attribute.
|
2016-04-14 18:06:38 +02:00
|
|
|
|
2016-05-18 19:50:55 +02:00
|
|
|
This method is for backwards compatibility. The guts of the function
|
|
|
|
were moved out in 2.1 so that custom modules could read the parameters.
|
|
|
|
'''
|
|
|
|
# debug overrides to read args from file or cmdline
|
|
|
|
self.params = _load_params()
|
2016-04-05 20:06:17 +02:00
|
|
|
|
2015-09-26 05:57:03 +02:00
|
|
|
def _log_to_syslog(self, msg):
|
2015-10-14 15:12:02 +02:00
|
|
|
if HAS_SYSLOG:
|
2016-06-10 17:48:54 +02:00
|
|
|
module = 'ansible-%s' % self._name
|
2016-05-13 05:30:05 +02:00
|
|
|
facility = getattr(syslog, self._syslog_facility, syslog.LOG_USER)
|
2016-04-05 20:06:17 +02:00
|
|
|
syslog.openlog(str(module), 0, facility)
|
2015-10-14 15:12:02 +02:00
|
|
|
syslog.syslog(syslog.LOG_INFO, msg)
|
2015-09-26 05:57:03 +02:00
|
|
|
|
2015-10-01 06:09:15 +02:00
|
|
|
def debug(self, msg):
|
|
|
|
if self._debug:
|
2016-11-17 03:29:30 +01:00
|
|
|
self.log('[debug] %s' % msg)
|
2015-10-01 06:09:15 +02:00
|
|
|
|
2015-09-26 05:57:03 +02:00
|
|
|
def log(self, msg, log_args=None):
|
|
|
|
|
|
|
|
if not self.no_log:
|
|
|
|
|
|
|
|
if log_args is None:
|
|
|
|
log_args = dict()
|
|
|
|
|
2016-06-10 17:48:54 +02:00
|
|
|
module = 'ansible-%s' % self._name
|
2016-08-20 17:08:59 +02:00
|
|
|
if isinstance(module, binary_type):
|
2015-10-02 20:11:48 +02:00
|
|
|
module = module.decode('utf-8', 'replace')
|
2015-09-26 05:57:03 +02:00
|
|
|
|
|
|
|
# 6655 - allow for accented characters
|
2016-08-20 17:08:59 +02:00
|
|
|
if not isinstance(msg, (binary_type, text_type)):
|
2015-10-02 20:11:48 +02:00
|
|
|
raise TypeError("msg should be a string (got %s)" % type(msg))
|
|
|
|
|
|
|
|
# We want journal to always take text type
|
|
|
|
# syslog takes bytes on py2, text type on py3
|
2016-08-20 17:08:59 +02:00
|
|
|
if isinstance(msg, binary_type):
|
2015-10-21 03:51:34 +02:00
|
|
|
journal_msg = remove_values(msg.decode('utf-8', 'replace'), self.no_log_values)
|
|
|
|
else:
|
|
|
|
# TODO: surrogateescape is a danger here on Py3
|
|
|
|
journal_msg = remove_values(msg, self.no_log_values)
|
|
|
|
|
2016-06-05 01:19:57 +02:00
|
|
|
if PY3:
|
2015-10-21 03:51:34 +02:00
|
|
|
syslog_msg = journal_msg
|
2015-10-02 20:11:48 +02:00
|
|
|
else:
|
2015-10-21 03:51:34 +02:00
|
|
|
syslog_msg = journal_msg.encode('utf-8', 'replace')
|
2015-09-26 05:57:03 +02:00
|
|
|
|
2015-10-02 20:11:48 +02:00
|
|
|
if has_journal:
|
2015-09-26 05:57:03 +02:00
|
|
|
journal_args = [("MODULE", os.path.basename(__file__))]
|
|
|
|
for arg in log_args:
|
|
|
|
journal_args.append((arg.upper(), str(log_args[arg])))
|
|
|
|
try:
|
2018-06-07 21:23:13 +02:00
|
|
|
if HAS_SYSLOG:
|
|
|
|
# If syslog_facility specified, it needs to convert
|
|
|
|
# from the facility name to the facility code, and
|
|
|
|
# set it as SYSLOG_FACILITY argument of journal.send()
|
|
|
|
facility = getattr(syslog,
|
|
|
|
self._syslog_facility,
|
|
|
|
syslog.LOG_USER) >> 3
|
|
|
|
journal.send(MESSAGE=u"%s %s" % (module, journal_msg),
|
|
|
|
SYSLOG_FACILITY=facility,
|
|
|
|
**dict(journal_args))
|
|
|
|
else:
|
|
|
|
journal.send(MESSAGE=u"%s %s" % (module, journal_msg),
|
|
|
|
**dict(journal_args))
|
2015-09-26 05:57:03 +02:00
|
|
|
except IOError:
|
|
|
|
# fall back to syslog since logging to journal failed
|
2015-10-02 20:11:48 +02:00
|
|
|
self._log_to_syslog(syslog_msg)
|
2015-09-26 05:57:03 +02:00
|
|
|
else:
|
2015-10-02 20:11:48 +02:00
|
|
|
self._log_to_syslog(syslog_msg)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
def _log_invocation(self):
|
|
|
|
''' log that ansible ran the module '''
|
|
|
|
# TODO: generalize a separate log function and make log_invocation use it
|
|
|
|
# Sanitize possible password argument when logging.
|
|
|
|
log_args = dict()
|
2014-02-13 21:23:49 +01:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
for param in self.params:
|
2017-06-02 13:14:11 +02:00
|
|
|
canon = self.aliases.get(param, param)
|
2013-10-31 21:52:37 +01:00
|
|
|
arg_opts = self.argument_spec.get(canon, {})
|
|
|
|
no_log = arg_opts.get('no_log', False)
|
2014-09-05 02:57:52 +02:00
|
|
|
|
2014-08-19 17:46:46 +02:00
|
|
|
if self.boolean(no_log):
|
2013-10-31 21:52:37 +01:00
|
|
|
log_args[param] = 'NOT_LOGGING_PARAMETER'
|
2017-02-16 16:52:27 +01:00
|
|
|
# try to capture all passwords/passphrase named fields missed by no_log
|
2017-06-02 13:14:11 +02:00
|
|
|
elif PASSWORD_MATCH.search(param) and arg_opts.get('type', 'str') != 'bool' and not arg_opts.get('choices', False):
|
2017-02-16 16:52:27 +01:00
|
|
|
# skip boolean and enums as they are about 'password' state
|
2013-10-31 21:52:37 +01:00
|
|
|
log_args[param] = 'NOT_LOGGING_PASSWORD'
|
2017-02-09 19:59:29 +01:00
|
|
|
self.warn('Module did not set no_log for %s' % param)
|
2013-10-31 21:52:37 +01:00
|
|
|
else:
|
2014-09-05 02:57:52 +02:00
|
|
|
param_val = self.params[param]
|
2016-08-20 17:08:59 +02:00
|
|
|
if not isinstance(param_val, (text_type, binary_type)):
|
2014-09-05 02:57:52 +02:00
|
|
|
param_val = str(param_val)
|
2016-08-20 17:08:59 +02:00
|
|
|
elif isinstance(param_val, text_type):
|
2014-09-05 02:57:52 +02:00
|
|
|
param_val = param_val.encode('utf-8')
|
2015-10-21 03:51:34 +02:00
|
|
|
log_args[param] = heuristic_log_sanitize(param_val, self.no_log_values)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2017-02-28 05:54:09 +01:00
|
|
|
msg = ['%s=%s' % (to_native(arg), to_native(val)) for arg, val in log_args.items()]
|
2013-10-31 21:52:37 +01:00
|
|
|
if msg:
|
2016-03-23 16:00:33 +01:00
|
|
|
msg = 'Invoked with %s' % ' '.join(msg)
|
2013-10-31 21:52:37 +01:00
|
|
|
else:
|
|
|
|
msg = 'Invoked'
|
|
|
|
|
2015-09-26 05:57:03 +02:00
|
|
|
self.log(msg, log_args=log_args)
|
|
|
|
|
2014-03-18 16:17:44 +01:00
|
|
|
def _set_cwd(self):
|
|
|
|
try:
|
|
|
|
cwd = os.getcwd()
|
2017-06-02 13:14:11 +02:00
|
|
|
if not os.access(cwd, os.F_OK | os.R_OK):
|
2017-04-07 01:58:16 +02:00
|
|
|
raise Exception()
|
2014-03-18 16:17:44 +01:00
|
|
|
return cwd
|
|
|
|
except:
|
2016-02-04 22:54:03 +01:00
|
|
|
# we don't have access to the cwd, probably because of sudo.
|
2014-03-18 16:17:44 +01:00
|
|
|
# Try and move to a neutral location to prevent errors
|
2018-02-15 18:01:02 +01:00
|
|
|
for cwd in [self.tmpdir, os.path.expandvars('$HOME'), tempfile.gettempdir()]:
|
2014-03-18 16:17:44 +01:00
|
|
|
try:
|
2017-06-02 13:14:11 +02:00
|
|
|
if os.access(cwd, os.F_OK | os.R_OK):
|
2014-03-18 16:17:44 +01:00
|
|
|
os.chdir(cwd)
|
|
|
|
return cwd
|
|
|
|
except:
|
|
|
|
pass
|
2016-02-04 22:54:03 +01:00
|
|
|
# we won't error here, as it may *not* be a problem,
|
2014-03-18 16:17:44 +01:00
|
|
|
# and we don't want to break modules unnecessarily
|
2016-02-04 22:54:03 +01:00
|
|
|
return None
|
2014-03-18 16:17:44 +01:00
|
|
|
|
2017-09-12 09:11:13 +02:00
|
|
|
def get_bin_path(self, arg, required=False, opt_dirs=None):
|
2013-10-31 21:52:37 +01:00
|
|
|
'''
|
|
|
|
find system executable in PATH.
|
|
|
|
Optional arguments:
|
|
|
|
- required: if executable is not found and required is true, fail_json
|
|
|
|
- opt_dirs: optional list of directories to search in addition to PATH
|
|
|
|
if found return full path; otherwise return None
|
|
|
|
'''
|
2018-07-31 19:04:05 +02:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
bin_path = None
|
2018-07-31 19:04:05 +02:00
|
|
|
try:
|
|
|
|
bin_path = get_bin_path(arg, required, opt_dirs)
|
|
|
|
except ValueError as e:
|
|
|
|
self.fail_json(msg=to_text(e))
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
return bin_path
|
|
|
|
|
|
|
|
def boolean(self, arg):
|
|
|
|
''' return a bool for the arg '''
|
2017-07-15 01:44:58 +02:00
|
|
|
if arg is None:
|
2013-10-31 21:52:37 +01:00
|
|
|
return arg
|
2017-07-15 01:44:58 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
return boolean(arg)
|
|
|
|
except TypeError as e:
|
|
|
|
self.fail_json(msg=to_native(e))
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
def jsonify(self, data):
|
2017-11-21 22:41:27 +01:00
|
|
|
try:
|
|
|
|
return jsonify(data)
|
|
|
|
except UnicodeError as e:
|
|
|
|
self.fail_json(msg=to_text(e))
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
def from_json(self, data):
|
|
|
|
return json.loads(data)
|
|
|
|
|
2014-05-13 20:52:38 +02:00
|
|
|
def add_cleanup_file(self, path):
|
|
|
|
if path not in self.cleanup_files:
|
|
|
|
self.cleanup_files.append(path)
|
|
|
|
|
|
|
|
def do_cleanup_files(self):
|
|
|
|
for path in self.cleanup_files:
|
|
|
|
self.cleanup(path)
|
|
|
|
|
2016-11-17 03:29:30 +01:00
|
|
|
def _return_formatted(self, kwargs):
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
self.add_path_info(kwargs)
|
2016-11-17 03:29:30 +01:00
|
|
|
|
2015-12-19 20:24:59 +01:00
|
|
|
if 'invocation' not in kwargs:
|
2015-12-23 04:45:25 +01:00
|
|
|
kwargs['invocation'] = {'module_args': self.params}
|
2016-11-17 03:29:30 +01:00
|
|
|
|
|
|
|
if 'warnings' in kwargs:
|
|
|
|
if isinstance(kwargs['warnings'], list):
|
|
|
|
for w in kwargs['warnings']:
|
|
|
|
self.warn(w)
|
|
|
|
else:
|
|
|
|
self.warn(kwargs['warnings'])
|
2017-02-14 05:49:39 +01:00
|
|
|
|
2016-11-17 03:29:30 +01:00
|
|
|
if self._warnings:
|
|
|
|
kwargs['warnings'] = self._warnings
|
|
|
|
|
|
|
|
if 'deprecations' in kwargs:
|
|
|
|
if isinstance(kwargs['deprecations'], list):
|
|
|
|
for d in kwargs['deprecations']:
|
2017-02-14 05:49:39 +01:00
|
|
|
if isinstance(d, SEQUENCETYPE) and len(d) == 2:
|
2017-03-22 03:19:40 +01:00
|
|
|
self.deprecate(d[0], version=d[1])
|
2018-09-21 18:30:31 +02:00
|
|
|
elif isinstance(d, Mapping):
|
|
|
|
self.deprecate(d['msg'], version=d.get('version', None))
|
2017-02-14 05:49:39 +01:00
|
|
|
else:
|
2017-03-22 03:19:40 +01:00
|
|
|
self.deprecate(d)
|
2016-11-17 03:29:30 +01:00
|
|
|
else:
|
2017-05-14 14:06:32 +02:00
|
|
|
self.deprecate(kwargs['deprecations'])
|
2016-11-17 03:29:30 +01:00
|
|
|
|
|
|
|
if self._deprecations:
|
|
|
|
kwargs['deprecations'] = self._deprecations
|
|
|
|
|
2015-10-21 03:51:34 +02:00
|
|
|
kwargs = remove_values(kwargs, self.no_log_values)
|
2016-04-08 17:18:35 +02:00
|
|
|
print('\n%s' % self.jsonify(kwargs))
|
2016-11-17 03:29:30 +01:00
|
|
|
|
|
|
|
def exit_json(self, **kwargs):
|
|
|
|
''' return from the module, without error '''
|
|
|
|
|
|
|
|
self.do_cleanup_files()
|
|
|
|
self._return_formatted(kwargs)
|
2013-10-31 21:52:37 +01:00
|
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
def fail_json(self, **kwargs):
|
|
|
|
''' return from the module, with an error message '''
|
2016-11-17 03:29:30 +01:00
|
|
|
|
2017-11-13 17:51:18 +01:00
|
|
|
if 'msg' not in kwargs:
|
|
|
|
raise AssertionError("implementation error -- msg to explain the error is required")
|
2013-10-31 21:52:37 +01:00
|
|
|
kwargs['failed'] = True
|
2016-11-17 03:29:30 +01:00
|
|
|
|
2018-07-25 17:49:16 +02:00
|
|
|
# Add traceback if debug or high verbosity and it is missing
|
|
|
|
# NOTE: Badly named as exception, it really always has been a traceback
|
2017-06-28 16:08:38 +02:00
|
|
|
if 'exception' not in kwargs and sys.exc_info()[2] and (self._debug or self._verbosity >= 3):
|
2018-07-25 17:49:16 +02:00
|
|
|
if PY2:
|
|
|
|
# On Python 2 this is the last (stack frame) exception and as such may be unrelated to the failure
|
|
|
|
kwargs['exception'] = 'WARNING: The below traceback may *not* be related to the actual failure.\n' +\
|
|
|
|
''.join(traceback.format_tb(sys.exc_info()[2]))
|
|
|
|
else:
|
|
|
|
kwargs['exception'] = ''.join(traceback.format_tb(sys.exc_info()[2]))
|
2017-06-28 16:08:38 +02:00
|
|
|
|
2014-05-13 20:52:38 +02:00
|
|
|
self.do_cleanup_files()
|
2016-11-17 03:29:30 +01:00
|
|
|
self._return_formatted(kwargs)
|
2013-10-31 21:52:37 +01:00
|
|
|
sys.exit(1)
|
|
|
|
|
2016-02-04 22:54:03 +01:00
|
|
|
def fail_on_missing_params(self, required_params=None):
|
|
|
|
''' This is for checking for required params when we can not check via argspec because we
|
|
|
|
need more information than is simply given in the argspec.
|
|
|
|
'''
|
|
|
|
if not required_params:
|
|
|
|
return
|
|
|
|
missing_params = []
|
|
|
|
for required_param in required_params:
|
|
|
|
if not self.params.get(required_param):
|
|
|
|
missing_params.append(required_param)
|
|
|
|
if missing_params:
|
2017-02-01 21:37:08 +01:00
|
|
|
self.fail_json(msg="missing required arguments: %s" % ', '.join(missing_params))
|
2016-02-04 22:54:03 +01:00
|
|
|
|
2015-08-03 11:00:25 +02:00
|
|
|
def digest_from_file(self, filename, algorithm):
|
|
|
|
''' Return hex digest of local file for a digest_method specified by name, or None if file is not present. '''
|
2013-10-31 21:52:37 +01:00
|
|
|
if not os.path.exists(filename):
|
|
|
|
return None
|
|
|
|
if os.path.isdir(filename):
|
|
|
|
self.fail_json(msg="attempted to take checksum of directory: %s" % filename)
|
2015-08-03 11:00:25 +02:00
|
|
|
|
|
|
|
# preserve old behaviour where the third parameter was a hash algorithm object
|
|
|
|
if hasattr(algorithm, 'hexdigest'):
|
|
|
|
digest_method = algorithm
|
|
|
|
else:
|
|
|
|
try:
|
2015-08-06 23:39:31 +02:00
|
|
|
digest_method = AVAILABLE_HASH_ALGORITHMS[algorithm]()
|
2015-08-03 11:00:25 +02:00
|
|
|
except KeyError:
|
|
|
|
self.fail_json(msg="Could not hash file '%s' with algorithm '%s'. Available algorithms: %s" %
|
2015-08-06 23:39:31 +02:00
|
|
|
(filename, algorithm, ', '.join(AVAILABLE_HASH_ALGORITHMS)))
|
2015-08-03 11:00:25 +02:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
blocksize = 64 * 1024
|
2017-04-06 00:40:29 +02:00
|
|
|
infile = open(os.path.realpath(filename), 'rb')
|
2013-10-31 21:52:37 +01:00
|
|
|
block = infile.read(blocksize)
|
|
|
|
while block:
|
2015-08-03 11:00:25 +02:00
|
|
|
digest_method.update(block)
|
2013-10-31 21:52:37 +01:00
|
|
|
block = infile.read(blocksize)
|
|
|
|
infile.close()
|
2015-08-03 11:00:25 +02:00
|
|
|
return digest_method.hexdigest()
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
def md5(self, filename):
|
2014-11-10 21:00:49 +01:00
|
|
|
''' Return MD5 hex digest of local file using digest_from_file().
|
|
|
|
|
|
|
|
Do not use this function unless you have no other choice for:
|
|
|
|
1) Optional backwards compatibility
|
|
|
|
2) Compatibility with a third party protocol
|
|
|
|
|
|
|
|
This function will not work on systems complying with FIPS-140-2.
|
|
|
|
|
|
|
|
Most uses of this function can use the module.sha1 function instead.
|
|
|
|
'''
|
2015-08-06 23:39:31 +02:00
|
|
|
if 'md5' not in AVAILABLE_HASH_ALGORITHMS:
|
|
|
|
raise ValueError('MD5 not available. Possibly running in FIPS mode')
|
2015-08-03 11:00:25 +02:00
|
|
|
return self.digest_from_file(filename, 'md5')
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2014-11-07 06:28:04 +01:00
|
|
|
def sha1(self, filename):
|
|
|
|
''' Return SHA1 hex digest of local file using digest_from_file(). '''
|
2015-08-03 11:00:25 +02:00
|
|
|
return self.digest_from_file(filename, 'sha1')
|
2014-11-07 06:28:04 +01:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
def sha256(self, filename):
|
|
|
|
''' Return SHA-256 hex digest of local file using digest_from_file(). '''
|
2015-08-03 11:00:25 +02:00
|
|
|
return self.digest_from_file(filename, 'sha256')
|
2013-10-31 21:52:37 +01:00
|
|
|
|
|
|
|
def backup_local(self, fn):
|
|
|
|
'''make a date-marked backup of the specified file, return True or False on success or failure'''
|
|
|
|
|
2015-04-07 05:37:32 +02:00
|
|
|
backupdest = ''
|
|
|
|
if os.path.exists(fn):
|
2017-03-03 16:22:20 +01:00
|
|
|
# backups named basename.PID.YYYY-MM-DD@HH:MM:SS~
|
2015-04-07 05:37:32 +02:00
|
|
|
ext = time.strftime("%Y-%m-%d@%H:%M:%S~", time.localtime(time.time()))
|
2016-07-30 05:03:34 +02:00
|
|
|
backupdest = '%s.%s.%s' % (fn, os.getpid(), ext)
|
2015-04-07 05:37:32 +02:00
|
|
|
|
|
|
|
try:
|
2017-08-02 16:04:09 +02:00
|
|
|
self.preserved_copy(fn, backupdest)
|
2017-08-12 05:23:17 +02:00
|
|
|
except (shutil.Error, IOError) as e:
|
|
|
|
self.fail_json(msg='Could not make backup of %s to %s: %s' % (fn, backupdest, to_native(e)))
|
2015-04-07 05:37:32 +02:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
return backupdest
|
|
|
|
|
2014-05-13 20:52:38 +02:00
|
|
|
def cleanup(self, tmpfile):
|
2013-10-31 21:52:37 +01:00
|
|
|
if os.path.exists(tmpfile):
|
|
|
|
try:
|
|
|
|
os.unlink(tmpfile)
|
2017-08-12 05:23:17 +02:00
|
|
|
except OSError as e:
|
|
|
|
sys.stderr.write("could not cleanup %s: %s" % (tmpfile, to_native(e)))
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2017-08-02 16:04:09 +02:00
|
|
|
def preserved_copy(self, src, dest):
|
|
|
|
"""Copy a file with preserved ownership, permissions and context"""
|
|
|
|
|
|
|
|
# shutil.copy2(src, dst)
|
|
|
|
# Similar to shutil.copy(), but metadata is copied as well - in fact,
|
|
|
|
# this is just shutil.copy() followed by copystat(). This is similar
|
|
|
|
# to the Unix command cp -p.
|
|
|
|
#
|
|
|
|
# shutil.copystat(src, dst)
|
|
|
|
# Copy the permission bits, last access time, last modification time,
|
|
|
|
# and flags from src to dst. The file contents, owner, and group are
|
|
|
|
# unaffected. src and dst are path names given as strings.
|
|
|
|
|
|
|
|
shutil.copy2(src, dest)
|
|
|
|
|
|
|
|
# Set the context
|
|
|
|
if self.selinux_enabled():
|
|
|
|
context = self.selinux_context(src)
|
|
|
|
self.set_context_if_different(dest, context, False)
|
|
|
|
|
|
|
|
# chown it
|
|
|
|
try:
|
|
|
|
dest_stat = os.stat(src)
|
|
|
|
tmp_stat = os.stat(dest)
|
|
|
|
if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
|
|
|
|
os.chown(dest, dest_stat.st_uid, dest_stat.st_gid)
|
|
|
|
except OSError as e:
|
|
|
|
if e.errno != errno.EPERM:
|
|
|
|
raise
|
|
|
|
|
|
|
|
# Set the attributes
|
|
|
|
current_attribs = self.get_file_attributes(src)
|
2016-12-03 17:48:51 +01:00
|
|
|
current_attribs = current_attribs.get('attr_flags', '')
|
2017-08-02 16:04:09 +02:00
|
|
|
self.set_attributes_if_different(dest, current_attribs, True)
|
|
|
|
|
2016-02-04 03:15:48 +01:00
|
|
|
def atomic_move(self, src, dest, unsafe_writes=False):
|
2013-10-31 21:52:37 +01:00
|
|
|
'''atomically move src to dest, copying attributes from dest, returns true on success
|
|
|
|
it uses os.rename to ensure this as it is an atomic operation, rest of the function is
|
|
|
|
to work around limitations, corner cases and ensure selinux context is saved if possible'''
|
|
|
|
context = None
|
2014-03-25 19:00:38 +01:00
|
|
|
dest_stat = None
|
2016-09-01 13:19:03 +02:00
|
|
|
b_src = to_bytes(src, errors='surrogate_or_strict')
|
|
|
|
b_dest = to_bytes(dest, errors='surrogate_or_strict')
|
2016-08-29 18:11:40 +02:00
|
|
|
if os.path.exists(b_dest):
|
2013-10-31 21:52:37 +01:00
|
|
|
try:
|
2016-08-29 18:11:40 +02:00
|
|
|
dest_stat = os.stat(b_dest)
|
2016-12-20 22:03:21 +01:00
|
|
|
|
|
|
|
# copy mode and ownership
|
2016-08-29 18:11:40 +02:00
|
|
|
os.chmod(b_src, dest_stat.st_mode & PERM_BITS)
|
|
|
|
os.chown(b_src, dest_stat.st_uid, dest_stat.st_gid)
|
2016-12-20 22:03:21 +01:00
|
|
|
|
|
|
|
# try to copy flags if possible
|
|
|
|
if hasattr(os, 'chflags') and hasattr(dest_stat, 'st_flags'):
|
|
|
|
try:
|
|
|
|
os.chflags(b_src, dest_stat.st_flags)
|
2017-08-12 05:23:17 +02:00
|
|
|
except OSError as e:
|
2016-12-20 22:03:21 +01:00
|
|
|
for err in 'EOPNOTSUPP', 'ENOTSUP':
|
|
|
|
if hasattr(errno, err) and e.errno == getattr(errno, err):
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
raise
|
2017-08-12 05:23:17 +02:00
|
|
|
except OSError as e:
|
2013-10-31 21:52:37 +01:00
|
|
|
if e.errno != errno.EPERM:
|
|
|
|
raise
|
|
|
|
if self.selinux_enabled():
|
|
|
|
context = self.selinux_context(dest)
|
|
|
|
else:
|
|
|
|
if self.selinux_enabled():
|
|
|
|
context = self.selinux_default_context(dest)
|
|
|
|
|
2016-08-29 18:11:40 +02:00
|
|
|
creating = not os.path.exists(b_dest)
|
2014-06-03 16:36:19 +02:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
try:
|
2014-03-14 04:07:35 +01:00
|
|
|
# Optimistically try a rename, solves some corner cases and can avoid useless work, throws exception if not atomic.
|
2016-08-29 18:11:40 +02:00
|
|
|
os.rename(b_src, b_dest)
|
2017-08-12 05:23:17 +02:00
|
|
|
except (IOError, OSError) as e:
|
2016-09-22 17:31:35 +02:00
|
|
|
if e.errno not in [errno.EPERM, errno.EXDEV, errno.EACCES, errno.ETXTBSY, errno.EBUSY]:
|
2016-02-04 03:15:48 +01:00
|
|
|
# only try workarounds for errno 18 (cross device), 1 (not permitted), 13 (permission denied)
|
|
|
|
# and 26 (text file busy) which happens on vagrant synced folders and other 'exotic' non posix file systems
|
2017-08-12 05:23:17 +02:00
|
|
|
self.fail_json(msg='Could not replace file: %s to %s: %s' % (src, dest, to_native(e)),
|
|
|
|
exception=traceback.format_exc())
|
2016-02-15 10:18:44 +01:00
|
|
|
else:
|
2016-09-03 05:32:14 +02:00
|
|
|
# Use bytes here. In the shippable CI, this fails with
|
|
|
|
# a UnicodeError with surrogateescape'd strings for an unknown
|
|
|
|
# reason (doesn't happen in a local Ubuntu16.04 VM)
|
2018-05-17 21:32:45 +02:00
|
|
|
b_dest_dir = os.path.dirname(b_dest)
|
|
|
|
b_suffix = os.path.basename(b_dest)
|
2017-07-20 21:41:57 +02:00
|
|
|
error_msg = None
|
|
|
|
tmp_dest_name = None
|
2014-08-21 21:07:18 +02:00
|
|
|
try:
|
2018-05-17 21:32:45 +02:00
|
|
|
tmp_dest_fd, tmp_dest_name = tempfile.mkstemp(prefix=b'.ansible_tmp',
|
|
|
|
dir=b_dest_dir, suffix=b_suffix)
|
2017-08-12 05:23:17 +02:00
|
|
|
except (OSError, IOError) as e:
|
|
|
|
error_msg = 'The destination directory (%s) is not writable by the current user. Error was: %s' % (os.path.dirname(dest), to_native(e))
|
2016-10-26 23:51:38 +02:00
|
|
|
except TypeError:
|
|
|
|
# We expect that this is happening because python3.4.x and
|
|
|
|
# below can't handle byte strings in mkstemp(). Traceback
|
|
|
|
# would end in something like:
|
|
|
|
# file = _os.path.join(dir, pre + name + suf)
|
|
|
|
# TypeError: can't concat bytes to str
|
2018-02-15 18:01:02 +01:00
|
|
|
error_msg = ('Failed creating tmp file for atomic move. This usually happens when using Python3 less than Python3.5. '
|
2017-07-20 21:41:57 +02:00
|
|
|
'Please use Python2.x or Python3.5 or greater.')
|
|
|
|
finally:
|
|
|
|
if error_msg:
|
|
|
|
if unsafe_writes:
|
|
|
|
self._unsafe_writes(b_src, b_dest)
|
|
|
|
else:
|
|
|
|
self.fail_json(msg=error_msg, exception=traceback.format_exc())
|
2016-10-26 23:51:38 +02:00
|
|
|
|
2017-07-20 21:41:57 +02:00
|
|
|
if tmp_dest_name:
|
|
|
|
b_tmp_dest_name = to_bytes(tmp_dest_name, errors='surrogate_or_strict')
|
2016-02-15 10:18:44 +01:00
|
|
|
|
|
|
|
try:
|
2016-02-15 18:08:07 +01:00
|
|
|
try:
|
2017-07-20 21:41:57 +02:00
|
|
|
# close tmp file handle before file operations to prevent text file busy errors on vboxfs synced folders (windows host)
|
|
|
|
os.close(tmp_dest_fd)
|
|
|
|
# leaves tmp file behind when sudo and not root
|
|
|
|
try:
|
|
|
|
shutil.move(b_src, b_tmp_dest_name)
|
|
|
|
except OSError:
|
2018-02-15 18:01:02 +01:00
|
|
|
# cleanup will happen by 'rm' of tmpdir
|
2017-07-20 21:41:57 +02:00
|
|
|
# copy2 will preserve some metadata
|
|
|
|
shutil.copy2(b_src, b_tmp_dest_name)
|
|
|
|
|
|
|
|
if self.selinux_enabled():
|
|
|
|
self.set_context_if_different(
|
|
|
|
b_tmp_dest_name, context, False)
|
|
|
|
try:
|
|
|
|
tmp_stat = os.stat(b_tmp_dest_name)
|
|
|
|
if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
|
|
|
|
os.chown(b_tmp_dest_name, dest_stat.st_uid, dest_stat.st_gid)
|
2017-08-12 05:23:17 +02:00
|
|
|
except OSError as e:
|
2017-07-20 21:41:57 +02:00
|
|
|
if e.errno != errno.EPERM:
|
|
|
|
raise
|
|
|
|
try:
|
|
|
|
os.rename(b_tmp_dest_name, b_dest)
|
2017-08-12 05:23:17 +02:00
|
|
|
except (shutil.Error, OSError, IOError) as e:
|
2017-07-20 21:41:57 +02:00
|
|
|
if unsafe_writes and e.errno == errno.EBUSY:
|
|
|
|
self._unsafe_writes(b_tmp_dest_name, b_dest)
|
|
|
|
else:
|
2018-07-19 18:13:09 +02:00
|
|
|
self.fail_json(msg='Unable to make %s into to %s, failed final rename from %s: %s' %
|
|
|
|
(src, dest, b_tmp_dest_name, to_native(e)),
|
2017-08-12 05:23:17 +02:00
|
|
|
exception=traceback.format_exc())
|
|
|
|
except (shutil.Error, OSError, IOError) as e:
|
|
|
|
self.fail_json(msg='Failed to replace file: %s to %s: %s' % (src, dest, to_native(e)),
|
|
|
|
exception=traceback.format_exc())
|
2017-07-20 21:41:57 +02:00
|
|
|
finally:
|
|
|
|
self.cleanup(b_tmp_dest_name)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2014-04-29 15:40:08 +02:00
|
|
|
if creating:
|
|
|
|
# make sure the file has the correct permissions
|
|
|
|
# based on the current value of umask
|
|
|
|
umask = os.umask(0)
|
|
|
|
os.umask(umask)
|
2016-08-29 18:11:40 +02:00
|
|
|
os.chmod(b_dest, DEFAULT_PERM & ~umask)
|
2017-01-04 21:31:29 +01:00
|
|
|
try:
|
2017-01-03 22:33:13 +01:00
|
|
|
os.chown(b_dest, os.geteuid(), os.getegid())
|
2017-01-04 21:31:29 +01:00
|
|
|
except OSError:
|
|
|
|
# We're okay with trying our best here. If the user is not
|
|
|
|
# root (or old Unices) they won't be able to chown.
|
|
|
|
pass
|
2014-03-24 21:10:43 +01:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
if self.selinux_enabled():
|
|
|
|
# rename might not preserve context
|
|
|
|
self.set_context_if_different(dest, context, False)
|
|
|
|
|
2016-12-20 21:53:46 +01:00
|
|
|
def _unsafe_writes(self, src, dest):
|
2016-12-20 16:36:17 +01:00
|
|
|
# sadly there are some situations where we cannot ensure atomicity, but only if
|
|
|
|
# the user insists and we get the appropriate error we update the file unsafely
|
2016-12-20 21:53:46 +01:00
|
|
|
try:
|
2017-10-16 16:43:22 +02:00
|
|
|
out_dest = in_src = None
|
2016-12-20 16:36:17 +01:00
|
|
|
try:
|
2016-12-20 21:53:46 +01:00
|
|
|
out_dest = open(dest, 'wb')
|
|
|
|
in_src = open(src, 'rb')
|
|
|
|
shutil.copyfileobj(in_src, out_dest)
|
|
|
|
finally: # assuring closed files in 2.4 compatible way
|
|
|
|
if out_dest:
|
|
|
|
out_dest.close()
|
|
|
|
if in_src:
|
|
|
|
in_src.close()
|
2017-08-12 05:23:17 +02:00
|
|
|
except (shutil.Error, OSError, IOError) as e:
|
|
|
|
self.fail_json(msg='Could not write data to file (%s) from (%s): %s' % (dest, src, to_native(e)),
|
|
|
|
exception=traceback.format_exc())
|
2016-12-20 16:36:17 +01:00
|
|
|
|
2016-12-13 15:29:10 +01:00
|
|
|
def _read_from_pipes(self, rpipes, rfds, file_descriptor):
|
|
|
|
data = b('')
|
|
|
|
if file_descriptor in rfds:
|
|
|
|
data = os.read(file_descriptor.fileno(), 9000)
|
|
|
|
if data == b(''):
|
|
|
|
rpipes.remove(file_descriptor)
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
2017-10-06 00:12:02 +02:00
|
|
|
def _clean_args(self, args):
|
|
|
|
|
|
|
|
if not self._clean:
|
|
|
|
# create a printable version of the command for use in reporting later,
|
|
|
|
# which strips out things like passwords from the args list
|
|
|
|
to_clean_args = args
|
|
|
|
if PY2:
|
|
|
|
if isinstance(args, text_type):
|
|
|
|
to_clean_args = to_bytes(args)
|
|
|
|
else:
|
|
|
|
if isinstance(args, binary_type):
|
|
|
|
to_clean_args = to_text(args)
|
|
|
|
if isinstance(args, (text_type, binary_type)):
|
|
|
|
to_clean_args = shlex.split(to_clean_args)
|
|
|
|
|
|
|
|
clean_args = []
|
|
|
|
is_passwd = False
|
|
|
|
for arg in (to_native(a) for a in to_clean_args):
|
|
|
|
if is_passwd:
|
|
|
|
is_passwd = False
|
|
|
|
clean_args.append('********')
|
|
|
|
continue
|
|
|
|
if PASSWD_ARG_RE.match(arg):
|
|
|
|
sep_idx = arg.find('=')
|
|
|
|
if sep_idx > -1:
|
|
|
|
clean_args.append('%s=********' % arg[:sep_idx])
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
is_passwd = True
|
|
|
|
arg = heuristic_log_sanitize(arg, self.no_log_values)
|
|
|
|
clean_args.append(arg)
|
|
|
|
self._clean = ' '.join(shlex_quote(arg) for arg in clean_args)
|
|
|
|
|
|
|
|
return self._clean
|
|
|
|
|
2018-08-03 18:35:34 +02:00
|
|
|
def _restore_signal_handlers(self):
|
|
|
|
# Reset SIGPIPE to SIG_DFL, otherwise in Python2.7 it gets ignored in subprocesses.
|
|
|
|
if PY2 and sys.platform != 'win32':
|
|
|
|
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
|
|
|
|
|
2017-03-23 02:50:28 +01:00
|
|
|
def run_command(self, args, check_rc=False, close_fds=True, executable=None, data=None, binary_data=False, path_prefix=None, cwd=None,
|
2018-09-14 22:07:11 +02:00
|
|
|
use_unsafe_shell=False, prompt_regex=None, environ_update=None, umask=None, encoding='utf-8', errors='surrogate_or_strict',
|
2018-11-05 21:00:34 +01:00
|
|
|
expand_user_and_vars=True, pass_fds=None, before_communicate_callback=None):
|
2013-10-31 21:52:37 +01:00
|
|
|
'''
|
|
|
|
Execute a command, returns rc, stdout, and stderr.
|
2016-01-20 18:04:44 +01:00
|
|
|
|
|
|
|
:arg args: is the command to run
|
|
|
|
* If args is a list, the command will be run with shell=False.
|
|
|
|
* If args is a string and use_unsafe_shell=False it will split args to a list and run with shell=False
|
|
|
|
* If args is a string and use_unsafe_shell=True it runs with shell=True.
|
|
|
|
:kw check_rc: Whether to call fail_json in case of non zero RC.
|
|
|
|
Default False
|
|
|
|
:kw close_fds: See documentation for subprocess.Popen(). Default True
|
|
|
|
:kw executable: See documentation for subprocess.Popen(). Default None
|
|
|
|
:kw data: If given, information to write to the stdin of the command
|
|
|
|
:kw binary_data: If False, append a newline to the data. Default False
|
|
|
|
:kw path_prefix: If given, additional path to find the command in.
|
2018-11-20 06:01:54 +01:00
|
|
|
This adds to the PATH environment variable so helper commands in
|
2016-01-20 18:04:44 +01:00
|
|
|
the same directory can also be found
|
2016-08-27 04:52:12 +02:00
|
|
|
:kw cwd: If given, working directory to run the command inside
|
2016-01-20 18:04:44 +01:00
|
|
|
:kw use_unsafe_shell: See `args` parameter. Default False
|
|
|
|
:kw prompt_regex: Regex string (not a compiled regex) which can be
|
|
|
|
used to detect prompts in the stdout which would otherwise cause
|
|
|
|
the execution to hang (especially if no input data is specified)
|
2016-10-03 20:04:12 +02:00
|
|
|
:kw environ_update: dictionary to *update* os.environ with
|
2016-09-24 18:29:15 +02:00
|
|
|
:kw umask: Umask to be used when running the command. Default None
|
2016-10-03 20:04:12 +02:00
|
|
|
:kw encoding: Since we return native strings, on python3 we need to
|
|
|
|
know the encoding to use to transform from bytes to text. If you
|
|
|
|
want to always get bytes back, use encoding=None. The default is
|
|
|
|
"utf-8". This does not affect transformation of strings given as
|
|
|
|
args.
|
|
|
|
:kw errors: Since we return native strings, on python3 we need to
|
|
|
|
transform stdout and stderr from bytes to text. If the bytes are
|
|
|
|
undecodable in the ``encoding`` specified, then use this error
|
|
|
|
handler to deal with them. The default is ``surrogate_or_strict``
|
|
|
|
which means that the bytes will be decoded using the
|
|
|
|
surrogateescape error handler if available (available on all
|
|
|
|
python3 versions we support) otherwise a UnicodeError traceback
|
|
|
|
will be raised. This does not affect transformations of strings
|
|
|
|
given as args.
|
2018-09-14 22:07:11 +02:00
|
|
|
:kw expand_user_and_vars: When ``use_unsafe_shell=False`` this argument
|
|
|
|
dictates whether ``~`` is expanded in paths and environment variables
|
|
|
|
are expanded before running the command. When ``True`` a string such as
|
|
|
|
``$SHELL`` will be expanded regardless of escaping. When ``False`` and
|
|
|
|
``use_unsafe_shell=False`` no path or variable expansion will be done.
|
2018-11-05 21:00:34 +01:00
|
|
|
:kw pass_fds: When running on python3 this argument
|
|
|
|
dictates which file descriptors should be passed
|
|
|
|
to an underlying ``Popen`` constructor.
|
|
|
|
:kw before_communicate_callback: This function will be called
|
|
|
|
after ``Popen`` object will be created
|
|
|
|
but before communicating to the process.
|
|
|
|
(``Popen`` object will be passed to callback as a first argument)
|
2016-10-03 20:04:12 +02:00
|
|
|
:returns: A 3-tuple of return code (integer), stdout (native string),
|
|
|
|
and stderr (native string). On python2, stdout and stderr are both
|
|
|
|
byte strings. On python3, stdout and stderr are text strings converted
|
|
|
|
according to the encoding and errors parameters. If you want byte
|
|
|
|
strings on python3, use encoding=None to turn decoding to text off.
|
2013-10-31 21:52:37 +01:00
|
|
|
'''
|
2017-10-06 00:12:02 +02:00
|
|
|
# used by clean args later on
|
|
|
|
self._clean = None
|
2014-03-10 22:11:24 +01:00
|
|
|
|
2017-10-05 17:02:41 +02:00
|
|
|
if not isinstance(args, (list, binary_type, text_type)):
|
|
|
|
msg = "Argument 'args' to run_command must be list or string"
|
|
|
|
self.fail_json(rc=257, cmd=args, msg=msg)
|
|
|
|
|
|
|
|
shell = False
|
|
|
|
if use_unsafe_shell:
|
|
|
|
|
|
|
|
# stringify args for unsafe/direct shell usage
|
|
|
|
if isinstance(args, list):
|
2017-05-02 20:01:57 +02:00
|
|
|
args = " ".join([shlex_quote(x) for x in args])
|
2017-10-05 17:02:41 +02:00
|
|
|
|
|
|
|
# not set explicitly, check if set by controller
|
|
|
|
if executable:
|
|
|
|
args = [executable, '-c', args]
|
|
|
|
elif self._shell not in (None, '/bin/sh'):
|
|
|
|
args = [self._shell, '-c', args]
|
2017-09-28 18:02:26 +02:00
|
|
|
else:
|
2017-10-05 17:02:41 +02:00
|
|
|
shell = True
|
|
|
|
else:
|
|
|
|
# ensure args are a list
|
|
|
|
if isinstance(args, (binary_type, text_type)):
|
2017-05-01 21:21:44 +02:00
|
|
|
# On python2.6 and below, shlex has problems with text type
|
|
|
|
# On python3, shlex needs a text type.
|
|
|
|
if PY2:
|
|
|
|
args = to_bytes(args, errors='surrogate_or_strict')
|
|
|
|
elif PY3:
|
|
|
|
args = to_text(args, errors='surrogateescape')
|
|
|
|
args = shlex.split(args)
|
2014-03-10 22:11:24 +01:00
|
|
|
|
2018-09-14 22:07:11 +02:00
|
|
|
# expand ``~`` in paths, and all environment vars
|
|
|
|
if expand_user_and_vars:
|
|
|
|
args = [os.path.expanduser(os.path.expandvars(x)) for x in args if x is not None]
|
|
|
|
else:
|
|
|
|
args = [x for x in args if x is not None]
|
2017-05-01 21:21:44 +02:00
|
|
|
|
2014-11-11 06:41:50 +01:00
|
|
|
prompt_re = None
|
|
|
|
if prompt_regex:
|
2016-06-05 01:19:57 +02:00
|
|
|
if isinstance(prompt_regex, text_type):
|
|
|
|
if PY3:
|
2016-08-26 10:30:46 +02:00
|
|
|
prompt_regex = to_bytes(prompt_regex, errors='surrogateescape')
|
2016-06-05 01:19:57 +02:00
|
|
|
elif PY2:
|
2016-09-01 13:19:03 +02:00
|
|
|
prompt_regex = to_bytes(prompt_regex, errors='surrogate_or_strict')
|
2014-11-11 06:41:50 +01:00
|
|
|
try:
|
|
|
|
prompt_re = re.compile(prompt_regex, re.MULTILINE)
|
|
|
|
except re.error:
|
|
|
|
self.fail_json(msg="invalid prompt regular expression given to run_command")
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
rc = 0
|
|
|
|
msg = None
|
|
|
|
st_in = None
|
2013-11-07 21:50:41 +01:00
|
|
|
|
2016-01-20 18:04:44 +01:00
|
|
|
# Manipulate the environ we'll send to the new process
|
|
|
|
old_env_vals = {}
|
2016-02-07 21:45:03 +01:00
|
|
|
# We can set this from both an attribute and per call
|
|
|
|
for key, val in self.run_command_environ_update.items():
|
|
|
|
old_env_vals[key] = os.environ.get(key, None)
|
|
|
|
os.environ[key] = val
|
2016-01-20 18:04:44 +01:00
|
|
|
if environ_update:
|
|
|
|
for key, val in environ_update.items():
|
|
|
|
old_env_vals[key] = os.environ.get(key, None)
|
|
|
|
os.environ[key] = val
|
2013-11-07 21:50:41 +01:00
|
|
|
if path_prefix:
|
2016-01-20 18:04:44 +01:00
|
|
|
old_env_vals['PATH'] = os.environ['PATH']
|
|
|
|
os.environ['PATH'] = "%s:%s" % (path_prefix, os.environ['PATH'])
|
2013-11-07 21:50:41 +01:00
|
|
|
|
2016-05-02 17:29:35 +02:00
|
|
|
# If using test-module and explode, the remote lib path will resemble ...
|
|
|
|
# /tmp/test_module_scratch/debug_dir/ansible/module_utils/basic.py
|
|
|
|
# If using ansible or ansible-playbook with a remote system ...
|
|
|
|
# /tmp/ansible_vmweLQ/ansible_modlib.zip/ansible/module_utils/basic.py
|
|
|
|
|
2016-07-21 19:58:24 +02:00
|
|
|
# Clean out python paths set by ansiballz
|
2016-05-02 17:29:35 +02:00
|
|
|
if 'PYTHONPATH' in os.environ:
|
|
|
|
pypaths = os.environ['PYTHONPATH'].split(':')
|
2017-06-02 13:14:11 +02:00
|
|
|
pypaths = [x for x in pypaths
|
|
|
|
if not x.endswith('/ansible_modlib.zip') and
|
|
|
|
not x.endswith('/debug_dir')]
|
2016-05-02 17:29:35 +02:00
|
|
|
os.environ['PYTHONPATH'] = ':'.join(pypaths)
|
2016-06-15 16:02:56 +02:00
|
|
|
if not os.environ['PYTHONPATH']:
|
|
|
|
del os.environ['PYTHONPATH']
|
2016-05-02 17:29:35 +02:00
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
if data:
|
|
|
|
st_in = subprocess.PIPE
|
2014-03-10 22:11:24 +01:00
|
|
|
|
|
|
|
kwargs = dict(
|
|
|
|
executable=executable,
|
|
|
|
shell=shell,
|
|
|
|
close_fds=close_fds,
|
2014-08-04 22:32:41 +02:00
|
|
|
stdin=st_in,
|
2014-03-10 22:11:24 +01:00
|
|
|
stdout=subprocess.PIPE,
|
2016-01-20 18:04:44 +01:00
|
|
|
stderr=subprocess.PIPE,
|
2018-08-03 18:35:34 +02:00
|
|
|
preexec_fn=self._restore_signal_handlers,
|
2014-03-10 22:11:24 +01:00
|
|
|
)
|
2018-11-05 21:00:34 +01:00
|
|
|
if PY3 and pass_fds:
|
|
|
|
kwargs["pass_fds"] = pass_fds
|
2014-03-10 22:11:24 +01:00
|
|
|
|
2014-03-13 22:15:23 +01:00
|
|
|
# store the pwd
|
|
|
|
prev_dir = os.getcwd()
|
2014-03-10 22:11:24 +01:00
|
|
|
|
2014-03-13 22:15:23 +01:00
|
|
|
# make sure we're in the right working directory
|
|
|
|
if cwd and os.path.isdir(cwd):
|
2016-12-22 09:19:50 +01:00
|
|
|
cwd = os.path.abspath(os.path.expanduser(cwd))
|
|
|
|
kwargs['cwd'] = cwd
|
2014-03-13 22:15:23 +01:00
|
|
|
try:
|
2014-03-12 19:59:50 +01:00
|
|
|
os.chdir(cwd)
|
2017-08-12 05:23:17 +02:00
|
|
|
except (OSError, IOError) as e:
|
|
|
|
self.fail_json(rc=e.errno, msg="Could not open %s, %s" % (cwd, to_native(e)),
|
|
|
|
exception=traceback.format_exc())
|
2014-03-12 20:33:31 +01:00
|
|
|
|
2016-09-24 18:29:15 +02:00
|
|
|
old_umask = None
|
|
|
|
if umask:
|
|
|
|
old_umask = os.umask(umask)
|
|
|
|
|
2014-03-13 22:15:23 +01:00
|
|
|
try:
|
2015-10-01 06:09:15 +02:00
|
|
|
if self._debug:
|
2017-10-06 00:12:02 +02:00
|
|
|
self.log('Executing: ' + self._clean_args(args))
|
2014-03-10 22:11:24 +01:00
|
|
|
cmd = subprocess.Popen(args, **kwargs)
|
2018-11-05 21:00:34 +01:00
|
|
|
if before_communicate_callback:
|
|
|
|
before_communicate_callback(cmd)
|
2014-03-10 22:11:24 +01:00
|
|
|
|
2014-08-04 22:32:41 +02:00
|
|
|
# the communication logic here is essentially taken from that
|
|
|
|
# of the _communicate() function in ssh.py
|
|
|
|
|
2016-06-05 01:19:57 +02:00
|
|
|
stdout = b('')
|
|
|
|
stderr = b('')
|
2014-08-04 22:32:41 +02:00
|
|
|
rpipes = [cmd.stdout, cmd.stderr]
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
if data:
|
|
|
|
if not binary_data:
|
2014-03-13 20:28:51 +01:00
|
|
|
data += '\n'
|
2016-06-05 01:19:57 +02:00
|
|
|
if isinstance(data, text_type):
|
2016-09-07 07:54:17 +02:00
|
|
|
data = to_bytes(data)
|
2014-08-04 22:32:41 +02:00
|
|
|
cmd.stdin.write(data)
|
|
|
|
cmd.stdin.close()
|
|
|
|
|
|
|
|
while True:
|
2016-12-13 15:29:10 +01:00
|
|
|
rfds, wfds, efds = select.select(rpipes, [], rpipes, 1)
|
|
|
|
stdout += self._read_from_pipes(rpipes, rfds, cmd.stdout)
|
|
|
|
stderr += self._read_from_pipes(rpipes, rfds, cmd.stderr)
|
2014-11-11 06:41:50 +01:00
|
|
|
# if we're checking for prompts, do it now
|
|
|
|
if prompt_re:
|
|
|
|
if prompt_re.search(stdout) and not data:
|
2016-10-04 03:45:28 +02:00
|
|
|
if encoding:
|
|
|
|
stdout = to_native(stdout, encoding=encoding, errors=errors)
|
|
|
|
else:
|
|
|
|
stdout = stdout
|
2015-06-24 19:22:37 +02:00
|
|
|
return (257, stdout, "A prompt was encountered while running a command, but no input data was specified")
|
2014-08-04 22:32:41 +02:00
|
|
|
# only break out if no pipes are left to read or
|
|
|
|
# the pipes are completely read and
|
|
|
|
# the process is terminated
|
2016-12-13 15:29:10 +01:00
|
|
|
if (not rpipes or not rfds) and cmd.poll() is not None:
|
2014-08-04 22:32:41 +02:00
|
|
|
break
|
|
|
|
# No pipes are left to read but process is not yet terminated
|
|
|
|
# Only then it is safe to wait for the process to be finished
|
|
|
|
# NOTE: Actually cmd.poll() is always None here if rpipes is empty
|
2017-01-28 09:12:11 +01:00
|
|
|
elif not rpipes and cmd.poll() is None:
|
2014-08-04 22:32:41 +02:00
|
|
|
cmd.wait()
|
|
|
|
# The process is terminated. Since no pipes to read from are
|
|
|
|
# left, there is no need to call select() again.
|
|
|
|
break
|
|
|
|
|
|
|
|
cmd.stdout.close()
|
|
|
|
cmd.stderr.close()
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
rc = cmd.returncode
|
2017-08-12 05:23:17 +02:00
|
|
|
except (OSError, IOError) as e:
|
2017-10-06 00:12:02 +02:00
|
|
|
self.log("Error Executing CMD:%s Exception:%s" % (self._clean_args(args), to_native(e)))
|
|
|
|
self.fail_json(rc=e.errno, msg=to_native(e), cmd=self._clean_args(args))
|
2017-08-12 05:23:17 +02:00
|
|
|
except Exception as e:
|
2017-10-06 00:12:02 +02:00
|
|
|
self.log("Error Executing CMD:%s Exception:%s" % (self._clean_args(args), to_native(traceback.format_exc())))
|
|
|
|
self.fail_json(rc=257, msg=to_native(e), exception=traceback.format_exc(), cmd=self._clean_args(args))
|
2014-03-13 21:06:59 +01:00
|
|
|
|
2016-01-20 18:04:44 +01:00
|
|
|
# Restore env settings
|
|
|
|
for key, val in old_env_vals.items():
|
|
|
|
if val is None:
|
|
|
|
del os.environ[key]
|
|
|
|
else:
|
|
|
|
os.environ[key] = val
|
|
|
|
|
2016-09-24 18:29:15 +02:00
|
|
|
if old_umask:
|
|
|
|
os.umask(old_umask)
|
|
|
|
|
2013-10-31 21:52:37 +01:00
|
|
|
if rc != 0 and check_rc:
|
2015-10-21 03:51:34 +02:00
|
|
|
msg = heuristic_log_sanitize(stderr.rstrip(), self.no_log_values)
|
2017-10-06 00:12:02 +02:00
|
|
|
self.fail_json(cmd=self._clean_args(args), rc=rc, stdout=stdout, stderr=stderr, msg=msg)
|
2014-03-13 22:15:23 +01:00
|
|
|
|
|
|
|
# reset the pwd
|
|
|
|
os.chdir(prev_dir)
|
|
|
|
|
2016-10-03 20:04:12 +02:00
|
|
|
if encoding is not None:
|
|
|
|
return (rc, to_native(stdout, encoding=encoding, errors=errors),
|
|
|
|
to_native(stderr, encoding=encoding, errors=errors))
|
2017-10-06 00:12:02 +02:00
|
|
|
|
2014-08-04 22:32:41 +02:00
|
|
|
return (rc, stdout, stderr)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2014-03-12 15:55:54 +01:00
|
|
|
def append_to_file(self, filename, str):
|
|
|
|
filename = os.path.expandvars(os.path.expanduser(filename))
|
|
|
|
fh = open(filename, 'a')
|
|
|
|
fh.write(str)
|
|
|
|
fh.close()
|
|
|
|
|
2016-08-16 19:45:41 +02:00
|
|
|
def bytes_to_human(self, size):
|
2016-08-24 21:04:20 +02:00
|
|
|
return bytes_to_human(size)
|
2013-10-31 21:52:37 +01:00
|
|
|
|
2016-08-16 19:45:41 +02:00
|
|
|
# for backwards compatibility
|
|
|
|
pretty_bytes = bytes_to_human
|
|
|
|
|
2016-08-24 21:04:20 +02:00
|
|
|
def human_to_bytes(self, number, isbits=False):
|
|
|
|
return human_to_bytes(number, isbits)
|
2016-08-16 19:45:41 +02:00
|
|
|
|
2015-09-25 16:46:09 +02:00
|
|
|
#
|
|
|
|
# Backwards compat
|
|
|
|
#
|
|
|
|
|
|
|
|
# In 2.0, moved from inside the module to the toplevel
|
|
|
|
is_executable = is_executable
|
|
|
|
|
|
|
|
|
2014-03-19 15:30:10 +01:00
|
|
|
def get_module_path():
|
|
|
|
return os.path.dirname(os.path.realpath(__file__))
|