ansible/test/runner/injector/injector.py
Matt Clay ca13e678ae Backport test infra fixes and updates to stable-2.5. (#46992)
* Fix unit test parametrize order on Python 3.5.

(cherry picked from commit 53b230ca74)

* Fix ansible-test unit test execution. (#45772)

* Fix ansible-test units requirements install.
* Run unit tests as unprivileged user under Docker.

(cherry picked from commit 379a7f4f5a)

* Run unit tests in parallel. (#45812)

(cherry picked from commit abe8e4c9e8)

* Minor fixes for unit test delegation.

(cherry picked from commit be199cfe90)

* add support for opening shell on remote Windows host (#43919)

* add support for opening shell on remote Windows host

* added arg completion and fix sanity check

* remove uneeded arg

(cherry picked from commit 6ca4ea0c1f)

* Block network access for unit tests in docker.

(cherry picked from commit 99cac99cbc)

* Make ansible-test available in the bin directory. (#45876)

(cherry picked from commit f3d1f9544b)

* Support comments in ansible-test flat files.

(cherry picked from commit 5a3000af19)

* Fix incorrect use of subprocess.CalledProcessError (#45890)

(cherry picked from commit 24dd87bd0a)

* Improve ansible-test match error handling.

(cherry picked from commit 2056c981ae)

* Improve error handling for docs-build test.

(cherry picked from commit 2148999048)

* Bug fixes and cleanup for ansible-test. (#45991)

* Remove unused imports.
* Clean up ConfigParser usage in ansible-test.
* Fix bare except statements in ansible-test.
* Miscellaneous cleanup from PyCharm inspections.
* Enable pylint no-self-use for ansible-test.
* Remove obsolete pylint ignores for Python 3.7.
* Fix shellcheck issuers under newer shellcheck.
* Use newer path for ansible-test.
* Fix issues in code-smell tests.

(cherry picked from commit ac492476e5)

* Fix integration test library search path.

This prevents tests from loading modules outside the source tree,
which could result in testing the wrong module if a system-wide
install is present, or custom modules exist.

(cherry picked from commit d603cd41fe)

* Update default container to version 1.2.0.

(cherry picked from commit d478a4c3f6)
(cherry picked from commit 21c4eb8db5)

* Fix ansible-test docker python version handling.

This removes the old name based version detection behavior and
uses versions defined in the docker completion file instead, as
the new containers do not follow the old naming scheme.

(cherry picked from commit 54937ba784)

* Reduce noise in docs-build test failures.

(cherry picked from commit 4085d01617)

* Fix ansible-test encoding issues for exceptions.

(cherry picked from commit 0d7a156319)

* Fix ansible-test multi-group smoke test handling. (#46363)

* Fix ansible-test smoke tests across groups.
* Fix ansible-test list arg defaults.
* Fix ansible-test require and exclude delegation.
* Fix detection of Windows specific changes.
* Add minimal Windows testing for Python 3.7.

(cherry picked from commit e53390b3b1)

* Use default-test-container version 1.3.0.

(cherry picked from commit 6d9be66418)

* Add file exists check in integration-aliases test.

(cherry picked from commit 33a8be9109)

* Improve ansible-test environment checking between tests. (#46459)

* Add unified diff output to environment validation.

This makes it easier to see where the environment changed.

* Compare Python interpreters by version to pip shebangs.

This helps expose cases where pip executables use a different
Python interpreter than is expected.

* Query `pip.__version__` instead of using `pip --version`.

This is a much faster way to query the pip version. It also more
closely matches how we invoke pip within ansible-test.

* Remove redundant environment scan between tests.

This reuses the environment scan from the end of the previous test
as the basis for comparison during the next test.

(cherry picked from commit 0dc7f38787)

* Add symlinks sanity test. (#46467)

* Add symlinks sanity test.
* Replace legacy test symlinks with actual content.
* Remove dir symlink from template_jinja2_latest.
* Update import test to use generated library dir.
* Fix copy test symlink setup.

(cherry picked from commit e2b6047514)

* Fix parametrize warning in unit tests.

(cherry picked from commit 1a28898a00)

* Update MANIFEST.in (#46502)

* Update MANIFEST.in:

- Remove unnecessary prune.
- Include files needed by tests.
- Exclude botmeta sanity test.

These changes permit sanity tests to pass on sdist output.
(cherry picked from commit cbb49f66ec)

* Fix unit tests which modify the source tree. (#45763)

* Fix CNOS unit test log usage.
* Use temp dir for Galaxy unit tests.
* Write to temp files in interfaces_file unit test.
* Fix log placement in netapp_e_ldap unit test.

(cherry picked from commit 0686450cae)

* Fix ansible-test custom docker image traceback.

(cherry picked from commit 712ad9ed64)

* ansible-test: Create public key creating Windows targets (#43760)

* ansible-test: Create public key creating Windows targets

* Changed to always set SSH Key for Windows hosts

(cherry picked from commit adc0efe10c)

* Fix and re-enable sts_assume_role integration tests (#46026)

* Fix the STS assume role error message assertion when the role to assume does not exist.

(cherry picked from commit 18dc928e28)

* Fix ACI unit test on Python 3.7.0.

The previous logic was only needed for pre-release versions of 3.7.

(cherry picked from commit c0bf9815c9)

* Remove placeboify from unit tests that are not calling AWS (i.e. creating a recording) (#45754)

(cherry picked from commit 2167ce6cb6)

* Update sanity test ignore entries.
2018-10-13 10:44:11 -07:00

268 lines
8.1 KiB
Python
Executable file

#!/usr/bin/env python
"""Interpreter and code coverage injector for use with ansible-test.
The injector serves two main purposes:
1) Control the python interpreter used to run test tools and ansible code.
2) Provide optional code coverage analysis of ansible code.
The injector is executed one of two ways:
1) On the controller via a symbolic link such as ansible or pytest.
This is accomplished by prepending the injector directory to the PATH by ansible-test.
2) As the python interpreter when running ansible modules.
This is only supported when connecting to the local host.
Otherwise set the ANSIBLE_TEST_REMOTE_INTERPRETER environment variable.
It can be empty to auto-detect the python interpreter on the remote host.
If not empty it will be used to set ansible_python_interpreter.
NOTE: Running ansible-test with the --tox option or inside a virtual environment
may prevent the injector from working for tests which use connection
types other than local, or which use become, due to lack of permissions
to access the interpreter for the virtual environment.
"""
from __future__ import absolute_import, print_function
import errno
import json
import os
import sys
import pipes
import logging
import getpass
import resource
logger = logging.getLogger('injector') # pylint: disable=locally-disabled, invalid-name
# pylint: disable=locally-disabled, invalid-name
config = None # type: InjectorConfig
class InjectorConfig(object):
"""Mandatory configuration."""
def __init__(self, config_path):
"""Initialize config."""
with open(config_path) as config_fd:
_config = json.load(config_fd)
self.python_interpreter = _config['python_interpreter']
self.coverage_file = _config['coverage_file']
# Read from the environment instead of config since it needs to be changed by integration test scripts.
# It also does not need to flow from the controller to the remote. It is only used on the controller.
self.remote_interpreter = os.environ.get('ANSIBLE_TEST_REMOTE_INTERPRETER', None)
self.arguments = [to_text(c) for c in sys.argv]
def to_text(value):
"""
:type value: str | None
:rtype: str | None
"""
if value is None:
return None
if isinstance(value, bytes):
return value.decode('utf-8')
return u'%s' % value
def main():
"""Main entry point."""
global config # pylint: disable=locally-disabled, global-statement
formatter = logging.Formatter('%(asctime)s %(process)d %(levelname)s %(message)s')
log_name = 'ansible-test-coverage.%s.log' % getpass.getuser()
self_dir = os.path.dirname(os.path.abspath(__file__))
handler = logging.FileHandler(os.path.join('/tmp', log_name))
handler.setFormatter(formatter)
logger.addHandler(handler)
handler = logging.FileHandler(os.path.abspath(os.path.join(self_dir, '..', 'logs', log_name)))
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
try:
logger.debug('Self: %s', __file__)
# to achieve a consistent nofile ulimit, set to 16k here, this can affect performance in subprocess.Popen when
# being called with close_fds=True on Python (8x the time on some environments)
nofile_limit = 16 * 1024
current_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
new_limit = (nofile_limit, nofile_limit)
if current_limit > new_limit:
logger.debug('RLIMIT_NOFILE: %s -> %s', current_limit, new_limit)
resource.setrlimit(resource.RLIMIT_NOFILE, (nofile_limit, nofile_limit))
else:
logger.debug('RLIMIT_NOFILE: %s', current_limit)
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'injector.json')
try:
config = InjectorConfig(config_path)
except IOError:
logger.exception('Error reading config: %s', config_path)
exit('No injector config found. Set ANSIBLE_TEST_REMOTE_INTERPRETER if the test is not connecting to the local host.')
logger.debug('Arguments: %s', ' '.join(pipes.quote(c) for c in config.arguments))
logger.debug('Python interpreter: %s', config.python_interpreter)
logger.debug('Remote interpreter: %s', config.remote_interpreter)
logger.debug('Coverage file: %s', config.coverage_file)
require_cwd = False
if os.path.basename(__file__) == 'injector.py':
if config.coverage_file:
args, env, require_cwd = cover()
else:
args, env = runner()
else:
args, env = injector()
logger.debug('Run command: %s', ' '.join(pipes.quote(c) for c in args))
altered_cwd = False
try:
cwd = os.getcwd()
except OSError as ex:
# some platforms, such as OS X, may not allow querying the working directory when using become to drop privileges
if ex.errno != errno.EACCES:
raise
if require_cwd:
# make sure the program we execute can determine the working directory if it's required
cwd = '/'
os.chdir(cwd)
altered_cwd = True
else:
cwd = None
logger.debug('Working directory: %s%s', cwd or '?', ' (altered)' if altered_cwd else '')
for key in sorted(env.keys()):
logger.debug('%s=%s', key, env[key])
os.execvpe(args[0], args, env)
except Exception as ex:
logger.fatal(ex)
raise
def injector():
"""
:rtype: list[str], dict[str, str]
"""
command = os.path.basename(__file__)
executable = find_executable(command)
if config.coverage_file:
args, env = coverage_command()
else:
args, env = [config.python_interpreter], os.environ.copy()
args += [executable]
if command in ('ansible', 'ansible-playbook', 'ansible-pull'):
if config.remote_interpreter is None:
interpreter = os.path.join(os.path.dirname(__file__), 'injector.py')
elif config.remote_interpreter == '':
interpreter = None
else:
interpreter = config.remote_interpreter
if interpreter:
args += ['--extra-vars', 'ansible_python_interpreter=' + interpreter]
args += config.arguments[1:]
return args, env
def runner():
"""
:rtype: list[str], dict[str, str]
"""
args, env = [config.python_interpreter], os.environ.copy()
args += config.arguments[1:]
return args, env
def cover():
"""
:rtype: list[str], dict[str, str], bool
"""
if len(config.arguments) > 1:
executable = config.arguments[1]
else:
executable = ''
require_cwd = False
if os.path.basename(executable).startswith('ansible_module_'):
args, env = coverage_command()
# coverage requires knowing the working directory
require_cwd = True
else:
args, env = [config.python_interpreter], os.environ.copy()
args += config.arguments[1:]
return args, env, require_cwd
def coverage_command():
"""
:rtype: list[str], dict[str, str]
"""
self_dir = os.path.dirname(os.path.abspath(__file__))
args = [
config.python_interpreter,
'-m',
'coverage.__main__',
'run',
'--rcfile',
os.path.join(self_dir, '.coveragerc'),
]
env = os.environ.copy()
env['COVERAGE_FILE'] = config.coverage_file
return args, env
def find_executable(executable):
"""
:type executable: str
:rtype: str
"""
self = os.path.abspath(__file__)
path = os.environ.get('PATH', os.path.defpath)
seen_dirs = set()
for path_dir in path.split(os.path.pathsep):
if path_dir in seen_dirs:
continue
seen_dirs.add(path_dir)
candidate = os.path.abspath(os.path.join(path_dir, executable))
if candidate == self:
continue
if os.path.exists(candidate) and os.access(candidate, os.F_OK | os.X_OK):
return candidate
raise Exception('Executable "%s" not found in path: %s' % (executable, path))
if __name__ == '__main__':
main()