Initial commit

This commit is contained in:
Jon Ervine
2021-03-03 11:36:53 +08:00
parent a5dc995324
commit 4cdbe9a6d5
137 changed files with 12374 additions and 2 deletions
+13
View File
@@ -0,0 +1,13 @@
import pkg_resources
from .interface import run, run_async # noqa
from .exceptions import AnsibleRunnerException, ConfigurationError, CallbackError # noqa
from .runner_config import RunnerConfig # noqa
from .runner import Runner # noqa
plugins = {
entry_point.name: entry_point.load()
for entry_point
in pkg_resources.iter_entry_points('ansible_runner.plugins')
}
+959
View File
@@ -0,0 +1,959 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import ast
import pkg_resources
import threading
import traceback
import argparse
import logging
import signal
import sys
import errno
import json
import stat
import os
import shutil
import textwrap
import tempfile
import atexit
from contextlib import contextmanager
from uuid import uuid4
from yaml import safe_load
from ansible_runner import run
from ansible_runner import output
from ansible_runner.utils import dump_artifact, Bunch
from ansible_runner.runner import Runner
from ansible_runner.exceptions import AnsibleRunnerException
VERSION = pkg_resources.require("ansible_runner")[0].version
DEFAULT_ROLES_PATH = os.getenv('ANSIBLE_ROLES_PATH', None)
DEFAULT_RUNNER_BINARY = os.getenv('RUNNER_BINARY', None)
DEFAULT_RUNNER_PLAYBOOK = os.getenv('RUNNER_PLAYBOOK', None)
DEFAULT_RUNNER_ROLE = os.getenv('RUNNER_ROLE', None)
DEFAULT_RUNNER_MODULE = os.getenv('RUNNER_MODULE', None)
DEFAULT_UUID = uuid4()
DEFAULT_CLI_ARGS = {
"positional_args": (
(
('private_data_dir',),
dict(
help="base directory containing the ansible-runner metadata "
"(project, inventory, env, etc)"
),
),
),
"generic_args": (
(
('--version',),
dict(
action='version',
version=VERSION
),
),
(
("--debug",),
dict(
action="store_true",
help="enable ansible-runner debug output logging (default=False)"
),
),
(
("--logfile",),
dict(
help="log output messages to a file (default=None)"
),
),
),
"mutually_exclusive_group": (
(
("-p", "--playbook",),
dict(
default=DEFAULT_RUNNER_PLAYBOOK,
help="invoke an Ansible playbook from the ansible-runner project "
"(See Ansible Playbook Options below)"
),
),
(
("-m", "--module",),
dict(
default=DEFAULT_RUNNER_MODULE,
help="invoke an Ansible module directly without a playbook "
"(See Ansible Module Options below)"
),
),
(
("-r", "--role",),
dict(
default=DEFAULT_RUNNER_ROLE,
help="invoke an Ansible role directly without a playbook "
"(See Ansible Role Options below)"
),
),
),
"ansible_group": (
(
("--limit",),
dict(
help="matches Ansible's ```--limit``` parameter to further constrain "
"the inventory to be used (default=None)"
),
),
(
("--cmdline",),
dict(
help="command line options to pass to ansible-playbook at "
"execution time (default=None)"
),
),
(
("--hosts",),
dict(
help="define the set of hosts to execute against (default=None) "
"Note: this parameter only works with -m or -r"
),
),
(
("--forks",),
dict(
help="matches Ansible's ```--forks``` parameter to set the number "
"of concurrent processes (default=None)"
),
),
),
"runner_group": (
# ansible-runner options
(
("-b", "--binary",),
dict(
default=DEFAULT_RUNNER_BINARY,
help="specifies the full path pointing to the Ansible binaries "
"(default={})".format(DEFAULT_RUNNER_BINARY)
),
),
(
("-i", "--ident",),
dict(
default=DEFAULT_UUID,
help="an identifier that will be used when generating the artifacts "
"directory and can be used to uniquely identify a playbook run "
"(default={})".format(DEFAULT_UUID)
),
),
(
("--rotate-artifacts",),
dict(
default=0,
type=int,
help="automatically clean up old artifact directories after a given "
"number have been created (default=0, disabled)"
),
),
(
("--artifact-dir",),
dict(
help="optional path for the artifact root directory "
"(default=<private_data_dir>/artifacts)"
),
),
(
("--project-dir",),
dict(
help="optional path for the location of the playbook content directory "
"(default=<private_data_dir/project)"
),
),
(
("--inventory",),
dict(
help="optional path for the location of the inventory content directory "
"(default=<private_data_dir>/inventory)"
),
),
(
("-j", "--json",),
dict(
action="store_true",
help="output the JSON event structure to stdout instead of "
"Ansible output (default=False)"
),
),
(
("--omit-event-data",),
dict(
action="store_true",
help="Omits including extra event data in the callback payloads "
"or the Runner payload data files "
"(status and stdout still included)"
),
),
(
("--only-failed-event-data",),
dict(
action="store_true",
help="Only adds extra event data for failed tasks in the callback "
"payloads or the Runner payload data files "
"(status and stdout still included for other events)"
),
),
(
("-q", "--quiet",),
dict(
action="store_true",
help="disable all messages sent to stdout/stderr (default=False)"
),
),
(
("-v",),
dict(
action="count",
help="increase the verbosity with multiple v's (up to 5) of the "
"ansible-playbook output (default=None)"
),
),
),
"roles_group": (
(
("--roles-path",),
dict(
default=DEFAULT_ROLES_PATH,
help="path used to locate the role to be executed (default=None)"
),
),
(
("--role-vars",),
dict(
help="set of variables to be passed to the role at run time in the "
"form of 'key1=value1 key2=value2 keyN=valueN'(default=None)"
),
),
(
("--role-skip-facts",),
dict(
action="store_true",
default=False,
help="disable fact collection when the role is executed (default=False)"
),
)
),
"playbook_group": (
(
("--process-isolation",),
dict(
dest="process_isolation",
action="store_true",
help="Isolate execution. Two methods are supported: (1) using a container engine (e.g. podman or docker) "
"to execute **Ansible**. (2) using a sandbox (e.g. bwrap) which will by default restrict access to /tmp "
"(default=False)"
),
),
(
("--process-isolation-executable",),
dict(
dest="process_isolation_executable",
default="podman",
help="Process isolation executable or container engine used to isolate execution. (default=podman)"
)
),
(
("--process-isolation-path",),
dict(
dest="process_isolation_path",
default="/tmp",
help="path that an isolated playbook run will use for staging. "
"(default=/tmp)"
)
),
(
("--process-isolation-hide-paths",),
dict(
dest="process_isolation_hide_paths",
nargs='*',
help="list of paths on the system that should be hidden from the "
"playbook run (default=None)"
)
),
(
("--process-isolation-show-paths",),
dict(
dest="process_isolation_show_paths",
nargs='*',
help="list of paths on the system that should be exposed to the "
"playbook run (default=None)"
)
),
(
("--process-isolation-ro-paths",),
dict(
dest="process_isolation_ro_paths",
nargs='*',
help="list of paths on the system that should be exposed to the "
"playbook run as read-only (default=None)"
)
),
(
("--directory-isolation-base-path",),
dict(
dest="directory_isolation_base_path",
help="copies the project directory to a location in this directory "
"to prevent multiple simultaneous executions from conflicting "
"(default=None)"
)
),
(
("--resource-profiling",),
dict(
dest='resource_profiling',
action="store_true",
help="Records resource utilization during playbook execution"
)
),
(
("--resource-profiling-base-cgroup",),
dict(
dest='resource_profiling_base_cgroup',
default="ansible-runner",
help="Top-level cgroup used to collect information on resource utilization. Defaults to ansible-runner"
)
),
(
("--resource-profiling-cpu-poll-interval",),
dict(
dest='resource_profiling_cpu_poll_interval',
default=0.25,
help="Interval (in seconds) between CPU polling for determining CPU usage. Defaults to 0.25"
)
),
(
("--resource-profiling-memory-poll-interval",),
dict(
dest='resource_profiling_memory_poll_interval',
default=0.25,
help="Interval (in seconds) between memory polling for determining memory usage. Defaults to 0.25"
)
),
(
("--resource-profiling-pid-poll-interval",),
dict(
dest='resource_profiling_pid_poll_interval',
default=0.25,
help="Interval (in seconds) between polling PID count for determining number of processes used. Defaults to 0.25"
)
),
(
("--resource-profiling-results-dir",),
dict(
dest='resource_profiling_results_dir',
help="Directory where profiling data files should be saved. "
"Defaults to None (profiling_data folder under private data dir is used in this case)."
)
)
),
"modules_group": (
(
("-a", "--args",),
dict(
dest='module_args',
help="set of arguments to be passed to the module at run time in the "
"form of 'key1=value1 key2=value2 keyN=valueN'(default=None)"
)
),
),
"container_group": (
(
("--container-image",),
dict(
dest="container_image",
default="quay.io/ansible/ansible-runner:devel",
help="Container image to use when running an ansible task"
)
),
(
("--container-volume-mount",),
dict(
dest="container_volume_mounts",
action='append',
help="Bind mounts (in the form 'host_dir:/container_dir)'. "
"Can be used more than once to create multiple bind mounts."
)
),
(
("--container-option",),
dict(
dest="container_options",
action='append',
help="Container options to pass to execution engine. "
"Can be used more than once to send multiple options."
)
),
),
"execenv_cli_group": (
(
('--container-runtime',),
dict(
dest='container_runtime',
default='podman',
help="OCI Compliant container runtime to use. Examples: podman, docker"
),
),
(
('--keep-files',),
dict(
dest='keep_files',
action='store_true',
default=False,
help="Keep temporary files persistent on disk instead of cleaning them automatically. "
"(Useful for debugging)"
),
),
),
}
logger = logging.getLogger('ansible-runner')
@contextmanager
def role_manager(vargs):
if vargs.get('role'):
role = {'name': vargs.get('role')}
if vargs.get('role_vars'):
role_vars = {}
for item in vargs['role_vars'].split():
key, value = item.split('=')
try:
role_vars[key] = ast.literal_eval(value)
except Exception:
role_vars[key] = value
role['vars'] = role_vars
kwargs = Bunch(**vargs)
kwargs.update(private_data_dir=vargs.get('private_data_dir'),
json_mode=vargs.get('json'),
ignore_logging=False,
project_dir=vargs.get('project_dir'),
rotate_artifacts=vargs.get('rotate_artifacts'))
if vargs.get('artifact_dir'):
kwargs.artifact_dir = vargs.get('artifact_dir')
if vargs.get('project_dir'):
project_path = kwargs.project_dir = vargs.get('project_dir')
else:
project_path = os.path.join(vargs.get('private_data_dir'), 'project')
project_exists = os.path.exists(project_path)
env_path = os.path.join(vargs.get('private_data_dir'), 'env')
env_exists = os.path.exists(env_path)
envvars_path = os.path.join(vargs.get('private_data_dir'), 'env/envvars')
envvars_exists = os.path.exists(envvars_path)
if vargs.get('cmdline'):
kwargs.cmdline = vargs.get('cmdline')
playbook = None
tmpvars = None
play = [{'hosts': vargs.get('hosts') if vargs.get('hosts') is not None else "all",
'gather_facts': not vargs.get('role_skip_facts'),
'roles': [role]}]
filename = str(uuid4().hex)
playbook = dump_artifact(json.dumps(play), project_path, filename)
kwargs.playbook = playbook
output.debug('using playbook file %s' % playbook)
if vargs.get('inventory'):
inventory_file = os.path.join(vargs.get('private_data_dir'), 'inventory', vargs.get('inventory'))
if not os.path.exists(inventory_file):
raise AnsibleRunnerException('location specified by --inventory does not exist')
kwargs.inventory = inventory_file
output.debug('using inventory file %s' % inventory_file)
roles_path = vargs.get('roles_path') or os.path.join(vargs.get('private_data_dir'), 'roles')
roles_path = os.path.abspath(roles_path)
output.debug('setting ANSIBLE_ROLES_PATH to %s' % roles_path)
envvars = {}
if envvars_exists:
with open(envvars_path, 'rb') as f:
tmpvars = f.read()
new_envvars = safe_load(tmpvars)
if new_envvars:
envvars = new_envvars
envvars['ANSIBLE_ROLES_PATH'] = roles_path
kwargs.envvars = envvars
else:
kwargs = vargs
yield kwargs
if vargs.get('role'):
if not project_exists and os.path.exists(project_path):
logger.debug('removing dynamically generated project folder')
shutil.rmtree(project_path)
elif playbook and os.path.isfile(playbook):
logger.debug('removing dynamically generated playbook')
os.remove(playbook)
# if a previous envvars existed in the private_data_dir,
# restore the original file contents
if tmpvars:
with open(envvars_path, 'wb') as f:
f.write(tmpvars)
elif not envvars_exists and os.path.exists(envvars_path):
logger.debug('removing dynamically generated envvars folder')
os.remove(envvars_path)
# since ansible-runner created the env folder, remove it
if not env_exists and os.path.exists(env_path):
logger.debug('removing dynamically generated env folder')
shutil.rmtree(env_path)
def print_common_usage():
print(textwrap.dedent("""
These are common Ansible Runner commands:
execute a playbook contained in an ansible-runner directory:
ansible-runner run /tmp/private -p playbook.yml
ansible-runner start /tmp/private -p playbook.yml
ansible-runner stop /tmp/private
ansible-runner is-alive /tmp/private
directly execute ansible primitives:
ansible-runner run . -r role_name --hosts myhost
ansible-runner run . -m command -a "ls -l" --hosts myhost
run ansible execution environments:
ansible-runner adhoc myhosts -m ping
ansible-runner playbook my_playbook.yml
`ansible-runner --help` list of optional command line arguments
"""))
def add_args_to_parser(parser, args):
"""
Traverse a tuple of argments to add to a parser
:param parser: Instance of a parser, subparser, or argument group
:type sys_args: argparse.ArgumentParser
:param args: Tuple of tuples, format ((arg1, arg2), {'kwarg1':'val1'},)
:type sys_args: tuple
:returns: None
"""
for arg in args:
parser.add_argument(*arg[0], **arg[1])
def main(sys_args=None):
"""Main entry point for ansible-runner executable
When the ```ansible-runner``` command is executed, this function
is the main entry point that is called and executed.
:param sys_args: List of arguments to be parsed by the parser
:type sys_args: list
:returns: an instance of SystemExit
:rtype: SystemExit
"""
parser = argparse.ArgumentParser(
prog='ansible-runner',
description="Use 'ansible-runner' (with no arguments) to see basic usage"
)
subparser = parser.add_subparsers(
help="Command to invoke",
dest='command',
description="COMMAND PRIVATE_DATA_DIR [ARGS]"
)
add_args_to_parser(parser, DEFAULT_CLI_ARGS['generic_args'])
subparser.required = True
# positional options
run_subparser = subparser.add_parser(
'run',
help="Run ansible-runner in the foreground"
)
add_args_to_parser(run_subparser, DEFAULT_CLI_ARGS['positional_args'])
start_subparser = subparser.add_parser(
'start',
help="Start an ansible-runner process in the background"
)
add_args_to_parser(start_subparser, DEFAULT_CLI_ARGS['positional_args'])
stop_subparser = subparser.add_parser(
'stop',
help="Stop an ansible-runner process that's running in the background"
)
add_args_to_parser(stop_subparser, DEFAULT_CLI_ARGS['positional_args'])
isalive_subparser = subparser.add_parser(
'is-alive',
help="Check if a an ansible-runner process in the background is still running."
)
add_args_to_parser(isalive_subparser, DEFAULT_CLI_ARGS['positional_args'])
# streaming commands
transmit_subparser = subparser.add_parser(
'transmit',
help="Send a job to a remote ansible-runner process"
)
add_args_to_parser(transmit_subparser, DEFAULT_CLI_ARGS['positional_args'])
worker_subparser = subparser.add_parser(
'worker',
help="Execute work streamed from a controlling instance"
)
worker_subparser.add_argument(
"--private-data-dir",
help="base directory containing the ansible-runner metadata "
"(project, inventory, env, etc)",
)
process_subparser = subparser.add_parser(
'process',
help="Receive the output of remote ansible-runner work and distribute the results"
)
add_args_to_parser(process_subparser, DEFAULT_CLI_ARGS['positional_args'])
# adhoc command exec
adhoc_subparser = subparser.add_parser(
'adhoc',
help="Run ansible adhoc commands in an Execution Environment"
)
adhoc_subparser.add_argument(
"--private-data-dir",
help="base directory containing the ansible-runner metadata "
"(project, inventory, env, etc)",
)
add_args_to_parser(adhoc_subparser, DEFAULT_CLI_ARGS['execenv_cli_group'])
# playbook command exec
playbook_subparser = subparser.add_parser(
'playbook',
help="Run ansible-playbook commands in an Execution Environment"
)
playbook_subparser.add_argument(
"--private-data-dir",
help="base directory containing the ansible-runner metadata "
"(project, inventory, env, etc)",
)
add_args_to_parser(playbook_subparser, DEFAULT_CLI_ARGS['execenv_cli_group'])
# generic args for all subparsers
add_args_to_parser(run_subparser, DEFAULT_CLI_ARGS['generic_args'])
add_args_to_parser(start_subparser, DEFAULT_CLI_ARGS['generic_args'])
add_args_to_parser(stop_subparser, DEFAULT_CLI_ARGS['generic_args'])
add_args_to_parser(isalive_subparser, DEFAULT_CLI_ARGS['generic_args'])
add_args_to_parser(adhoc_subparser, DEFAULT_CLI_ARGS['generic_args'])
add_args_to_parser(playbook_subparser, DEFAULT_CLI_ARGS['generic_args'])
add_args_to_parser(transmit_subparser, DEFAULT_CLI_ARGS['generic_args'])
add_args_to_parser(worker_subparser, DEFAULT_CLI_ARGS['generic_args'])
add_args_to_parser(process_subparser, DEFAULT_CLI_ARGS['generic_args'])
# runner group
ansible_runner_group_options = (
"Ansible Runner Options",
"configuration options for controlling the ansible-runner "
"runtime environment.",
)
base_runner_group = parser.add_argument_group(*ansible_runner_group_options)
run_runner_group = run_subparser.add_argument_group(*ansible_runner_group_options)
start_runner_group = start_subparser.add_argument_group(*ansible_runner_group_options)
stop_runner_group = stop_subparser.add_argument_group(*ansible_runner_group_options)
isalive_runner_group = isalive_subparser.add_argument_group(*ansible_runner_group_options)
transmit_runner_group = transmit_subparser.add_argument_group(*ansible_runner_group_options)
add_args_to_parser(base_runner_group, DEFAULT_CLI_ARGS['runner_group'])
add_args_to_parser(run_runner_group, DEFAULT_CLI_ARGS['runner_group'])
add_args_to_parser(start_runner_group, DEFAULT_CLI_ARGS['runner_group'])
add_args_to_parser(stop_runner_group, DEFAULT_CLI_ARGS['runner_group'])
add_args_to_parser(isalive_runner_group, DEFAULT_CLI_ARGS['runner_group'])
add_args_to_parser(transmit_runner_group, DEFAULT_CLI_ARGS['runner_group'])
# mutually exclusive group
run_mutually_exclusive_group = run_subparser.add_mutually_exclusive_group()
start_mutually_exclusive_group = start_subparser.add_mutually_exclusive_group()
stop_mutually_exclusive_group = stop_subparser.add_mutually_exclusive_group()
isalive_mutually_exclusive_group = isalive_subparser.add_mutually_exclusive_group()
transmit_mutually_exclusive_group = transmit_subparser.add_mutually_exclusive_group()
add_args_to_parser(run_mutually_exclusive_group, DEFAULT_CLI_ARGS['mutually_exclusive_group'])
add_args_to_parser(start_mutually_exclusive_group, DEFAULT_CLI_ARGS['mutually_exclusive_group'])
add_args_to_parser(stop_mutually_exclusive_group, DEFAULT_CLI_ARGS['mutually_exclusive_group'])
add_args_to_parser(isalive_mutually_exclusive_group, DEFAULT_CLI_ARGS['mutually_exclusive_group'])
add_args_to_parser(transmit_mutually_exclusive_group, DEFAULT_CLI_ARGS['mutually_exclusive_group'])
# ansible options
ansible_options = (
"Ansible Options",
"control the ansible[-playbook] execution environment",
)
run_ansible_group = run_subparser.add_argument_group(*ansible_options)
start_ansible_group = start_subparser.add_argument_group(*ansible_options)
stop_ansible_group = stop_subparser.add_argument_group(*ansible_options)
isalive_ansible_group = isalive_subparser.add_argument_group(*ansible_options)
transmit_ansible_group = transmit_subparser.add_argument_group(*ansible_options)
add_args_to_parser(run_ansible_group, DEFAULT_CLI_ARGS['ansible_group'])
add_args_to_parser(start_ansible_group, DEFAULT_CLI_ARGS['ansible_group'])
add_args_to_parser(stop_ansible_group, DEFAULT_CLI_ARGS['ansible_group'])
add_args_to_parser(isalive_ansible_group, DEFAULT_CLI_ARGS['ansible_group'])
add_args_to_parser(transmit_ansible_group, DEFAULT_CLI_ARGS['ansible_group'])
# roles group
roles_group_options = (
"Ansible Role Options",
"configuration options for directly executing Ansible roles",
)
run_roles_group = run_subparser.add_argument_group(*roles_group_options)
start_roles_group = start_subparser.add_argument_group(*roles_group_options)
stop_roles_group = stop_subparser.add_argument_group(*roles_group_options)
isalive_roles_group = isalive_subparser.add_argument_group(*roles_group_options)
transmit_roles_group = transmit_subparser.add_argument_group(*roles_group_options)
add_args_to_parser(run_roles_group, DEFAULT_CLI_ARGS['roles_group'])
add_args_to_parser(start_roles_group, DEFAULT_CLI_ARGS['roles_group'])
add_args_to_parser(stop_roles_group, DEFAULT_CLI_ARGS['roles_group'])
add_args_to_parser(isalive_roles_group, DEFAULT_CLI_ARGS['roles_group'])
add_args_to_parser(transmit_roles_group, DEFAULT_CLI_ARGS['roles_group'])
# modules groups
modules_group_options = (
"Ansible Module Options",
"configuration options for directly executing Ansible modules",
)
run_modules_group = run_subparser.add_argument_group(*modules_group_options)
start_modules_group = start_subparser.add_argument_group(*modules_group_options)
stop_modules_group = stop_subparser.add_argument_group(*modules_group_options)
isalive_modules_group = isalive_subparser.add_argument_group(*modules_group_options)
transmit_modules_group = transmit_subparser.add_argument_group(*modules_group_options)
add_args_to_parser(run_modules_group, DEFAULT_CLI_ARGS['modules_group'])
add_args_to_parser(start_modules_group, DEFAULT_CLI_ARGS['modules_group'])
add_args_to_parser(stop_modules_group, DEFAULT_CLI_ARGS['modules_group'])
add_args_to_parser(isalive_modules_group, DEFAULT_CLI_ARGS['modules_group'])
add_args_to_parser(transmit_modules_group, DEFAULT_CLI_ARGS['modules_group'])
# playbook options
playbook_group_options = (
"Ansible Playbook Options",
"configuation options for executing Ansible playbooks",
)
run_playbook_group = run_subparser.add_argument_group(*playbook_group_options)
start_playbook_group = start_subparser.add_argument_group(*playbook_group_options)
stop_playbook_group = stop_subparser.add_argument_group(*playbook_group_options)
isalive_playbook_group = isalive_subparser.add_argument_group(*playbook_group_options)
transmit_playbook_group = transmit_subparser.add_argument_group(*playbook_group_options)
add_args_to_parser(run_playbook_group, DEFAULT_CLI_ARGS['playbook_group'])
add_args_to_parser(start_playbook_group, DEFAULT_CLI_ARGS['playbook_group'])
add_args_to_parser(stop_playbook_group, DEFAULT_CLI_ARGS['playbook_group'])
add_args_to_parser(isalive_playbook_group, DEFAULT_CLI_ARGS['playbook_group'])
add_args_to_parser(transmit_playbook_group, DEFAULT_CLI_ARGS['playbook_group'])
# container group
container_group_options = (
"Ansible Container Options",
"configuation options for executing Ansible playbooks",
)
run_container_group = run_subparser.add_argument_group(*container_group_options)
start_container_group = start_subparser.add_argument_group(*container_group_options)
stop_container_group = stop_subparser.add_argument_group(*container_group_options)
isalive_container_group = isalive_subparser.add_argument_group(*container_group_options)
transmit_container_group = transmit_subparser.add_argument_group(*container_group_options)
adhoc_container_group = adhoc_subparser.add_argument_group(*container_group_options)
playbook_container_group = playbook_subparser.add_argument_group(*container_group_options)
add_args_to_parser(run_container_group, DEFAULT_CLI_ARGS['container_group'])
add_args_to_parser(start_container_group, DEFAULT_CLI_ARGS['container_group'])
add_args_to_parser(stop_container_group, DEFAULT_CLI_ARGS['container_group'])
add_args_to_parser(isalive_container_group, DEFAULT_CLI_ARGS['container_group'])
add_args_to_parser(transmit_container_group, DEFAULT_CLI_ARGS['container_group'])
add_args_to_parser(adhoc_container_group, DEFAULT_CLI_ARGS['container_group'])
add_args_to_parser(playbook_container_group, DEFAULT_CLI_ARGS['container_group'])
if len(sys.argv) == 1:
parser.print_usage()
print_common_usage()
parser.exit(status=0)
if ('playbook' in sys.argv) or ('adhoc' in sys.argv):
args, leftover_args = parser.parse_known_args(sys_args)
else:
args = parser.parse_args(sys_args)
vargs = vars(args)
# FIXME - Probably a more elegant way to handle this.
# set some state about CLI Exec Env
cli_execenv_cmd = ""
if vargs.get('command') in ('adhoc', 'playbook'):
cli_execenv_cmd = vargs.get('command')
if not leftover_args:
parser.exit(
status=1,
message="The {} subcommand requires arguments to pass to Ansible inside the container.\n".format(
vargs.get('command')
)
)
if vargs.get('command') in ('worker', 'process', 'adhoc', 'playbook'):
if not vargs.get('private_data_dir'):
temp_private_dir = tempfile.mkdtemp()
vargs['private_data_dir'] = temp_private_dir
if vargs.get('keep_files', False):
print("ANSIBLE-RUNNER: keeping temporary data directory: {}".format(temp_private_dir))
else:
@atexit.register
def conditonally_clean_cli_execenv_tempdir():
shutil.rmtree(temp_private_dir)
if vargs.get('command') in ('start', 'run', 'transmit'):
if vargs.get('hosts') and not (vargs.get('module') or vargs.get('role')):
parser.exit(status=1, message="The --hosts option can only be used with -m or -r\n")
if not (vargs.get('module') or vargs.get('role')) and not vargs.get('playbook'):
parser.exit(status=1, message="The -p option must be specified when not using -m or -r\n")
output.configure()
# enable or disable debug mode
output.set_debug('enable' if vargs.get('debug') else 'disable')
# set the output logfile
if ('logfile' in args) and vargs.get('logfile'):
output.set_logfile(vargs.get('logfile'))
output.debug('starting debug logging')
# get the absolute path for start since it is a daemon
vargs['private_data_dir'] = os.path.abspath(vargs.get('private_data_dir'))
pidfile = os.path.join(vargs.get('private_data_dir'), 'pid')
try:
os.makedirs(vargs.get('private_data_dir'), mode=0o700)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(vargs.get('private_data_dir')):
pass
else:
raise
stderr_path = None
context = None
if vargs.get('command') not in ('run', 'transmit', 'worker', 'adhoc', 'playbook'):
stderr_path = os.path.join(vargs.get('private_data_dir'), 'daemon.log')
if not os.path.exists(stderr_path):
os.close(os.open(stderr_path, os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR))
if vargs.get('command') in ('start', 'run', 'transmit', 'worker', 'process', 'adhoc', 'playbook'):
if vargs.get('command') == 'start':
import daemon
from daemon.pidfile import TimeoutPIDLockFile
context = daemon.DaemonContext(pidfile=TimeoutPIDLockFile(pidfile))
else:
context = threading.Lock()
streamer = None
if vargs.get('command') in ('transmit', 'worker', 'process'):
streamer = vargs.get('command')
with context:
with role_manager(vargs) as vargs:
run_options = dict(private_data_dir=vargs.get('private_data_dir'),
ident=vargs.get('ident'),
binary=vargs.get('binary'),
playbook=vargs.get('playbook'),
module=vargs.get('module'),
module_args=vargs.get('module_args'),
host_pattern=vargs.get('hosts'),
verbosity=vargs.get('v'),
quiet=vargs.get('quiet'),
rotate_artifacts=vargs.get('rotate_artifacts'),
ignore_logging=False,
json_mode=vargs.get('json'),
omit_event_data=vargs.get('omit_event_data'),
only_failed_event_data=vargs.get('only_failed_event_data'),
inventory=vargs.get('inventory'),
forks=vargs.get('forks'),
project_dir=vargs.get('project_dir'),
artifact_dir=vargs.get('artifact_dir'),
roles_path=[vargs.get('roles_path')] if vargs.get('roles_path') else None,
process_isolation=vargs.get('process_isolation'),
process_isolation_executable=vargs.get('process_isolation_executable'),
process_isolation_path=vargs.get('process_isolation_path'),
process_isolation_hide_paths=vargs.get('process_isolation_hide_paths'),
process_isolation_show_paths=vargs.get('process_isolation_show_paths'),
process_isolation_ro_paths=vargs.get('process_isolation_ro_paths'),
container_image=vargs.get('container_image'),
container_volume_mounts=vargs.get('container_volume_mounts'),
container_options=vargs.get('container_options'),
directory_isolation_base_path=vargs.get('directory_isolation_base_path'),
resource_profiling=vargs.get('resource_profiling'),
resource_profiling_base_cgroup=vargs.get('resource_profiling_base_cgroup'),
resource_profiling_cpu_poll_interval=vargs.get('resource_profiling_cpu_poll_interval'),
resource_profiling_memory_poll_interval=vargs.get('resource_profiling_memory_poll_interval'),
resource_profiling_pid_poll_interval=vargs.get('resource_profiling_pid_poll_interval'),
resource_profiling_results_dir=vargs.get('resource_profiling_results_dir'),
limit=vargs.get('limit'),
streamer=streamer,
cli_execenv_cmd=cli_execenv_cmd
)
if vargs.get('command') in ('adhoc', 'playbook'):
run_options['cmdline'] = sys.argv[sys.argv.index(leftover_args[0]):]
run_options['process_isolation']=True
run_options['process_isolation_executable']=vargs.get('container_runtime')
try:
res = run(**run_options)
except Exception:
exc = traceback.format_exc()
if stderr_path:
open(stderr_path, 'w+').write(exc)
else:
sys.stderr.write(exc)
return 1
return(res.rc)
try:
with open(pidfile, 'r') as f:
pid = int(f.readline())
except IOError:
return(1)
if vargs.get('command') == 'stop':
Runner.handle_termination(pid, pidfile=pidfile)
return (0)
elif vargs.get('command') == 'is-alive':
try:
os.kill(pid, signal.SIG_DFL)
return(0)
except OSError:
return(1)
+50
View File
@@ -0,0 +1,50 @@
# Copyright (c) 2017 Ansible by Red Hat
#
# This file is part of Ansible Tower, but depends on code imported from Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
DOCUMENTATION = '''
callback: awx_display
short_description: Playbook event dispatcher for ansible-runner
version_added: "2.0"
description:
- This callback is necessary for ansible-runner to work
type: stdout
extends_documentation_fragment:
- default_callback
requirements:
- Set as stdout in config
'''
# Python
import os # noqa
import sys # noqa
# Add awx/lib to sys.path.
awx_lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if awx_lib_path not in sys.path:
sys.path.insert(0, awx_lib_path)
# Tower Display Callback
from display_callback import AWXDefaultCallbackModule # noqa
# In order to be recognized correctly, self.__class__.__name__ needs to
# match "CallbackModule"
class CallbackModule(AWXDefaultCallbackModule):
pass
+50
View File
@@ -0,0 +1,50 @@
# Copyright (c) 2017 Ansible by Red Hat
#
# This file is part of Ansible Tower, but depends on code imported from Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
DOCUMENTATION = '''
callback: minimal
short_description: Ad hoc event dispatcher for ansible-runner
version_added: "2.0"
description:
- This callback is necessary for ansible-runner to work
type: stdout
extends_documentation_fragment:
- default_callback
requirements:
- Set as stdout in config
'''
# Python
import os # noqa
import sys # noqa
# Add awx/lib to sys.path.
awx_lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if awx_lib_path not in sys.path:
sys.path.insert(0, awx_lib_path)
# Tower Display Callback
from display_callback import AWXMinimalCallbackModule # noqa
# In order to be recognized correctly, self.__class__.__name__ needs to
# match "CallbackModule"
class CallbackModule(AWXMinimalCallbackModule):
pass
+2
View File
@@ -0,0 +1,2 @@
default_process_isolation_executable = 'podman'
default_container_image = 'quay.io/ansible/ansible-runner:devel'
@@ -0,0 +1,24 @@
# Copyright (c) 2016 Ansible by Red Hat, Inc.
#
# This file is part of Ansible Tower, but depends on code imported from Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
# AWX Display Callback
from . import display # noqa (wraps ansible.display.Display methods)
from .module import AWXDefaultCallbackModule, AWXMinimalCallbackModule
__all__ = ['AWXDefaultCallbackModule', 'AWXMinimalCallbackModule']
@@ -0,0 +1,98 @@
# Copyright (c) 2016 Ansible by Red Hat, Inc.
#
# This file is part of Ansible Tower, but depends on code imported from Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
# Python
import functools
import sys
import uuid
# Ansible
from ansible.utils.display import Display
# Tower Display Callback
from .events import event_context
__all__ = []
def with_context(**context):
global event_context
def wrap(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
with event_context.set_local(**context):
return f(*args, **kwargs)
return wrapper
return wrap
for attr in dir(Display):
if attr.startswith('_') or 'cow' in attr or 'prompt' in attr:
continue
if attr in ('display', 'v', 'vv', 'vvv', 'vvvv', 'vvvvv', 'vvvvvv', 'verbose'):
continue
if not callable(getattr(Display, attr)):
continue
setattr(Display, attr, with_context(**{attr: True})(getattr(Display, attr)))
def with_verbosity(f):
global event_context
@functools.wraps(f)
def wrapper(*args, **kwargs):
host = args[2] if len(args) >= 3 else kwargs.get('host', None)
caplevel = args[3] if len(args) >= 4 else kwargs.get('caplevel', 2)
context = dict(verbose=True, verbosity=(caplevel + 1))
if host is not None:
context['remote_addr'] = host
with event_context.set_local(**context):
return f(*args, **kwargs)
return wrapper
Display.verbose = with_verbosity(Display.verbose)
def display_with_context(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
log_only = args[5] if len(args) >= 6 else kwargs.get('log_only', False)
stderr = args[3] if len(args) >= 4 else kwargs.get('stderr', False)
event_uuid = event_context.get().get('uuid', None)
with event_context.display_lock:
# If writing only to a log file or there is already an event UUID
# set (from a callback module method), skip dumping the event data.
if log_only or event_uuid:
return f(*args, **kwargs)
try:
fileobj = sys.stderr if stderr else sys.stdout
event_context.add_local(uuid=str(uuid.uuid4()))
event_context.dump_begin(fileobj)
return f(*args, **kwargs)
finally:
event_context.dump_end(fileobj)
event_context.remove_local(uuid=None)
return wrapper
Display.display = display_with_context(Display.display)
+203
View File
@@ -0,0 +1,203 @@
# Copyright (c) 2016 Ansible by Red Hat, Inc.
#
# This file is part of Ansible Tower, but depends on code imported from Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
# Python
import base64
import contextlib
import datetime
import json
import multiprocessing
import os
import stat
import threading
import uuid
__all__ = ['event_context']
# use a custom JSON serializer so we can properly handle !unsafe and !vault
# objects that may exist in events emitted by the callback plugin
# see: https://github.com/ansible/ansible/pull/38759
class AnsibleJSONEncoderLocal(json.JSONEncoder):
'''
The class AnsibleJSONEncoder exists in Ansible core for this function
this performs a mostly identical function via duck typing
'''
def default(self, o):
if getattr(o, 'yaml_tag', None) == '!vault':
encrypted_form = o._ciphertext
if isinstance(encrypted_form, bytes):
encrypted_form = encrypted_form.decode('utf-8')
return {'__ansible_vault': encrypted_form}
elif isinstance(o, (datetime.date, datetime.datetime)):
return o.isoformat()
return super(AnsibleJSONEncoderLocal, self).default(o)
class IsolatedFileWrite:
'''
Class that will write partial event data to a file
'''
def __init__(self):
self.private_data_dir = os.getenv('AWX_ISOLATED_DATA_DIR')
def set(self, key, value):
# Strip off the leading key identifying characters :1:ev-
event_uuid = key[len(':1:ev-'):]
# Write data in a staging area and then atomic move to pickup directory
filename = '{}-partial.json'.format(event_uuid)
if not os.path.exists(os.path.join(self.private_data_dir, 'job_events')):
os.mkdir(os.path.join(self.private_data_dir, 'job_events'), 0o700)
dropoff_location = os.path.join(self.private_data_dir, 'job_events', filename)
write_location = '.'.join([dropoff_location, 'tmp'])
partial_data = json.dumps(value, cls=AnsibleJSONEncoderLocal)
with os.fdopen(os.open(write_location, os.O_WRONLY | os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR), 'w') as f:
f.write(partial_data)
os.rename(write_location, dropoff_location)
class EventContext(object):
'''
Store global and local (per thread/process) data associated with callback
events and other display output methods.
'''
def __init__(self):
self.display_lock = multiprocessing.RLock()
self._local = threading.local()
if os.getenv('AWX_ISOLATED_DATA_DIR', False):
self.cache = IsolatedFileWrite()
def add_local(self, **kwargs):
tls = vars(self._local)
ctx = tls.setdefault('_ctx', {})
ctx.update(kwargs)
def remove_local(self, **kwargs):
for key in kwargs.keys():
self._local._ctx.pop(key, None)
@contextlib.contextmanager
def set_local(self, **kwargs):
try:
self.add_local(**kwargs)
yield
finally:
self.remove_local(**kwargs)
def get_local(self):
return getattr(getattr(self, '_local', None), '_ctx', {})
def add_global(self, **kwargs):
if not hasattr(self, '_global_ctx'):
self._global_ctx = {}
self._global_ctx.update(kwargs)
def remove_global(self, **kwargs):
if hasattr(self, '_global_ctx'):
for key in kwargs.keys():
self._global_ctx.pop(key, None)
@contextlib.contextmanager
def set_global(self, **kwargs):
try:
self.add_global(**kwargs)
yield
finally:
self.remove_global(**kwargs)
def get_global(self):
return getattr(self, '_global_ctx', {})
def get(self):
ctx = {}
ctx.update(self.get_global())
ctx.update(self.get_local())
return ctx
def get_begin_dict(self):
omit_event_data = os.getenv("RUNNER_OMIT_EVENTS", "False").lower() == "true"
include_only_failed_event_data = os.getenv("RUNNER_ONLY_FAILED_EVENTS", "False").lower() == "true"
event_data = self.get()
event = event_data.pop('event', None)
if not event:
event = 'verbose'
for key in ('debug', 'verbose', 'deprecated', 'warning', 'system_warning', 'error'):
if event_data.get(key, False):
event = key
break
event_dict = dict(event=event)
should_process_event_data = (include_only_failed_event_data and event in ('runner_on_failed', 'runner_on_async_failed', 'runner_on_item_failed')) \
or not include_only_failed_event_data
if os.getenv('JOB_ID', ''):
event_dict['job_id'] = int(os.getenv('JOB_ID', '0'))
if os.getenv('AD_HOC_COMMAND_ID', ''):
event_dict['ad_hoc_command_id'] = int(os.getenv('AD_HOC_COMMAND_ID', '0'))
if os.getenv('PROJECT_UPDATE_ID', ''):
event_dict['project_update_id'] = int(os.getenv('PROJECT_UPDATE_ID', '0'))
event_dict['pid'] = event_data.get('pid', os.getpid())
event_dict['uuid'] = event_data.get('uuid', str(uuid.uuid4()))
event_dict['created'] = event_data.get('created', datetime.datetime.utcnow().isoformat())
if not event_data.get('parent_uuid', None):
for key in ('task_uuid', 'play_uuid', 'playbook_uuid'):
parent_uuid = event_data.get(key, None)
if parent_uuid and parent_uuid != event_data.get('uuid', None):
event_dict['parent_uuid'] = parent_uuid
break
else:
event_dict['parent_uuid'] = event_data.get('parent_uuid', None)
if "verbosity" in event_data.keys():
event_dict["verbosity"] = event_data.pop("verbosity")
if not omit_event_data and should_process_event_data:
max_res = int(os.getenv("MAX_EVENT_RES", 700000))
if event not in ('playbook_on_stats',) and "res" in event_data and len(str(event_data['res'])) > max_res:
event_data['res'] = {}
else:
event_data = dict()
event_dict['event_data'] = event_data
return event_dict
def get_end_dict(self):
return {}
def dump(self, fileobj, data, max_width=78, flush=False):
b64data = base64.b64encode(json.dumps(data).encode('utf-8')).decode()
with self.display_lock:
# pattern corresponding to OutputEventFilter expectation
fileobj.write(u'\x1b[K')
for offset in range(0, len(b64data), max_width):
chunk = b64data[offset:offset + max_width]
escaped_chunk = u'{}\x1b[{}D'.format(chunk, len(chunk))
fileobj.write(escaped_chunk)
fileobj.write(u'\x1b[K')
if flush:
fileobj.flush()
def dump_begin(self, fileobj):
begin_dict = self.get_begin_dict()
self.cache.set(":1:ev-{}".format(begin_dict['uuid']), begin_dict)
self.dump(fileobj, {'uuid': begin_dict['uuid']})
def dump_end(self, fileobj):
self.dump(fileobj, self.get_end_dict(), flush=True)
event_context = EventContext()
@@ -0,0 +1,29 @@
# Copyright (c) 2016 Ansible by Red Hat, Inc.
#
# This file is part of Ansible Tower, but depends on code imported from Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
# Python
import os
# Ansible
import ansible
# Because of the way Ansible loads plugins, it's not possible to import
# ansible.plugins.callback.minimal when being loaded as the minimal plugin. Ugh.
minimal_plugin = os.path.join(os.path.dirname(ansible.__file__), 'plugins', 'callback', 'minimal.py')
exec(compile(open(minimal_plugin, "rb").read(), minimal_plugin, 'exec'))
+548
View File
@@ -0,0 +1,548 @@
# Copyright (c) 2016 Ansible by Red Hat, Inc.
#
# This file is part of Ansible Tower, but depends on code imported from Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
# Python
import collections
import contextlib
import datetime
import sys
import uuid
from copy import copy
# Ansible
from ansible import constants as C
from ansible.plugins.callback import CallbackBase
from ansible.plugins.callback.default import CallbackModule as DefaultCallbackModule
# AWX Display Callback
from .events import event_context
from .minimal import CallbackModule as MinimalCallbackModule
CENSORED = "the output has been hidden due to the fact that 'no_log: true' was specified for this result" # noqa
def current_time():
return datetime.datetime.utcnow()
class BaseCallbackModule(CallbackBase):
'''
Callback module for logging ansible/ansible-playbook events.
'''
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
# These events should never have an associated play.
EVENTS_WITHOUT_PLAY = [
'playbook_on_start',
'playbook_on_stats',
]
# These events should never have an associated task.
EVENTS_WITHOUT_TASK = EVENTS_WITHOUT_PLAY + [
'playbook_on_setup',
'playbook_on_notify',
'playbook_on_import_for_host',
'playbook_on_not_import_for_host',
'playbook_on_no_hosts_matched',
'playbook_on_no_hosts_remaining',
]
def __init__(self):
super(BaseCallbackModule, self).__init__()
self._host_start = {}
self.task_uuids = set()
self.duplicate_task_counts = collections.defaultdict(lambda: 1)
self.play_uuids = set()
self.duplicate_play_counts = collections.defaultdict(lambda: 1)
@contextlib.contextmanager
def capture_event_data(self, event, **event_data):
event_data.setdefault('uuid', str(uuid.uuid4()))
if event not in self.EVENTS_WITHOUT_TASK:
task = event_data.pop('task', None)
else:
task = None
if event_data.get('res'):
if event_data['res'].get('_ansible_no_log', False):
event_data['res'] = {'censored': CENSORED}
if event_data['res'].get('results', []):
event_data['res']['results'] = copy(event_data['res']['results'])
for i, item in enumerate(event_data['res'].get('results', [])):
if isinstance(item, dict) and item.get('_ansible_no_log', False):
event_data['res']['results'][i] = {'censored': CENSORED}
with event_context.display_lock:
try:
event_context.add_local(event=event, **event_data)
if task:
self.set_task(task, local=True)
event_context.dump_begin(sys.stdout)
yield
finally:
event_context.dump_end(sys.stdout)
if task:
self.clear_task(local=True)
event_context.remove_local(event=None, **event_data)
def set_playbook(self, playbook):
# NOTE: Ansible doesn't generate a UUID for playbook_on_start so do it for them.
self.playbook_uuid = str(uuid.uuid4())
file_name = getattr(playbook, '_file_name', '???')
event_context.add_global(playbook=file_name, playbook_uuid=self.playbook_uuid)
self.clear_play()
def set_play(self, play):
if hasattr(play, 'hosts'):
if isinstance(play.hosts, list):
pattern = ','.join(play.hosts)
else:
pattern = play.hosts
else:
pattern = ''
name = play.get_name().strip() or pattern
event_context.add_global(play=name, play_uuid=str(play._uuid), play_pattern=pattern)
self.clear_task()
def clear_play(self):
event_context.remove_global(play=None, play_uuid=None, play_pattern=None)
self.clear_task()
def set_task(self, task, local=False):
self.clear_task(local)
# FIXME: Task is "global" unless using free strategy!
task_ctx = dict(
task=(task.name or task.action),
task_uuid=str(task._uuid),
task_action=task.action,
task_args='',
)
try:
task_ctx['task_path'] = task.get_path()
except AttributeError:
pass
if C.DISPLAY_ARGS_TO_STDOUT:
if task.no_log:
task_ctx['task_args'] = "the output has been hidden due to the fact that 'no_log: true' was specified for this result"
else:
task_args = ', '.join(('%s=%s' % a for a in task.args.items()))
task_ctx['task_args'] = task_args
if getattr(task, '_role', None):
task_role = task._role._role_name
else:
task_role = getattr(task, 'role_name', '')
if task_role:
task_ctx['role'] = task_role
if local:
event_context.add_local(**task_ctx)
else:
event_context.add_global(**task_ctx)
def clear_task(self, local=False):
task_ctx = dict(task=None, task_path=None, task_uuid=None, task_action=None, task_args=None, role=None)
if local:
event_context.remove_local(**task_ctx)
else:
event_context.remove_global(**task_ctx)
def v2_playbook_on_start(self, playbook):
self.set_playbook(playbook)
event_data = dict(
uuid=self.playbook_uuid,
)
with self.capture_event_data('playbook_on_start', **event_data):
super(BaseCallbackModule, self).v2_playbook_on_start(playbook)
def v2_playbook_on_vars_prompt(self, varname, private=True, prompt=None,
encrypt=None, confirm=False, salt_size=None,
salt=None, default=None, unsafe=None):
event_data = dict(
varname=varname,
private=private,
prompt=prompt,
encrypt=encrypt,
confirm=confirm,
salt_size=salt_size,
salt=salt,
default=default,
unsafe=unsafe,
)
with self.capture_event_data('playbook_on_vars_prompt', **event_data):
super(BaseCallbackModule, self).v2_playbook_on_vars_prompt(
varname, private, prompt, encrypt, confirm, salt_size, salt,
default,
)
def v2_playbook_on_include(self, included_file):
event_data = dict(
included_file=included_file._filename if included_file is not None else None,
)
with self.capture_event_data('playbook_on_include', **event_data):
super(BaseCallbackModule, self).v2_playbook_on_include(included_file)
def v2_playbook_on_play_start(self, play):
play_uuid = str(play._uuid)
if play_uuid in self.play_uuids:
# When this play UUID repeats, it means the play is using the
# free strategy (or serial:1) so different hosts may be running
# different tasks within a play (where duplicate UUIDS are common).
#
# When this is the case, modify the UUID slightly to append
# a counter so we can still _track_ duplicate events, but also
# avoid breaking the display in these scenarios.
self.duplicate_play_counts[play_uuid] += 1
play_uuid = '_'.join([
play_uuid,
str(self.duplicate_play_counts[play_uuid])
])
self.play_uuids.add(play_uuid)
play._uuid = play_uuid
self.set_play(play)
if hasattr(play, 'hosts'):
if isinstance(play.hosts, list):
pattern = ','.join(play.hosts)
else:
pattern = play.hosts
else:
pattern = ''
name = play.get_name().strip() or pattern
event_data = dict(
name=name,
pattern=pattern,
uuid=str(play._uuid),
)
with self.capture_event_data('playbook_on_play_start', **event_data):
super(BaseCallbackModule, self).v2_playbook_on_play_start(play)
def v2_playbook_on_import_for_host(self, result, imported_file):
# NOTE: Not used by Ansible 2.x.
with self.capture_event_data('playbook_on_import_for_host'):
super(BaseCallbackModule, self).v2_playbook_on_import_for_host(result, imported_file)
def v2_playbook_on_not_import_for_host(self, result, missing_file):
# NOTE: Not used by Ansible 2.x.
with self.capture_event_data('playbook_on_not_import_for_host'):
super(BaseCallbackModule, self).v2_playbook_on_not_import_for_host(result, missing_file)
def v2_playbook_on_setup(self):
# NOTE: Not used by Ansible 2.x.
with self.capture_event_data('playbook_on_setup'):
super(BaseCallbackModule, self).v2_playbook_on_setup()
def v2_playbook_on_task_start(self, task, is_conditional):
# FIXME: Flag task path output as vv.
task_uuid = str(task._uuid)
if task_uuid in self.task_uuids:
# When this task UUID repeats, it means the play is using the
# free strategy (or serial:1) so different hosts may be running
# different tasks within a play (where duplicate UUIDS are common).
#
# When this is the case, modify the UUID slightly to append
# a counter so we can still _track_ duplicate events, but also
# avoid breaking the display in these scenarios.
self.duplicate_task_counts[task_uuid] += 1
task_uuid = '_'.join([
task_uuid,
str(self.duplicate_task_counts[task_uuid])
])
self.task_uuids.add(task_uuid)
self.set_task(task)
event_data = dict(
task=task,
name=task.get_name(),
is_conditional=is_conditional,
uuid=task_uuid,
)
with self.capture_event_data('playbook_on_task_start', **event_data):
super(BaseCallbackModule, self).v2_playbook_on_task_start(task, is_conditional)
def v2_playbook_on_cleanup_task_start(self, task):
# NOTE: Not used by Ansible 2.x.
self.set_task(task)
event_data = dict(
task=task,
name=task.get_name(),
uuid=str(task._uuid),
is_conditional=True,
)
with self.capture_event_data('playbook_on_task_start', **event_data):
super(BaseCallbackModule, self).v2_playbook_on_cleanup_task_start(task)
def v2_playbook_on_handler_task_start(self, task):
# NOTE: Re-using playbook_on_task_start event for this v2-specific
# event, but setting is_conditional=True, which is how v1 identified a
# task run as a handler.
self.set_task(task)
event_data = dict(
task=task,
name=task.get_name(),
uuid=str(task._uuid),
is_conditional=True,
)
with self.capture_event_data('playbook_on_task_start', **event_data):
super(BaseCallbackModule, self).v2_playbook_on_handler_task_start(task)
def v2_playbook_on_no_hosts_matched(self):
with self.capture_event_data('playbook_on_no_hosts_matched'):
super(BaseCallbackModule, self).v2_playbook_on_no_hosts_matched()
def v2_playbook_on_no_hosts_remaining(self):
with self.capture_event_data('playbook_on_no_hosts_remaining'):
super(BaseCallbackModule, self).v2_playbook_on_no_hosts_remaining()
def v2_playbook_on_notify(self, handler, host):
# NOTE: Not used by Ansible < 2.5.
event_data = dict(
host=host.get_name(),
handler=handler.get_name(),
)
with self.capture_event_data('playbook_on_notify', **event_data):
super(BaseCallbackModule, self).v2_playbook_on_notify(handler, host)
'''
ansible_stats is, retoractively, added in 2.2
'''
def v2_playbook_on_stats(self, stats):
self.clear_play()
# FIXME: Add count of plays/tasks.
event_data = dict(
changed=stats.changed,
dark=stats.dark,
failures=stats.failures,
ignored=getattr(stats, 'ignored', 0),
ok=stats.ok,
processed=stats.processed,
rescued=getattr(stats, 'rescued', 0),
skipped=stats.skipped,
artifact_data=stats.custom.get('_run', {}) if hasattr(stats, 'custom') else {}
)
with self.capture_event_data('playbook_on_stats', **event_data):
super(BaseCallbackModule, self).v2_playbook_on_stats(stats)
@staticmethod
def _get_event_loop(task):
if hasattr(task, 'loop_with'): # Ansible >=2.5
return task.loop_with
elif hasattr(task, 'loop'): # Ansible <2.4
return task.loop
return None
def _get_result_timing_data(self, result):
host_start = self._host_start.get(result._host.get_name())
if host_start:
end_time = current_time()
return host_start, end_time, (end_time - host_start).total_seconds()
return None, None, None
def v2_runner_on_ok(self, result):
# FIXME: Display detailed results or not based on verbosity.
# strip environment vars from the job event; it already exists on the
# job and sensitive values are filtered there
if result._task.action in ('setup', 'gather_facts'):
result._result.get('ansible_facts', {}).pop('ansible_env', None)
host_start, end_time, duration = self._get_result_timing_data(result)
event_data = dict(
host=result._host.get_name(),
remote_addr=result._host.address,
task=result._task,
res=result._result,
start=host_start,
end=end_time,
duration=duration,
event_loop=self._get_event_loop(result._task),
)
with self.capture_event_data('runner_on_ok', **event_data):
super(BaseCallbackModule, self).v2_runner_on_ok(result)
def v2_runner_on_failed(self, result, ignore_errors=False):
# FIXME: Add verbosity for exception/results output.
host_start, end_time, duration = self._get_result_timing_data(result)
event_data = dict(
host=result._host.get_name(),
remote_addr=result._host.address,
res=result._result,
task=result._task,
start=host_start,
end=end_time,
duration=duration,
ignore_errors=ignore_errors,
event_loop=self._get_event_loop(result._task),
)
with self.capture_event_data('runner_on_failed', **event_data):
super(BaseCallbackModule, self).v2_runner_on_failed(result, ignore_errors)
def v2_runner_on_skipped(self, result):
host_start, end_time, duration = self._get_result_timing_data(result)
event_data = dict(
host=result._host.get_name(),
remote_addr=result._host.address,
task=result._task,
start=host_start,
end=end_time,
duration=duration,
event_loop=self._get_event_loop(result._task),
)
with self.capture_event_data('runner_on_skipped', **event_data):
super(BaseCallbackModule, self).v2_runner_on_skipped(result)
def v2_runner_on_unreachable(self, result):
host_start, end_time, duration = self._get_result_timing_data(result)
event_data = dict(
host=result._host.get_name(),
remote_addr=result._host.address,
task=result._task,
start=host_start,
end=end_time,
duration=duration,
res=result._result,
)
with self.capture_event_data('runner_on_unreachable', **event_data):
super(BaseCallbackModule, self).v2_runner_on_unreachable(result)
def v2_runner_on_no_hosts(self, task):
# NOTE: Not used by Ansible 2.x.
event_data = dict(
task=task,
)
with self.capture_event_data('runner_on_no_hosts', **event_data):
super(BaseCallbackModule, self).v2_runner_on_no_hosts(task)
def v2_runner_on_async_poll(self, result):
# NOTE: Not used by Ansible 2.x.
event_data = dict(
host=result._host.get_name(),
task=result._task,
res=result._result,
jid=result._result.get('ansible_job_id'),
)
with self.capture_event_data('runner_on_async_poll', **event_data):
super(BaseCallbackModule, self).v2_runner_on_async_poll(result)
def v2_runner_on_async_ok(self, result):
# NOTE: Not used by Ansible 2.x.
event_data = dict(
host=result._host.get_name(),
task=result._task,
res=result._result,
jid=result._result.get('ansible_job_id'),
)
with self.capture_event_data('runner_on_async_ok', **event_data):
super(BaseCallbackModule, self).v2_runner_on_async_ok(result)
def v2_runner_on_async_failed(self, result):
# NOTE: Not used by Ansible 2.x.
event_data = dict(
host=result._host.get_name(),
task=result._task,
res=result._result,
jid=result._result.get('ansible_job_id'),
)
with self.capture_event_data('runner_on_async_failed', **event_data):
super(BaseCallbackModule, self).v2_runner_on_async_failed(result)
def v2_runner_on_file_diff(self, result, diff):
# NOTE: Not used by Ansible 2.x.
event_data = dict(
host=result._host.get_name(),
task=result._task,
diff=diff,
)
with self.capture_event_data('runner_on_file_diff', **event_data):
super(BaseCallbackModule, self).v2_runner_on_file_diff(result, diff)
def v2_on_file_diff(self, result):
# NOTE: Logged as runner_on_file_diff.
event_data = dict(
host=result._host.get_name(),
task=result._task,
diff=result._result.get('diff'),
)
with self.capture_event_data('runner_on_file_diff', **event_data):
super(BaseCallbackModule, self).v2_on_file_diff(result)
def v2_runner_item_on_ok(self, result):
event_data = dict(
host=result._host.get_name(),
task=result._task,
res=result._result,
)
with self.capture_event_data('runner_item_on_ok', **event_data):
super(BaseCallbackModule, self).v2_runner_item_on_ok(result)
def v2_runner_item_on_failed(self, result):
event_data = dict(
host=result._host.get_name(),
task=result._task,
res=result._result,
)
with self.capture_event_data('runner_item_on_failed', **event_data):
super(BaseCallbackModule, self).v2_runner_item_on_failed(result)
def v2_runner_item_on_skipped(self, result):
event_data = dict(
host=result._host.get_name(),
task=result._task,
res=result._result,
)
with self.capture_event_data('runner_item_on_skipped', **event_data):
super(BaseCallbackModule, self).v2_runner_item_on_skipped(result)
def v2_runner_retry(self, result):
event_data = dict(
host=result._host.get_name(),
task=result._task,
res=result._result,
)
with self.capture_event_data('runner_retry', **event_data):
super(BaseCallbackModule, self).v2_runner_retry(result)
def v2_runner_on_start(self, host, task):
event_data = dict(
host=host.get_name(),
task=task
)
self._host_start[host.get_name()] = current_time()
with self.capture_event_data('runner_on_start', **event_data):
super(BaseCallbackModule, self).v2_runner_on_start(host, task)
class AWXDefaultCallbackModule(BaseCallbackModule, DefaultCallbackModule):
CALLBACK_NAME = 'awx_display'
class AWXMinimalCallbackModule(BaseCallbackModule, MinimalCallbackModule):
CALLBACK_NAME = 'minimal'
def v2_playbook_on_play_start(self, play):
pass
def v2_playbook_on_task_start(self, task, is_conditional):
self.set_task(task)
+11
View File
@@ -0,0 +1,11 @@
class AnsibleRunnerException(Exception):
""" Generic Runner Error """
class ConfigurationError(AnsibleRunnerException):
""" Misconfiguration of Runner """
class CallbackError(AnsibleRunnerException):
""" Exception occurred in Callback """
+258
View File
@@ -0,0 +1,258 @@
# Copyright (c) 2016 Ansible by Red Hat, Inc.
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import os
import sys
import threading
import logging
from ansible_runner import output
from ansible_runner.runner_config import RunnerConfig
from ansible_runner.runner import Runner
from ansible_runner.streaming import Transmitter, Worker, Processor
from ansible_runner.utils import (
dump_artifacts,
check_isolation_executable_installed,
)
logging.getLogger('ansible-runner').addHandler(logging.NullHandler())
def init_runner(**kwargs):
'''
Initialize the Runner() instance
This function will properly initialize both run() and run_async()
functions in the same way and return a value instance of Runner.
See parameters given to :py:func:`ansible_runner.interface.run`
'''
# If running via the transmit-worker-process method, we must only extract things as read-only
# inside of one of these commands. That could be either transmit or worker.
if not kwargs.get('cli_execenv_cmd') and (kwargs.get('streamer') not in ('worker', 'process')):
dump_artifacts(kwargs)
if kwargs.get('streamer'):
# undo any full paths that were dumped by dump_artifacts above in the streamer case
private_data_dir = kwargs['private_data_dir']
project_dir = os.path.join(private_data_dir, 'project')
playbook_path = kwargs.get('playbook') or ''
if os.path.isabs(playbook_path) and playbook_path.startswith(project_dir):
kwargs['playbook'] = os.path.relpath(playbook_path, project_dir)
inventory_path = kwargs.get('inventory') or ''
if os.path.isabs(inventory_path) and inventory_path.startswith(private_data_dir):
kwargs['inventory'] = os.path.relpath(inventory_path, private_data_dir)
roles_path = kwargs.get('envvars', {}).get('ANSIBLE_ROLES_PATH') or ''
if os.path.isabs(roles_path) and roles_path.startswith(private_data_dir):
kwargs['envvars']['ANSIBLE_ROLES_PATH'] = os.path.relpath(roles_path, private_data_dir)
debug = kwargs.pop('debug', None)
logfile = kwargs.pop('logfile', None)
if not kwargs.pop("ignore_logging", True):
output.configure()
if debug in (True, False):
output.set_debug('enable' if debug is True else 'disable')
if logfile:
output.set_logfile(logfile)
if kwargs.get("process_isolation", False):
pi_executable = kwargs.get("process_isolation_executable", "podman")
if not check_isolation_executable_installed(pi_executable):
print(f'Unable to find process isolation executable: {pi_executable}')
sys.exit(1)
event_callback_handler = kwargs.pop('event_handler', None)
status_callback_handler = kwargs.pop('status_handler', None)
artifacts_handler = kwargs.pop('artifacts_handler', None)
cancel_callback = kwargs.pop('cancel_callback', None)
finished_callback = kwargs.pop('finished_callback', None)
streamer = kwargs.pop('streamer', None)
if streamer:
if streamer == 'transmit':
stream_transmitter = Transmitter(**kwargs)
return stream_transmitter
if streamer == 'worker':
stream_worker = Worker(**kwargs)
return stream_worker
if streamer == 'process':
stream_processor = Processor(event_handler=event_callback_handler,
status_handler=status_callback_handler,
artifacts_handler=artifacts_handler,
cancel_callback=cancel_callback,
finished_callback=finished_callback,
**kwargs)
return stream_processor
kwargs.pop('_input', None)
kwargs.pop('_output', None)
rc = RunnerConfig(**kwargs)
rc.prepare()
return Runner(rc,
event_handler=event_callback_handler,
status_handler=status_callback_handler,
artifacts_handler=artifacts_handler,
cancel_callback=cancel_callback,
finished_callback=finished_callback)
def run(**kwargs):
'''
Run an Ansible Runner task in the foreground and return a Runner object when complete.
:param private_data_dir: The directory containing all runner metadata needed to invoke the runner
module. Output artifacts will also be stored here for later consumption.
:param ident: The run identifier for this invocation of Runner. Will be used to create and name
the artifact directory holding the results of the invocation.
:param json_mode: Store event data in place of stdout on the console and in the stdout file
:param playbook: The playbook (either supplied here as a list or string... or as a path relative to
``private_data_dir/project``) that will be invoked by runner when executing Ansible.
:param module: The module that will be invoked in ad-hoc mode by runner when executing Ansible.
:param module_args: The module arguments that will be supplied to ad-hoc mode.
:param host_pattern: The host pattern to match when running in ad-hoc mode.
:param inventory: Overrides the inventory directory/file (supplied at ``private_data_dir/inventory``) with
a specific host or list of hosts. This can take the form of
- Path to the inventory file in the ``private_data_dir``
- Native python dict supporting the YAML/json inventory structure
- A text INI formatted string
- A list of inventory sources, or an empty list to disable passing inventory
:param roles_path: Directory or list of directories to assign to ANSIBLE_ROLES_PATH
:param envvars: Environment variables to be used when running Ansible. Environment variables will also be
read from ``env/envvars`` in ``private_data_dir``
:param extravars: Extra variables to be passed to Ansible at runtime using ``-e``. Extra vars will also be
read from ``env/extravars`` in ``private_data_dir``.
:param passwords: A dictionary containing password prompt patterns and response values used when processing output from
Ansible. Passwords will also be read from ``env/passwords`` in ``private_data_dir``.
:param settings: A dictionary containing settings values for the ``ansible-runner`` runtime environment. These will also
be read from ``env/settings`` in ``private_data_dir``.
:param ssh_key: The ssh private key passed to ``ssh-agent`` as part of the ansible-playbook run.
:param cmdline: Command line options passed to Ansible read from ``env/cmdline`` in ``private_data_dir``
:param limit: Matches ansible's ``--limit`` parameter to further constrain the inventory to be used
:param forks: Control Ansible parallel concurrency
:param verbosity: Control how verbose the output of ansible-playbook is
:param quiet: Disable all output
:param artifact_dir: The path to the directory where artifacts should live, this defaults to 'artifacts' under the private data dir
:param project_dir: The path to the playbook content, this defaults to 'project' within the private data dir
:param rotate_artifacts: Keep at most n artifact directories, disable with a value of 0 which is the default
:param streamer: Optionally invoke ansible-runner as one of the steps in the streaming pipeline
:param _input: An optional file or file-like object for use as input in a streaming pipeline
:param _output: An optional file or file-like object for use as output in a streaming pipeline
:param event_handler: An optional callback that will be invoked any time an event is received by Runner itself, return True to keep the event
:param cancel_callback: An optional callback that can inform runner to cancel (returning True) or not (returning False)
:param finished_callback: An optional callback that will be invoked at shutdown after process cleanup.
:param status_handler: An optional callback that will be invoked any time the status changes (e.g...started, running, failed, successful, timeout)
:param artifacts_handler: An optional callback that will be invoked at the end of the run to deal with the artifacts from the run.
:param process_isolation: Enable process isolation, using either a container engine (e.g. podman) or a sandbox (e.g. bwrap).
:param process_isolation_executable: Process isolation executable or container engine used to isolate execution. (default: podman)
:param process_isolation_path: Path that an isolated playbook run will use for staging. (default: /tmp)
:param process_isolation_hide_paths: A path or list of paths on the system that should be hidden from the playbook run.
:param process_isolation_show_paths: A path or list of paths on the system that should be exposed to the playbook run.
:param process_isolation_ro_paths: A path or list of paths on the system that should be exposed to the playbook run as read-only.
:param container_image: Container image to use when running an ansible task (default: quay.io/ansible/ansible-runner:devel)
:param container_volume_mounts: List of bind mounts in the form 'host_dir:/container_dir. (default: None)
:param container_options: List of container options to pass to execution engine.
:param resource_profiling: Enable collection of resource utilization data during playbook execution.
:param resource_profiling_base_cgroup: Name of existing cgroup which will be sub-grouped in order to measure resource utilization (default: ansible-runner)
:param resource_profiling_cpu_poll_interval: Interval (in seconds) between CPU polling for determining CPU usage (default: 0.25)
:param resource_profiling_memory_poll_interval: Interval (in seconds) between memory polling for determining memory usage (default: 0.25)
:param resource_profiling_pid_poll_interval: Interval (in seconds) between polling PID count for determining number of processes used (default: 0.25)
:param resource_profiling_results_dir: Directory where profiling data files should be saved (defaults to profiling_data folder inside private data dir)
:param directory_isolation_base_path: An optional path will be used as the base path to create a temp directory, the project contents will be
copied to this location which will then be used as the working directory during playbook execution.
:param fact_cache: A string that will be used as the name for the subdirectory of the fact cache in artifacts directory.
This is only used for 'jsonfile' type fact caches.
:param fact_cache_type: A string of the type of fact cache to use. Defaults to 'jsonfile'.
:param omit_event_data: Omits extra ansible event data from event payload (stdout and event still included)
:param only_failed_event_data: Omits extra ansible event data unless it's a failed event (stdout and event still included)
:param cli_execenv_cmd: Tells Ansible Runner to emulate the CLI of Ansible by prepping an Execution Environment and then passing the user provided cmdline
:type private_data_dir: str
:type ident: str
:type json_mode: bool
:type playbook: str or filename or list
:type inventory: str or dict or list
:type envvars: dict
:type extravars: dict
:type passwords: dict
:type settings: dict
:type ssh_key: str
:type artifact_dir: str
:type project_dir: str
:type rotate_artifacts: int
:type cmdline: str
:type limit: str
:type forks: int
:type quiet: bool
:type verbosity: int
:type streamer: str
:type _input: file
:type _output: file
:type event_handler: function
:type cancel_callback: function
:type finished_callback: function
:type status_handler: function
:type artifacts_handler: function
:type process_isolation: bool
:type process_isolation_executable: str
:type process_isolation_path: str
:type process_isolation_hide_paths: str or list
:type process_isolation_show_paths: str or list
:type process_isolation_ro_paths: str or list
:type container_image: str
:type container_volume_mounts: list
:type container_options: list
:type resource_profiling: bool
:type resource_profiling_base_cgroup: str
:type resource_profiling_cpu_poll_interval: float
:type resource_profiling_memory_poll_interval: float
:type resource_profiling_pid_poll_interval: float
:type resource_profiling_results_dir: str
:type directory_isolation_base_path: str
:type fact_cache: str
:type fact_cache_type: str
:type omit_event_data: bool
:type only_failed_event_data: bool
:type cli_execenv_cmd: str
:returns: A :py:class:`ansible_runner.runner.Runner` object, or a simple object containing `rc` if run remotely
'''
r = init_runner(**kwargs)
r.run()
return r
def run_async(**kwargs):
'''
Runs an Ansible Runner task in the background which will start immediately. Returns the thread object and a Runner object.
This uses the same parameters as :py:func:`ansible_runner.interface.run`
:returns: A tuple containing a :py:class:`threading.Thread` object and a :py:class:`ansible_runner.runner.Runner` object
'''
r = init_runner(**kwargs)
runner_thread = threading.Thread(target=r.run)
runner_thread.start()
return runner_thread, r
+185
View File
@@ -0,0 +1,185 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import os
import json
import codecs
from yaml import safe_load, YAMLError
from six import string_types
from ansible_runner.exceptions import ConfigurationError
from ansible_runner.output import debug
class ArtifactLoader(object):
'''
Handles loading and caching file contents from disk
This class will load the file contents and attempt to deserialize the
contents as either JSON or YAML. If the file contents cannot be
deserialized, the contents will be returned to the caller as a string.
The deserialized file contents are stored as a cached object in the
instance to avoid any additional reads from disk for subsequent calls
to load the same file.
'''
def __init__(self, base_path):
self._cache = {}
self.base_path = base_path
def _load_json(self, contents):
'''
Attempts to deserialize the contents of a JSON object
Args:
contents (string): The contents to deserialize
Returns:
dict: If the contents are JSON serialized
None: If the contents are not JSON serialized
'''
try:
return json.loads(contents)
except ValueError:
pass
def _load_yaml(self, contents):
'''
Attempts to deserialize the contents of a YAML object
Args:
contents (string): The contents to deserialize
Returns:
dict: If the contents are YAML serialized
None: If the contents are not YAML serialized
'''
try:
return safe_load(contents)
except YAMLError:
pass
def get_contents(self, path):
'''
Loads the contents of the file specified by path
Args:
path (string): The relative or absolute path to the file to
be loaded. If the path is relative, then it is combined
with the base_path to generate a full path string
Returns:
string: The contents of the file as a string
Raises:
ConfigurationError: If the file cannot be loaded
'''
try:
if not os.path.exists(path):
raise ConfigurationError('specified path does not exist %s' % path)
with codecs.open(path, encoding='utf-8') as f:
data = f.read()
return data
except (IOError, OSError) as exc:
raise ConfigurationError('error trying to load file contents: %s' % exc)
def abspath(self, path):
'''
Transform the path to an absolute path
Args:
path (string): The path to transform to an absolute path
Returns:
string: The absolute path to the file
'''
if not path.startswith(os.path.sep) or path.startswith('~'):
path = os.path.expanduser(os.path.join(self.base_path, path))
return path
def isfile(self, path):
'''
Check if the path is a file
:params path: The path to the file to check. If the path is relative
it will be exanded to an absolute path
:returns: boolean
'''
return os.path.isfile(self.abspath(path))
def load_file(self, path, objtype=None, encoding='utf-8'):
'''
Load the file specified by path
This method will first try to load the file contents from cache and
if there is a cache miss, it will load the contents from disk
Args:
path (string): The full or relative path to the file to be loaded
encoding (string): The file contents text encoding
objtype (object): The object type of the file contents. This
is used to type check the deserialized content against the
contents loaded from disk.
Ignore serializing if objtype is string_types
Returns:
object: The deserialized file contents which could be either a
string object or a dict object
Raises:
ConfigurationError:
'''
path = self.abspath(path)
debug('file path is %s' % path)
if path in self._cache:
return self._cache[path]
try:
debug('cache miss, attempting to load file from disk: %s' % path)
contents = parsed_data = self.get_contents(path)
if encoding:
parsed_data = contents.encode(encoding)
except ConfigurationError as exc:
debug(exc)
raise
except UnicodeEncodeError:
raise ConfigurationError('unable to encode file contents')
if objtype is not string_types:
for deserializer in (self._load_json, self._load_yaml):
parsed_data = deserializer(contents)
if parsed_data:
break
if objtype and not isinstance(parsed_data, objtype):
debug('specified file %s is not of type %s' % (path, objtype))
raise ConfigurationError('invalid file serialization type for contents')
self._cache[path] = parsed_data
return parsed_data
+91
View File
@@ -0,0 +1,91 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import sys
import logging
DEBUG_ENABLED = False
TRACEBACK_ENABLED = True
_display_logger = logging.getLogger('ansible-runner.display')
_debug_logger = logging.getLogger('ansible-runner.debug')
def display(msg, log_only=False):
if not log_only:
_display_logger.log(70, msg)
_debug_logger.log(10, msg)
def debug(msg):
if DEBUG_ENABLED:
if isinstance(msg, Exception):
if TRACEBACK_ENABLED:
_debug_logger.exception(msg)
display(msg)
def set_logfile(filename):
handlers = [h.get_name() for h in _debug_logger.handlers]
if 'logfile' not in handlers:
logfile_handler = logging.FileHandler(filename)
logfile_handler.set_name('logfile')
formatter = logging.Formatter('%(asctime)s: %(message)s')
logfile_handler.setFormatter(formatter)
_debug_logger.addHandler(logfile_handler)
def set_debug(value):
global DEBUG_ENABLED
if value.lower() not in ('enable', 'disable'):
raise ValueError('value must be one of `enable` or `disable`, got %s' % value)
DEBUG_ENABLED = value.lower() == 'enable'
def set_traceback(value):
global TRACEBACK_ENABLED
if value.lower() not in ('enable', 'disable'):
raise ValueError('value must be one of `enable` or `disable`, got %s' % value)
TRACEBACK_ENABLED = value.lower() == 'enable'
def configure():
'''
Configures the logging facility
This function will setup an initial logging facility for handling display
and debug outputs. The default facility will send display messages to
stdout and the default debug facility will do nothing.
:returns: None
'''
root_logger = logging.getLogger()
root_logger.addHandler(logging.NullHandler())
root_logger.setLevel(99)
_display_logger.setLevel(70)
_debug_logger.setLevel(10)
display_handlers = [h.get_name() for h in _display_logger.handlers]
if 'stdout' not in display_handlers:
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.set_name('stdout')
formatter = logging.Formatter('%(message)s')
stdout_handler.setFormatter(formatter)
_display_logger.addHandler(stdout_handler)
View File
+472
View File
@@ -0,0 +1,472 @@
import os
import stat
import time
import json
import errno
import signal
from subprocess import Popen, PIPE
import shutil
import codecs
import collections
import datetime
import logging
import six
import pexpect
import ansible_runner.plugins
from .utils import OutputEventFilter, cleanup_artifact_dir, ensure_str, collect_new_events
from .exceptions import CallbackError, AnsibleRunnerException
from ansible_runner.output import debug
logger = logging.getLogger('ansible-runner')
class Runner(object):
def __init__(self, config, cancel_callback=None, remove_partials=True, event_handler=None,
artifacts_handler=None, finished_callback=None, status_handler=None):
self.config = config
self.cancel_callback = cancel_callback
self.event_handler = event_handler
self.artifacts_handler = artifacts_handler
self.finished_callback = finished_callback
self.status_handler = status_handler
self.canceled = False
self.timed_out = False
self.errored = False
self.status = "unstarted"
self.rc = None
self.remove_partials = remove_partials
def event_callback(self, event_data):
'''
Invoked for every Ansible event to collect stdout with the event data and store it for
later use
'''
self.last_stdout_update = time.time()
if 'uuid' in event_data:
filename = '{}-partial.json'.format(event_data['uuid'])
partial_filename = os.path.join(self.config.artifact_dir,
'job_events',
filename)
full_filename = os.path.join(self.config.artifact_dir,
'job_events',
'{}-{}.json'.format(event_data['counter'],
event_data['uuid']))
try:
event_data.update(dict(runner_ident=str(self.config.ident)))
try:
with codecs.open(partial_filename, 'r', encoding='utf-8') as read_file:
partial_event_data = json.load(read_file)
event_data.update(partial_event_data)
if self.remove_partials:
os.remove(partial_filename)
except IOError:
debug("Failed to open ansible stdout callback plugin partial data file {}".format(partial_filename))
# prefer 'created' from partial data, but verbose events set time here
if 'created' not in event_data:
event_data['created'] = datetime.datetime.utcnow().isoformat()
if self.event_handler is not None:
should_write = self.event_handler(event_data)
else:
should_write = True
for plugin in ansible_runner.plugins:
ansible_runner.plugins[plugin].event_handler(self.config, event_data)
if should_write:
with codecs.open(full_filename, 'w', encoding='utf-8') as write_file:
os.chmod(full_filename, stat.S_IRUSR | stat.S_IWUSR)
json.dump(event_data, write_file)
except IOError as e:
debug("Failed writing event data: {}".format(e))
def status_callback(self, status):
self.status = status
status_data = {'status': status, 'runner_ident': str(self.config.ident)}
if status == 'starting':
status_data.update({'command': self.config.command, 'env': self.config.env, 'cwd': self.config.cwd})
for plugin in ansible_runner.plugins:
ansible_runner.plugins[plugin].status_handler(self.config, status_data)
if self.status_handler is not None:
self.status_handler(status_data, runner_config=self.config)
def run(self):
'''
Launch the Ansible task configured in self.config (A RunnerConfig object), returns once the
invocation is complete
'''
self.status_callback('starting')
stdout_filename = os.path.join(self.config.artifact_dir, 'stdout')
command_filename = os.path.join(self.config.artifact_dir, 'command')
try:
os.makedirs(self.config.artifact_dir, mode=0o700)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(self.config.artifact_dir):
pass
else:
raise
os.close(os.open(stdout_filename, os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR))
job_events_path = os.path.join(self.config.artifact_dir, 'job_events')
if not os.path.exists(job_events_path):
os.mkdir(job_events_path, 0o700)
command = self.config.command
with codecs.open(command_filename, 'w', encoding='utf-8') as f:
os.chmod(command_filename, stat.S_IRUSR | stat.S_IWUSR)
json.dump(
{'command': command,
'cwd': self.config.cwd,
'env': self.config.env}, f, ensure_ascii=False
)
if self.config.ident is not None:
cleanup_artifact_dir(os.path.join(self.config.artifact_dir, ".."), self.config.rotate_artifacts)
stdout_handle = codecs.open(stdout_filename, 'w', encoding='utf-8')
stdout_handle = OutputEventFilter(stdout_handle, self.event_callback, self.config.suppress_ansible_output, output_json=self.config.json_mode)
if not isinstance(self.config.expect_passwords, collections.OrderedDict):
# We iterate over `expect_passwords.keys()` and
# `expect_passwords.values()` separately to map matched inputs to
# patterns and choose the proper string to send to the subprocess;
# enforce usage of an OrderedDict so that the ordering of elements in
# `keys()` matches `values()`.
expect_passwords = collections.OrderedDict(self.config.expect_passwords)
password_patterns = list(expect_passwords.keys())
password_values = list(expect_passwords.values())
# pexpect needs all env vars to be utf-8 encoded bytes
# https://github.com/pexpect/pexpect/issues/512
# Use a copy so as not to cause problems when serializing the job_env.
if self.config.containerized:
# We call the actual docker or podman executable right where we are
cwd = os.getcwd()
# If this is containerized, the shell environment calling podman has little
# to do with the actual job environment, but still needs PATH, auth, etc.
pexpect_env = os.environ.copy()
# But we still rely on env vars to pass secrets
pexpect_env.update(self.config.env)
# Write the keys to pass into container to expected file in artifacts dir
# option expecting should have already been written in ansible_runner.runner_config
env_file_host = os.path.join(self.config.artifact_dir, 'env.list')
with open(env_file_host, 'w') as f:
f.write('\n'.join(list(self.config.env.keys())))
else:
cwd = self.config.cwd
pexpect_env = self.config.env
env = {
ensure_str(k): ensure_str(v) if k != 'PATH' and isinstance(v, six.text_type) else v
for k, v in pexpect_env.items()
}
# Prepare to collect performance data
if self.config.resource_profiling:
cgroup_path = '{0}/{1}'.format(self.config.resource_profiling_base_cgroup, self.config.ident)
import getpass
import grp
user = getpass.getuser()
group = grp.getgrgid(os.getgid()).gr_name
cmd = 'cgcreate -a {user}:{group} -t {user}:{group} -g cpuacct,memory,pids:{}'.format(cgroup_path, user=user, group=group)
proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
_, stderr = proc.communicate()
if proc.returncode:
# Unable to create cgroup
logger.error('Unable to create cgroup: {}'.format(stderr))
raise RuntimeError('Unable to create cgroup: {}'.format(stderr))
else:
logger.info("Created cgroup '{}'".format(cgroup_path))
self.status_callback('running')
self.last_stdout_update = time.time()
try:
child = pexpect.spawn(
command[0],
command[1:],
cwd=cwd,
env=env,
ignore_sighup=True,
encoding='utf-8',
codec_errors='replace',
echo=False,
use_poll=self.config.pexpect_use_poll,
)
child.logfile_read = stdout_handle
except pexpect.exceptions.ExceptionPexpect as e:
child = collections.namedtuple(
'MissingProcess', 'exitstatus isalive close'
)(
exitstatus=127,
isalive=lambda: False,
close=lambda: None,
)
def _decode(x):
return x.decode('utf-8') if six.PY2 else x
# create the events directory (the callback plugin won't run, so it
# won't get created)
events_directory = os.path.join(self.config.artifact_dir, 'job_events')
if not os.path.exists(events_directory):
os.mkdir(events_directory, 0o700)
stdout_handle.write(_decode(str(e)))
stdout_handle.write(_decode('\n'))
job_start = time.time()
while child.isalive():
result_id = child.expect(password_patterns,
timeout=self.config.pexpect_timeout,
searchwindowsize=100)
password = password_values[result_id]
if password is not None:
child.sendline(password)
self.last_stdout_update = time.time()
if self.cancel_callback:
try:
self.canceled = self.cancel_callback()
except Exception as e:
# TODO: logger.exception('Could not check cancel callback - cancelling immediately')
#if isinstance(extra_update_fields, dict):
# extra_update_fields['job_explanation'] = "System error during job execution, check system logs"
raise CallbackError("Exception in Cancel Callback: {}".format(e))
if self.config.job_timeout and not self.canceled and (time.time() - job_start) > self.config.job_timeout:
self.timed_out = True
# if isinstance(extra_update_fields, dict):
# extra_update_fields['job_explanation'] = "Job terminated due to timeout"
if self.canceled or self.timed_out or self.errored:
self.kill_container()
Runner.handle_termination(child.pid, is_cancel=self.canceled)
if self.config.idle_timeout and (time.time() - self.last_stdout_update) > self.config.idle_timeout:
self.kill_container()
Runner.handle_termination(child.pid, is_cancel=False)
self.timed_out = True
stdout_handle.flush()
stdout_handle.close()
child.close()
if self.canceled:
self.status_callback('canceled')
elif child.exitstatus == 0 and not self.timed_out:
self.status_callback('successful')
elif self.timed_out:
self.status_callback('timeout')
else:
self.status_callback('failed')
self.rc = child.exitstatus if not (self.timed_out or self.canceled) else 254
for filename, data in [
('status', self.status),
('rc', self.rc),
]:
artifact_path = os.path.join(self.config.artifact_dir, filename)
if not os.path.exists(artifact_path):
os.close(os.open(artifact_path, os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR))
with open(artifact_path, 'w') as f:
f.write(str(data))
if self.config.directory_isolation_path and self.config.directory_isolation_cleanup:
shutil.rmtree(self.config.directory_isolation_path)
if self.config.process_isolation and self.config.process_isolation_path_actual:
def _delete(retries=15):
try:
shutil.rmtree(self.config.process_isolation_path_actual)
except OSError as e:
res = False
if e.errno == 16 and retries > 0:
time.sleep(1)
res = _delete(retries=retries - 1)
if not res:
raise
return True
_delete()
if self.config.resource_profiling:
cmd = 'cgdelete -g cpuacct,memory,pids:{}'.format(cgroup_path)
proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
_, stderr = proc.communicate()
if proc.returncode:
logger.error('Failed to delete cgroup: {}'.format(stderr))
raise RuntimeError('Failed to delete cgroup: {}'.format(stderr))
if self.artifacts_handler is not None:
try:
self.artifacts_handler(self.config.artifact_dir)
except Exception as e:
raise CallbackError("Exception in Artifact Callback: {}".format(e))
if self.finished_callback is not None:
try:
self.finished_callback(self)
except Exception as e:
raise CallbackError("Exception in Finished Callback: {}".format(e))
return self.status, self.rc
@property
def stdout(self):
'''
Returns an open file handle to the stdout representing the Ansible run
'''
stdout_path = os.path.join(self.config.artifact_dir, 'stdout')
if not os.path.exists(stdout_path):
raise AnsibleRunnerException("stdout missing")
return open(os.path.join(self.config.artifact_dir, 'stdout'), 'r')
@property
def events(self):
'''
A generator that will return all ansible job events in the order that they were emitted from Ansible
Example:
{
"event":"runner_on_ok",
"uuid":"00a50d9c-161a-4b74-b978-9f60becaf209",
"stdout":"ok: [localhost] => {\\r\\n \\" msg\\":\\"Test!\\"\\r\\n}",
"counter":6,
"pid":740,
"created":"2018-04-05T18:24:36.096725",
"end_line":10,
"start_line":7,
"event_data":{
"play_pattern":"all",
"play":"all",
"task":"debug",
"task_args":"msg=Test!",
"remote_addr":"localhost",
"res":{
"msg":"Test!",
"changed":false,
"_ansible_verbose_always":true,
"_ansible_no_log":false
},
"pid":740,
"play_uuid":"0242ac11-0002-443b-cdb1-000000000006",
"task_uuid":"0242ac11-0002-443b-cdb1-000000000008",
"event_loop":null,
"playbook_uuid":"634edeee-3228-4c17-a1b4-f010fdd42eb2",
"playbook":"test.yml",
"task_action":"debug",
"host":"localhost",
"task_path":"/tmp/demo/project/test.yml:3"
}
}
'''
# collection of all the events that were yielded
old_events = {}
event_path = os.path.join(self.config.artifact_dir, 'job_events')
# Wait for events dir to be created
now = datetime.datetime.now()
while not os.path.exists(event_path):
time.sleep(0.05)
wait_time = datetime.datetime.now() - now
if wait_time.total_seconds() > 60:
raise AnsibleRunnerException("events directory is missing: %s" % event_path)
while self.status == "running":
for event, old_evnts in collect_new_events(event_path, old_events):
old_events = old_evnts
yield event
# collect new events that were written after the playbook has finished
for event, old_evnts in collect_new_events(event_path, old_events):
old_events = old_evnts
yield event
@property
def stats(self):
'''
Returns the final high level stats from the Ansible run
Example:
{'dark': {}, 'failures': {}, 'skipped': {}, 'ok': {u'localhost': 2}, 'processed': {u'localhost': 1}}
'''
last_event = list(filter(lambda x: 'event' in x and x['event'] == 'playbook_on_stats',
self.events))
if not last_event:
return None
last_event = last_event[0]['event_data']
return dict(skipped=last_event.get('skipped',{}),
ok=last_event.get('ok',{}),
dark=last_event.get('dark',{}),
failures=last_event.get('failures',{}),
ignored=last_event.get('ignored', {}),
rescued=last_event.get('rescued', {}),
processed=last_event.get('processed',{}),
changed=last_event.get('changed',{}))
def host_events(self, host):
'''
Given a host name, this will return all task events executed on that host
'''
all_host_events = filter(lambda x: 'event_data' in x and 'host' in x['event_data'] and x['event_data']['host'] == host,
self.events)
return all_host_events
def kill_container(self):
'''
Internal method to terminate a container being used for job isolation
'''
container_name = self.config.container_name
if container_name:
container_cli = self.config.process_isolation_executable
cmd = '{} kill {}'.format(container_cli, container_name)
proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
_, stderr = proc.communicate()
if proc.returncode:
logger.info('Error from {} kill {} command:\n{}'.format(container_cli, container_name, stderr))
else:
logger.info("Killed container {}".format(container_name))
@classmethod
def handle_termination(cls, pid, pidfile=None, is_cancel=True):
'''
Internal method to terminate a subprocess spawned by `pexpect` representing an invocation of runner.
:param pid: the process id of the running the job.
:param pidfile: the daemon's PID file
:param is_cancel: flag showing whether this termination is caused by
instance's cancel_flag.
'''
try:
pgroup = os.getpgid(pid)
os.killpg(pgroup, signal.SIGKILL)
except (OSError, ProcessLookupError):
pass
try:
os.remove(pidfile)
except (TypeError, OSError):
pass
def get_fact_cache(self, host):
'''
Get the entire fact cache only if the fact_cache_type is 'jsonfile'
'''
if self.config.fact_cache_type != 'jsonfile':
raise Exception('Unsupported fact cache type. Only "jsonfile" is supported for reading and writing facts from ansible-runner')
fact_cache = os.path.join(self.config.fact_cache, host)
if os.path.exists(fact_cache):
with open(fact_cache) as f:
return json.loads(f.read())
return {}
def set_fact_cache(self, host, data):
'''
Set the entire fact cache data only if the fact_cache_type is 'jsonfile'
'''
if self.config.fact_cache_type != 'jsonfile':
raise Exception('Unsupported fact cache type. Only "jsonfile" is supported for reading and writing facts from ansible-runner')
fact_cache = os.path.join(self.config.fact_cache, host)
if not os.path.exists(os.path.dirname(fact_cache)):
os.makedirs(os.path.dirname(fact_cache), mode=0o700)
with open(fact_cache, 'w') as f:
return f.write(json.dumps(data))
+881
View File
@@ -0,0 +1,881 @@
############################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import json
import logging
import os
import pexpect
import re
import shlex
import stat
import tempfile
import six
from uuid import uuid4
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
from distutils.dir_util import copy_tree
from six import iteritems, string_types, text_type
from ansible_runner import defaults
from ansible_runner import output
from ansible_runner.exceptions import ConfigurationError
from ansible_runner.loader import ArtifactLoader
from ansible_runner.output import debug
from ansible_runner.utils import (
open_fifo_write,
args2cmdline,
sanitize_container_name
)
logger = logging.getLogger('ansible-runner')
class ExecutionMode():
NONE = 0
ANSIBLE = 1
ANSIBLE_PLAYBOOK = 2
RAW = 3
CLI_EXECENV = 4
class RunnerConfig(object):
"""
A ``Runner`` configuration object that's meant to encapsulate the configuration used by the
:py:mod:`ansible_runner.runner.Runner` object to launch and manage the invocation of ``ansible``
and ``ansible-playbook``
Typically this object is initialized for you when using the standard ``run`` interfaces in :py:mod:`ansible_runner.interface`
but can be used to construct the ``Runner`` configuration to be invoked elsewhere. It can also be overridden to provide different
functionality to the Runner object.
:Example:
>>> rc = RunnerConfig(...)
>>> r = Runner(config=rc)
>>> r.run()
"""
def __init__(self,
private_data_dir=None, playbook=None, ident=None,
inventory=None, roles_path=None, limit=None, module=None, module_args=None,
verbosity=None, quiet=False, json_mode=False, artifact_dir=None,
rotate_artifacts=0, host_pattern=None, binary=None, extravars=None, suppress_ansible_output=False,
process_isolation=False, process_isolation_executable=None, process_isolation_path=None,
process_isolation_hide_paths=None, process_isolation_show_paths=None, process_isolation_ro_paths=None,
container_image=None, container_volume_mounts=None, container_options=None,
resource_profiling=False, resource_profiling_base_cgroup='ansible-runner', resource_profiling_cpu_poll_interval=0.25,
resource_profiling_memory_poll_interval=0.25, resource_profiling_pid_poll_interval=0.25,
resource_profiling_results_dir=None,
tags=None, skip_tags=None, fact_cache_type='jsonfile', fact_cache=None, ssh_key=None,
project_dir=None, directory_isolation_base_path=None, envvars=None, forks=None, cmdline=None, omit_event_data=False,
only_failed_event_data=False, cli_execenv_cmd=""):
self.private_data_dir = os.path.abspath(private_data_dir)
if ident is None:
self.ident = str(uuid4())
else:
self.ident = ident
self.json_mode = json_mode
self.playbook = playbook
self.inventory = inventory
self.roles_path = roles_path
self.limit = limit
self.module = module
self.module_args = module_args
self.cli_execenv_cmd = cli_execenv_cmd
self.host_pattern = host_pattern
self.binary = binary
self.rotate_artifacts = rotate_artifacts
self.artifact_dir = os.path.abspath(artifact_dir or self.private_data_dir)
if artifact_dir is None:
self.artifact_dir = os.path.join(self.private_data_dir, 'artifacts')
else:
self.artifact_dir = os.path.abspath(artifact_dir)
if self.ident is not None:
self.artifact_dir = os.path.join(self.artifact_dir, "{}".format(self.ident))
self.extra_vars = extravars
self.process_isolation = process_isolation
self.process_isolation_executable = process_isolation_executable or defaults.default_process_isolation_executable
self.process_isolation_path = process_isolation_path
self.container_name = None # like other properties, not accurate until prepare is called
self.process_isolation_path_actual = None
self.process_isolation_hide_paths = process_isolation_hide_paths
self.process_isolation_show_paths = process_isolation_show_paths
self.process_isolation_ro_paths = process_isolation_ro_paths
self.container_image = container_image or defaults.default_container_image
self.container_volume_mounts = container_volume_mounts
self.container_options = container_options
self.resource_profiling = resource_profiling
self.resource_profiling_base_cgroup = resource_profiling_base_cgroup
self.resource_profiling_cpu_poll_interval = resource_profiling_cpu_poll_interval
self.resource_profiling_memory_poll_interval = resource_profiling_memory_poll_interval
self.resource_profiling_pid_poll_interval = resource_profiling_pid_poll_interval
self.resource_profiling_results_dir = resource_profiling_results_dir
self.directory_isolation_path = directory_isolation_base_path
if not project_dir:
self.project_dir = os.path.join(self.private_data_dir, 'project')
else:
self.project_dir = project_dir
self.verbosity = verbosity
self.quiet = quiet
self.suppress_ansible_output = suppress_ansible_output
self.loader = ArtifactLoader(self.private_data_dir)
self.tags = tags
self.skip_tags = skip_tags
self.fact_cache_type = fact_cache_type
self.fact_cache = os.path.join(self.artifact_dir, fact_cache or 'fact_cache') if self.fact_cache_type == 'jsonfile' else None
self.ssh_key_data = ssh_key
self.execution_mode = ExecutionMode.NONE
self.envvars = envvars
self.forks = forks
self.cmdline_args = cmdline
self.omit_event_data = omit_event_data
self.only_failed_event_data = only_failed_event_data
_CONTAINER_ENGINES = ('docker', 'podman')
@property
def sandboxed(self):
return self.process_isolation and self.process_isolation_executable not in self._CONTAINER_ENGINES
@property
def containerized(self):
return self.process_isolation and self.process_isolation_executable in self._CONTAINER_ENGINES
def prepare(self):
"""
Performs basic checks and then properly invokes
- prepare_inventory
- prepare_env
- prepare_command
It's also responsible for wrapping the command with the proper ssh agent invocation
and setting early ANSIBLE_ environment variables.
"""
# ansible_path = find_executable('ansible')
# if ansible_path is None or not os.access(ansible_path, os.X_OK):
# raise ConfigurationError("Ansible not found. Make sure that it is installed.")
if self.private_data_dir is None:
raise ConfigurationError("Runner Base Directory is not defined")
if self.module and self.playbook:
raise ConfigurationError("Only one of playbook and module options are allowed")
if not os.path.exists(self.artifact_dir):
os.makedirs(self.artifact_dir, mode=0o700)
if self.sandboxed and self.directory_isolation_path is not None:
self.directory_isolation_path = tempfile.mkdtemp(prefix='runner_di_', dir=self.directory_isolation_path)
if os.path.exists(self.project_dir):
output.debug("Copying directory tree from {} to {} for working directory isolation".format(self.project_dir,
self.directory_isolation_path))
copy_tree(self.project_dir, self.directory_isolation_path, preserve_symlinks=True)
self.prepare_env()
self.prepare_inventory()
self.prepare_command()
if self.execution_mode == ExecutionMode.ANSIBLE_PLAYBOOK and self.playbook is None:
raise ConfigurationError("Runner playbook required when running ansible-playbook")
elif self.execution_mode == ExecutionMode.ANSIBLE and self.module is None:
raise ConfigurationError("Runner module required when running ansible")
elif self.execution_mode == ExecutionMode.CLI_EXECENV and self.cmdline_args is None:
raise ConfigurationError("Runner requires arguments to pass to ansible, try '-h' for ansible help output")
elif self.execution_mode == ExecutionMode.NONE:
raise ConfigurationError("No executable for runner to run")
# write the SSH key data into a fifo read by ssh-agent
if self.ssh_key_data:
self.ssh_key_path = os.path.join(self.artifact_dir, 'ssh_key_data')
open_fifo_write(self.ssh_key_path, self.ssh_key_data)
self.command = self.wrap_args_with_ssh_agent(self.command, self.ssh_key_path)
# Use local callback directory
if not self.containerized:
callback_dir = self.env.get('AWX_LIB_DIRECTORY', os.getenv('AWX_LIB_DIRECTORY'))
if callback_dir is None:
callback_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], "callbacks")
python_path = self.env.get('PYTHONPATH', os.getenv('PYTHONPATH', ''))
self.env['PYTHONPATH'] = ':'.join([python_path, callback_dir])
if python_path and not python_path.endswith(':'):
python_path += ':'
self.env['ANSIBLE_CALLBACK_PLUGINS'] = ':'.join(filter(None,(self.env.get('ANSIBLE_CALLBACK_PLUGINS'), callback_dir)))
if 'AD_HOC_COMMAND_ID' in self.env:
self.env['ANSIBLE_STDOUT_CALLBACK'] = 'minimal'
else:
self.env['ANSIBLE_STDOUT_CALLBACK'] = 'awx_display'
self.env['ANSIBLE_RETRY_FILES_ENABLED'] = 'False'
if 'ANSIBLE_HOST_KEY_CHECKING' not in self.env:
self.env['ANSIBLE_HOST_KEY_CHECKING'] = 'False'
if not self.containerized:
self.env['AWX_ISOLATED_DATA_DIR'] = self.artifact_dir
if self.resource_profiling:
callback_whitelist = os.environ.get('ANSIBLE_CALLBACK_WHITELIST', '').strip()
self.env['ANSIBLE_CALLBACK_WHITELIST'] = ','.join(filter(None, [callback_whitelist, 'cgroup_perf_recap']))
self.env['CGROUP_CONTROL_GROUP'] = '{}/{}'.format(self.resource_profiling_base_cgroup, self.ident)
if self.resource_profiling_results_dir:
cgroup_output_dir = self.resource_profiling_results_dir
else:
cgroup_output_dir = os.path.normpath(os.path.join(self.private_data_dir, 'profiling_data'))
# Create results directory if it does not exist
if not os.path.isdir(cgroup_output_dir):
os.mkdir(cgroup_output_dir, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
self.env['CGROUP_OUTPUT_DIR'] = cgroup_output_dir
self.env['CGROUP_OUTPUT_FORMAT'] = 'json'
self.env['CGROUP_CPU_POLL_INTERVAL'] = str(self.resource_profiling_cpu_poll_interval)
self.env['CGROUP_MEMORY_POLL_INTERVAL'] = str(self.resource_profiling_memory_poll_interval)
self.env['CGROUP_PID_POLL_INTERVAL'] = str(self.resource_profiling_pid_poll_interval)
self.env['CGROUP_FILE_PER_TASK'] = 'True'
self.env['CGROUP_WRITE_FILES'] = 'True'
self.env['CGROUP_DISPLAY_RECAP'] = 'False'
if self.roles_path:
if isinstance(self.roles_path, list):
self.env['ANSIBLE_ROLES_PATH'] = ':'.join(self.roles_path)
else:
self.env['ANSIBLE_ROLES_PATH'] = self.roles_path
if self.sandboxed:
debug('sandbox enabled')
self.command = self.wrap_args_for_sandbox(self.command)
else:
debug('sandbox disabled')
if self.resource_profiling and self.execution_mode == ExecutionMode.ANSIBLE_PLAYBOOK:
self.command = self.wrap_args_with_cgexec(self.command)
if self.fact_cache_type == 'jsonfile':
self.env['ANSIBLE_CACHE_PLUGIN'] = 'jsonfile'
if not self.containerized:
self.env['ANSIBLE_CACHE_PLUGIN_CONNECTION'] = self.fact_cache
self.env["RUNNER_OMIT_EVENTS"] = str(self.omit_event_data)
self.env["RUNNER_ONLY_FAILED_EVENTS"] = str(self.only_failed_event_data)
if self.containerized:
debug('containerization enabled')
self.command = self.wrap_args_for_containerization(self.command)
else:
debug('containerization disabled')
debug('env:')
for k,v in sorted(self.env.items()):
debug(f' {k}: {v}')
if hasattr(self, 'command') and isinstance(self.command, list):
debug(f"command: {' '.join(self.command)}")
def prepare_inventory(self):
"""
Prepares the inventory default under ``private_data_dir`` if it's not overridden by the constructor.
"""
if self.containerized:
self.inventory = '/runner/inventory/hosts'
return
if self.inventory is None:
if os.path.exists(os.path.join(self.private_data_dir, "inventory")):
self.inventory = os.path.join(self.private_data_dir, "inventory")
def prepare_env(self):
"""
Manages reading environment metadata files under ``private_data_dir`` and merging/updating
with existing values so the :py:class:`ansible_runner.runner.Runner` object can read and use them easily
"""
try:
passwords = self.loader.load_file('env/passwords', Mapping)
self.expect_passwords = {
re.compile(pattern, re.M): password
for pattern, password in iteritems(passwords)
}
except ConfigurationError:
output.debug('Not loading passwords')
self.expect_passwords = dict()
self.expect_passwords[pexpect.TIMEOUT] = None
self.expect_passwords[pexpect.EOF] = None
try:
self.settings = self.loader.load_file('env/settings', Mapping)
except ConfigurationError:
output.debug("Not loading settings")
self.settings = dict()
self.process_isolation = self.settings.get('process_isolation', self.process_isolation)
self.process_isolation_executable = self.settings.get('process_isolation_executable', self.process_isolation_executable)
if self.containerized:
self.container_name = "ansible_runner_{}".format(sanitize_container_name(self.ident))
self.env = {}
# Special flags to convey info to entrypoint or process in container
self.env['LAUNCHED_BY_RUNNER'] = '1'
artifact_dir = os.path.join("/runner/artifacts", "{}".format(self.ident))
self.env['AWX_ISOLATED_DATA_DIR'] = artifact_dir
if self.fact_cache_type == 'jsonfile':
self.env['ANSIBLE_CACHE_PLUGIN_CONNECTION'] = os.path.join(artifact_dir, 'fact_cache')
else:
# seed env with existing shell env
self.env = os.environ.copy()
if self.envvars and isinstance(self.envvars, dict):
self.env.update(self.envvars)
try:
envvars = self.loader.load_file('env/envvars', Mapping)
if envvars:
self.env.update({str(k):str(v) for k, v in envvars.items()})
except ConfigurationError:
output.debug("Not loading environment vars")
# Still need to pass default environment to pexpect
try:
if self.ssh_key_data is None:
self.ssh_key_data = self.loader.load_file('env/ssh_key', string_types)
except ConfigurationError:
output.debug("Not loading ssh key")
self.ssh_key_data = None
self.idle_timeout = self.settings.get('idle_timeout', None)
self.job_timeout = self.settings.get('job_timeout', None)
self.pexpect_timeout = self.settings.get('pexpect_timeout', 5)
self.process_isolation_path = self.settings.get('process_isolation_path', self.process_isolation_path)
self.process_isolation_hide_paths = self.settings.get('process_isolation_hide_paths', self.process_isolation_hide_paths)
self.process_isolation_show_paths = self.settings.get('process_isolation_show_paths', self.process_isolation_show_paths)
self.process_isolation_ro_paths = self.settings.get('process_isolation_ro_paths', self.process_isolation_ro_paths)
self.directory_isolation_cleanup = bool(self.settings.get('directory_isolation_cleanup', True))
self.container_image = self.settings.get('container_image', self.container_image)
self.container_volume_mounts = self.settings.get('container_volume_mounts', self.container_volume_mounts)
self.container_options = self.settings.get('container_options', self.container_options)
self.resource_profiling = self.settings.get('resource_profiling', self.resource_profiling)
self.resource_profiling_base_cgroup = self.settings.get('resource_profiling_base_cgroup', self.resource_profiling_base_cgroup)
self.resource_profiling_cpu_poll_interval = self.settings.get('resource_profiling_cpu_poll_interval', self.resource_profiling_cpu_poll_interval)
self.resource_profiling_memory_poll_interval = self.settings.get('resource_profiling_memory_poll_interval',
self.resource_profiling_memory_poll_interval)
self.resource_profiling_pid_poll_interval = self.settings.get('resource_profiling_pid_poll_interval', self.resource_profiling_pid_poll_interval)
self.resource_profiling_results_dir = self.settings.get('resource_profiling_results_dir', self.resource_profiling_results_dir)
self.pexpect_use_poll = self.settings.get('pexpect_use_poll', True)
self.suppress_ansible_output = self.settings.get('suppress_ansible_output', self.quiet)
if 'AD_HOC_COMMAND_ID' in self.env or not os.path.exists(self.project_dir):
self.cwd = self.private_data_dir
else:
if self.directory_isolation_path is not None:
self.cwd = self.directory_isolation_path
else:
self.cwd = self.project_dir
if 'fact_cache' in self.settings:
if 'fact_cache_type' in self.settings:
if self.settings['fact_cache_type'] == 'jsonfile':
self.fact_cache = os.path.join(self.artifact_dir, self.settings['fact_cache'])
else:
self.fact_cache = os.path.join(self.artifact_dir, self.settings['fact_cache'])
def prepare_command(self):
"""
Determines if the literal ``ansible`` or ``ansible-playbook`` commands are given
and if not calls :py:meth:`ansible_runner.runner_config.RunnerConfig.generate_ansible_command`
"""
if not self.cli_execenv_cmd:
try:
cmdline_args = self.loader.load_file('args', string_types, encoding=None)
if six.PY2 and isinstance(cmdline_args, text_type):
cmdline_args = cmdline_args.encode('utf-8')
self.command = shlex.split(cmdline_args)
self.execution_mode = ExecutionMode.RAW
except ConfigurationError:
self.command = self.generate_ansible_command()
else:
if self.cli_execenv_cmd:
if self.cli_execenv_cmd == 'adhoc':
self.command = ['ansible'] + self.cmdline_args
elif self.cli_execenv_cmd == 'playbook':
self.command = ['ansible-playbook'] + self.cmdline_args
self.execution_mode = ExecutionMode.CLI_EXECENV
def generate_ansible_command(self):
"""
Given that the ``RunnerConfig`` preparation methods have been run to gather the inputs this method
will generate the ``ansible`` or ``ansible-playbook`` command that will be used by the
:py:class:`ansible_runner.runner.Runner` object to start the process
"""
# FIXME - this never happens because the conditional in prepare_command
# "branches around it" and I need to figure out if that's the
# correct course of action or not.
if self.cli_execenv_cmd:
if self.cli_execenv_cmd == 'adhoc':
base_command = 'ansible'
elif self.cli_execenv_cmd == 'playbook':
base_command = 'ansible-playbook'
self.execution_mode = ExecutionMode.CLI_EXECENV
elif self.binary is not None:
base_command = self.binary
self.execution_mode = ExecutionMode.RAW
elif self.module is not None:
base_command = 'ansible'
self.execution_mode = ExecutionMode.ANSIBLE
else:
base_command = 'ansible-playbook'
self.execution_mode = ExecutionMode.ANSIBLE_PLAYBOOK
exec_list = [base_command]
if self.cli_execenv_cmd:
# Provide dummy data for Tower/AWX vars so that playbooks won't
# fail with undefined var errors
awx_tower_vars = {
'awx_job_id': 1,
'tower_job_id': 1,
'awx_job_launch_type': 'workflow',
'tower_job_launch_type': 'workflow',
'awx_workflow_job_name': 'workflow-job',
'tower_workflow_job_name': 'workflow-job',
'awx_workflow_job_id': 1,
'tower_workflow_job_id': 1,
'awx_parent_job_schedule_id': 1,
'tower_parent_job_schedule_id': 1,
'awx_parent_job_schedule_name': 'job-schedule',
'tower_parent_job_schedule_name': 'job-schedule',
}
for k,v in awx_tower_vars.items():
exec_list.append('-e')
exec_list.append('"{}={}"'.format(k, v))
try:
if self.cmdline_args:
cmdline_args = self.cmdline_args
else:
cmdline_args = self.loader.load_file('env/cmdline', string_types, encoding=None)
if six.PY2 and isinstance(cmdline_args, text_type):
cmdline_args = cmdline_args.encode('utf-8')
args = shlex.split(cmdline_args)
exec_list.extend(args)
except ConfigurationError:
pass
if self.inventory is None:
pass
elif isinstance(self.inventory, list):
for i in self.inventory:
exec_list.append("-i")
exec_list.append(i)
else:
exec_list.append("-i")
exec_list.append(self.inventory)
if self.limit is not None:
exec_list.append("--limit")
exec_list.append(self.limit)
if self.loader.isfile('env/extravars'):
if self.containerized:
extravars_path = '/runner/env/extravars'
else:
extravars_path = self.loader.abspath('env/extravars')
exec_list.extend(['-e', '@{}'.format(extravars_path)])
if self.extra_vars:
if isinstance(self.extra_vars, dict) and self.extra_vars:
extra_vars_list = []
for k in self.extra_vars:
extra_vars_list.append("\"{}\":{}".format(k, json.dumps(self.extra_vars[k])))
exec_list.extend(
[
'-e',
'{%s}' % ','.join(extra_vars_list)
]
)
elif self.loader.isfile(self.extra_vars):
exec_list.extend(['-e', '@{}'.format(self.loader.abspath(self.extra_vars))])
if self.verbosity:
v = 'v' * self.verbosity
exec_list.append('-{}'.format(v))
if self.tags:
exec_list.extend(['--tags', '{}'.format(self.tags)])
if self.skip_tags:
exec_list.extend(['--skip-tags', '{}'.format(self.skip_tags)])
if self.forks:
exec_list.extend(['--forks', '{}'.format(self.forks)])
# Other parameters
if self.execution_mode == ExecutionMode.ANSIBLE_PLAYBOOK:
exec_list.append(self.playbook)
elif self.execution_mode == ExecutionMode.ANSIBLE:
exec_list.append("-m")
exec_list.append(self.module)
if self.module_args is not None:
exec_list.append("-a")
exec_list.append(self.module_args)
if self.host_pattern is not None:
exec_list.append(self.host_pattern)
return exec_list
def build_process_isolation_temp_dir(self):
'''
Create a temporary directory for process isolation to use.
'''
path = tempfile.mkdtemp(prefix='ansible_runner_pi_', dir=self.process_isolation_path)
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
return path
def wrap_args_with_cgexec(self, args):
'''
Wrap existing command line with cgexec in order to profile resource usage
'''
new_args = ['cgexec', '--sticky', '-g', 'cpuacct,memory,pids:{}/{}'.format(self.resource_profiling_base_cgroup, self.ident)]
new_args.extend(args)
return new_args
def wrap_args_for_sandbox(self, args):
'''
Wrap existing command line with bwrap to restrict access to:
- self.process_isolation_path (generally, /tmp) (except for own /tmp files)
'''
cwd = os.path.realpath(self.cwd)
self.process_isolation_path_actual = self.build_process_isolation_temp_dir()
new_args = [self.process_isolation_executable or 'bwrap', '--die-with-parent', '--unshare-pid', '--dev-bind', '/', '/', '--proc', '/proc']
for path in sorted(set(self.process_isolation_hide_paths or [])):
if not os.path.exists(path):
logger.debug('hide path not found: {0}'.format(path))
continue
path = os.path.realpath(path)
if os.path.isdir(path):
new_path = tempfile.mkdtemp(dir=self.process_isolation_path_actual)
os.chmod(new_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
else:
handle, new_path = tempfile.mkstemp(dir=self.process_isolation_path_actual)
os.close(handle)
os.chmod(new_path, stat.S_IRUSR | stat.S_IWUSR)
new_args.extend(['--bind', '{0}'.format(new_path), '{0}'.format(path)])
if self.private_data_dir:
show_paths = [self.private_data_dir]
else:
show_paths = [cwd]
for path in sorted(set(self.process_isolation_ro_paths or [])):
if not os.path.exists(path):
logger.debug('read-only path not found: {0}'.format(path))
continue
path = os.path.realpath(path)
new_args.extend(['--ro-bind', '{0}'.format(path), '{0}'.format(path)])
show_paths.extend(self.process_isolation_show_paths or [])
for path in sorted(set(show_paths)):
if not os.path.exists(path):
logger.debug('show path not found: {0}'.format(path))
continue
path = os.path.realpath(path)
new_args.extend(['--bind', '{0}'.format(path), '{0}'.format(path)])
if self.execution_mode == ExecutionMode.ANSIBLE_PLAYBOOK:
# playbook runs should cwd to the SCM checkout dir
if self.directory_isolation_path is not None:
new_args.extend(['--chdir', os.path.realpath(self.directory_isolation_path)])
else:
new_args.extend(['--chdir', os.path.realpath(self.project_dir)])
elif self.execution_mode == ExecutionMode.ANSIBLE:
# ad-hoc runs should cwd to the root of the private data dir
new_args.extend(['--chdir', os.path.realpath(self.private_data_dir)])
new_args.extend(args)
return new_args
def wrap_args_for_containerization(self, args):
new_args = [self.process_isolation_executable]
new_args.extend(['run', '--rm', '--tty', '--interactive'])
container_workdir = "/runner/project"
new_args.extend(["--workdir", container_workdir])
self.cwd = container_workdir
def _ensure_path_safe_to_mount(path):
if path in ('/home', '/usr'):
raise ConfigurationError("When using containerized execution, cannot mount /home or /usr")
_ensure_path_safe_to_mount(self.private_data_dir)
def _parse_cli_execenv_cmd_playbook_args():
# Determine all inventory file paths, accounting for the possibility of multiple
# inventory files provided
_inventory_paths = []
_playbook = ""
_book_keeping_copy = self.cmdline_args.copy()
for arg in self.cmdline_args:
if arg == '-i':
_book_keeping_copy_inventory_index = _book_keeping_copy.index('-i')
_inventory_paths.append(self.cmdline_args[_book_keeping_copy_inventory_index + 1])
_book_keeping_copy.pop(_book_keeping_copy_inventory_index)
_book_keeping_copy.pop(_book_keeping_copy_inventory_index)
if len(_book_keeping_copy) == 1:
# it's probably safe to assume this is the playbook
_playbook = _book_keeping_copy[0]
elif _book_keeping_copy[0][0] != '-':
# this should be the playbook, it's the only "naked" arg
_playbook = _book_keeping_copy[0]
else:
# parse everything beyond the first arg because we checked that
# in the previous case already
for arg in _book_keeping_copy[1:]:
if arg[0] == '-':
continue
elif _book_keeping_copy[(_book_keeping_copy.index(arg) - 1)][0] != '-':
_playbook = arg
break
return (_playbook, _inventory_paths)
if self.cli_execenv_cmd:
_parsed_playbook_path, _parsed_inventory_paths = _parse_cli_execenv_cmd_playbook_args()
if self.cli_execenv_cmd == 'playbook':
playbook_file_path = _parsed_playbook_path
_ensure_path_safe_to_mount(playbook_file_path)
if os.path.isabs(playbook_file_path) and (os.path.dirname(playbook_file_path) != '/'):
new_args.extend([
"-v", "{}:{}".format(
os.path.dirname(playbook_file_path),
os.path.dirname(playbook_file_path),
)
])
else:
new_args.extend([
"-v", "{}:/runner/project/{}".format(
os.path.dirname(os.path.abspath(playbook_file_path)),
os.path.dirname(playbook_file_path),
)
])
# volume mount inventory into the exec env container if provided at cli
if '-i' in self.cmdline_args:
inventory_file_paths = _parsed_inventory_paths
inventory_playbook_share_parent = False
for inventory_file_path in inventory_file_paths:
_ensure_path_safe_to_mount(inventory_file_path)
if self.cli_execenv_cmd == 'playbook':
if os.path.dirname(os.path.abspath(inventory_file_path)) == \
os.path.dirname(os.path.abspath(playbook_file_path)):
inventory_playbook_share_parent = True
if not inventory_file_path.endswith(',') and not inventory_playbook_share_parent:
if os.path.isabs(inventory_file_path) and (os.path.dirname(inventory_file_path) != '/'):
new_args.extend([
"-v", "{}:{}".format(
os.path.dirname(inventory_file_path),
os.path.dirname(inventory_file_path),
)
])
else:
new_args.extend([
"-v", "{}:/runner/project/{}".format(
os.path.dirname(os.path.abspath(inventory_file_path)),
os.path.dirname(inventory_file_path),
)
])
# Handle automounts
cli_automounts = [
{
'ENVS': ['SSH_AUTH_SOCK'],
'PATHS': [
{
'src': '{}/.ssh/'.format(os.environ['HOME']),
'dest': '/home/runner/.ssh/'
},
{
'src': '/etc/ssh/ssh_known_hosts',
'dest': '/etc/ssh/ssh_known_hosts'
}
]
},
{
"ENVS": ['K8S_AUTH_KUBECONFIG'],
"PATHS": [
{
'src': '{}/.kube/'.format(os.environ['HOME']),
'dest': '/home/runner/.kube/'
},
]
},
{
"ENVS": [
'AWS_URL', 'EC2_URL', 'AWS_ACCESS_KEY_ID', 'AWS_ACCESS_KEY',
'EC2_ACCESS_KEY', 'AWS_SECRET_ACCESS_KEY', 'AWS_SECRET_KEY', 'EC2_SECRET_KEY',
'AWS_SECURITY_TOKEN', 'EC2_SECURITY_TOKEN', 'AWS_REGION', 'EC2_REGION'
],
"PATHS": [
{
'src': '{}/.boto/'.format(os.environ['HOME']),
'dest': '/home/runner/.boto/'
},
]
},
{
"ENVS": [
'AZURE_SUBSCRIPTION_ID', 'AZURE_CLIENT_ID', 'AZURE_SECRET', 'AZURE_TENANT',
'AZURE_AD_USER', 'AZURE_PASSWORD'
],
"PATHS": [
{
'src': '{}/.azure/'.format(os.environ['HOME']),
'dest': '/home/runner/.azure/'
},
]
},
{
"ENVS": [
'gcp_service_account_file', 'GCP_SERVICE_ACCOUNT_FILE', 'GCP_SERVICE_ACCOUNT_CONTENTS',
'GCP_SERVICE_ACCOUNT_EMAIL', 'GCP_AUTH_KIND', 'GCP_SCOPES'
],
"PATHS": [
{
'src': '{}/.gcp/'.format(os.environ['HOME']),
'dest': '/home/runner/.gcp/'
},
]
}
]
for cli_automount in cli_automounts:
for env in cli_automount['ENVS']:
if env in os.environ:
dest_path = os.environ[env]
if os.path.exists(os.environ[env]):
if os.environ[env].startswith(os.environ['HOME']):
dest_path = '/home/runner/{}'.format(os.environ[env].lstrip(os.environ['HOME']))
elif os.environ[env].startswith('~'):
dest_path = '/home/runner/{}'.format(os.environ[env].lstrip('~/'))
else:
dest_path = os.environ[env]
new_args.extend(["-v", "{}:{}".format(os.environ[env], dest_path)])
new_args.extend(["-e", "{}={}".format(env, dest_path)])
for paths in cli_automount['PATHS']:
if os.path.exists(paths['src']):
new_args.extend(["-v", "{}:{}".format(paths['src'], paths['dest'])])
if 'podman' in self.process_isolation_executable:
# container namespace stuff
new_args.extend(["--group-add=root"])
new_args.extend(["--userns=keep-id"])
new_args.extend(["--ipc=host"])
# the playbook / adhoc cases (cli_execenv_cmd) are handled separately
# because they have pre-existing mounts already in new_args
if self.cli_execenv_cmd:
# Relative paths are mounted relative to /runner/project
for subdir in ('project', 'artifacts'):
subdir_path = os.path.join(self.private_data_dir, subdir)
if not os.path.exists(subdir_path):
os.mkdir(subdir_path, 0o700)
# playbook / adhoc commands need artifacts mounted to output data
new_args.extend(["-v", "{}/artifacts:/runner/artifacts:Z".format(self.private_data_dir)])
else:
subdir_path = os.path.join(self.private_data_dir, 'artifacts')
if not os.path.exists(subdir_path):
os.mkdir(subdir_path, 0o700)
# Mount the entire private_data_dir
# custom show paths inside private_data_dir do not make sense
new_args.extend(["-v", "{}:/runner:Z".format(self.private_data_dir)])
container_volume_mounts = self.container_volume_mounts
if container_volume_mounts:
for mapping in container_volume_mounts:
host_path, container_path = mapping.split(':', 1)
_ensure_path_safe_to_mount(host_path)
new_args.extend(["-v", "{}:{}".format(host_path, container_path)])
# Reference the file with list of keys to pass into container
# this file will be written in ansible_runner.runner
env_file_host = os.path.join(self.artifact_dir, 'env.list')
new_args.extend(['--env-file', env_file_host])
if 'podman' in self.process_isolation_executable:
# docker doesnt support this option
new_args.extend(['--quiet'])
if 'docker' in self.process_isolation_executable:
new_args.extend([f'--user={os.getuid()}'])
new_args.extend(['--name', self.container_name])
if self.container_options:
new_args.extend(self.container_options)
new_args.extend([self.container_image])
new_args.extend(args)
debug(f"container engine invocation: {' '.join(new_args)}")
return new_args
def wrap_args_with_ssh_agent(self, args, ssh_key_path, ssh_auth_sock=None, silence_ssh_add=False):
"""
Given an existing command line and parameterization this will return the same command line wrapped with the
necessary calls to ``ssh-agent``
"""
if self.containerized:
artifact_dir = os.path.join("/runner/artifacts", "{}".format(self.ident))
ssh_key_path = os.path.join(artifact_dir, "ssh_key_data")
if ssh_key_path:
ssh_add_command = args2cmdline('ssh-add', ssh_key_path)
if silence_ssh_add:
ssh_add_command = ' '.join([ssh_add_command, '2>/dev/null'])
ssh_key_cleanup_command = 'rm -f {}'.format(ssh_key_path)
# The trap ensures the fifo is cleaned up even if the call to ssh-add fails.
# This prevents getting into certain scenarios where subsequent reads will
# hang forever.
cmd = ' && '.join([args2cmdline('trap', ssh_key_cleanup_command, 'EXIT'),
ssh_add_command,
ssh_key_cleanup_command,
args2cmdline(*args)])
args = ['ssh-agent']
if ssh_auth_sock:
args.extend(['-a', ssh_auth_sock])
args.extend(['sh', '-c', cmd])
return args
+258
View File
@@ -0,0 +1,258 @@
import codecs
import json
import os
import stat
import sys
import tempfile
import uuid
import traceback
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
import ansible_runner
from ansible_runner.exceptions import ConfigurationError
from ansible_runner.loader import ArtifactLoader
import ansible_runner.plugins
from ansible_runner import utils
class UUIDEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, uuid.UUID):
return obj.hex
return json.JSONEncoder.default(self, obj)
class MockConfig(object):
def __init__(self, settings):
self.settings = settings
class Transmitter(object):
def __init__(self, _output=None, **kwargs):
if _output is None:
_output = sys.stdout.buffer
self._output = _output
self.private_data_dir = os.path.abspath(kwargs.pop('private_data_dir'))
self.only_transmit_kwargs = kwargs.pop('only_transmit_kwargs', False)
self.kwargs = kwargs
self.status = "unstarted"
self.rc = None
def run(self):
self._output.write(
json.dumps({'kwargs': self.kwargs}, cls=UUIDEncoder).encode('utf-8')
)
self._output.write(b'\n')
self._output.flush()
if not self.only_transmit_kwargs:
self._output.write(utils.stream_dir(self.private_data_dir))
self._output.write(json.dumps({'eof': True}).encode('utf-8'))
self._output.write(b'\n')
self._output.flush()
return self.status, self.rc
class Worker(object):
def __init__(self, _input=None, _output=None, **kwargs):
if _input is None:
_input = sys.stdin.buffer
if _output is None:
_output = sys.stdout.buffer
self._input = _input
self._output = _output
self.kwargs = kwargs
self.job_kwargs = None
private_data_dir = kwargs.get('private_data_dir')
if private_data_dir is None:
private_data_dir = tempfile.TemporaryDirectory().name
self.private_data_dir = private_data_dir
self.status = "unstarted"
self.rc = None
def update_paths(self, kwargs):
if kwargs.get('envvars'):
if 'ANSIBLE_ROLES_PATH' in kwargs['envvars']:
roles_path = kwargs['envvars']['ANSIBLE_ROLES_PATH']
roles_dir = os.path.join(self.private_data_dir, 'roles')
kwargs['envvars']['ANSIBLE_ROLES_PATH'] = os.path.join(roles_dir, roles_path)
if kwargs.get('inventory'):
kwargs['inventory'] = os.path.join(self.private_data_dir, kwargs['inventory'])
return kwargs
def run(self):
while True:
try:
line = self._input.readline()
data = json.loads(line)
except (json.decoder.JSONDecodeError, IOError):
self.status_handler({'status': 'error', 'job_explanation': 'Failed to JSON parse a line from transmit stream.'}, None)
self.finished_callback(None) # send eof line
return self.status, self.rc
if 'kwargs' in data:
self.job_kwargs = self.update_paths(data['kwargs'])
elif 'zipfile' in data:
zip_data = self._input.read(data['zipfile'])
try:
utils.unstream_dir(zip_data, self.private_data_dir)
except Exception:
self.status_handler({
'status': 'error',
'job_explanation': 'Failed to extract private data directory on worker.',
'result_traceback': traceback.format_exc()
}, None)
self.finished_callback(None) # send eof line
return self.status, self.rc
elif 'eof' in data:
break
self.kwargs.update(self.job_kwargs)
self.kwargs['quiet'] = True
self.kwargs['suppress_ansible_output'] = True
self.kwargs['private_data_dir'] = self.private_data_dir
self.kwargs['status_handler'] = self.status_handler
self.kwargs['event_handler'] = self.event_handler
self.kwargs['artifacts_handler'] = self.artifacts_handler
self.kwargs['finished_callback'] = self.finished_callback
r = ansible_runner.interface.run(**self.kwargs)
self.status, self.rc = r.status, r.rc
# FIXME: do cleanup on the tempdir
return self.status, self.rc
def status_handler(self, status_data, runner_config):
self.status = status_data['status']
self._output.write(json.dumps(status_data).encode('utf-8'))
self._output.write(b'\n')
self._output.flush()
def event_handler(self, event_data):
self._output.write(json.dumps(event_data).encode('utf-8'))
self._output.write(b'\n')
self._output.flush()
def artifacts_handler(self, artifact_dir):
self._output.write(utils.stream_dir(artifact_dir))
self._output.flush()
def finished_callback(self, runner_obj):
self._output.write(json.dumps({'eof': True}).encode('utf-8'))
self._output.write(b'\n')
self._output.flush()
class Processor(object):
def __init__(self, _input=None, status_handler=None, event_handler=None,
artifacts_handler=None, cancel_callback=None, finished_callback=None, **kwargs):
if _input is None:
_input = sys.stdin.buffer
self._input = _input
self.quiet = kwargs.get('quiet')
private_data_dir = kwargs.get('private_data_dir')
if private_data_dir is None:
private_data_dir = tempfile.TemporaryDirectory().name
self.private_data_dir = private_data_dir
self._loader = ArtifactLoader(self.private_data_dir)
settings = kwargs.get('settings')
if settings is None:
try:
settings = self._loader.load_file('env/settings', Mapping)
except ConfigurationError:
settings = {}
self.config = MockConfig(settings)
artifact_dir = kwargs.get('artifact_dir')
self.artifact_dir = os.path.abspath(
artifact_dir or os.path.join(self.private_data_dir, 'artifacts'))
self.status_handler = status_handler
self.event_handler = event_handler
self.artifacts_handler = artifacts_handler
self.cancel_callback = cancel_callback # FIXME: unused
self.finished_callback = finished_callback
self.status = "unstarted"
self.rc = None
def status_callback(self, status_data):
self.status = status_data['status']
if self.status == 'starting':
self.config.command = status_data.get('command')
self.config.env = status_data.get('env')
self.config.cwd = status_data.get('cwd')
for plugin in ansible_runner.plugins:
ansible_runner.plugins[plugin].status_handler(self.config, status_data)
if self.status_handler is not None:
self.status_handler(status_data, runner_config=self.config)
def event_callback(self, event_data):
full_filename = os.path.join(self.artifact_dir,
'job_events',
'{}-{}.json'.format(event_data['counter'],
event_data['uuid']))
if not self.quiet and 'stdout' in event_data:
print(event_data['stdout'])
if self.event_handler is not None:
should_write = self.event_handler(event_data)
else:
should_write = True
for plugin in ansible_runner.plugins:
ansible_runner.plugins[plugin].event_handler(self.config, event_data)
if should_write:
with codecs.open(full_filename, 'w', encoding='utf-8') as write_file:
os.chmod(full_filename, stat.S_IRUSR | stat.S_IWUSR)
json.dump(event_data, write_file)
def artifacts_callback(self, artifacts_data):
zip_data = self._input.read(artifacts_data['zipfile'])
utils.unstream_dir(zip_data, self.artifact_dir)
if self.artifacts_handler is not None:
self.artifacts_handler(self.artifact_dir)
def run(self):
job_events_path = os.path.join(self.artifact_dir, 'job_events')
if not os.path.exists(job_events_path):
os.makedirs(job_events_path, 0o700, exist_ok=True)
while True:
try:
line = self._input.readline()
data = json.loads(line)
except (json.decoder.JSONDecodeError, IOError):
self.status_callback({'status': 'error', 'job_explanation': 'Failed to JSON parse a line from worker stream.'})
break
if 'status' in data:
self.status_callback(data)
elif 'zipfile' in data:
self.artifacts_callback(data)
elif 'eof' in data:
break
else:
self.event_callback(data)
if self.finished_callback is not None:
self.finished_callback(self)
return self.status, self.rc
+431
View File
@@ -0,0 +1,431 @@
import json
import sys
import re
import os
import stat
import fcntl
import shutil
import hashlib
import tempfile
import subprocess
import base64
import threading
import pipes
import uuid
import codecs
import zipfile
try:
from collections.abc import Iterable, Mapping
except ImportError:
from collections import Iterable, Mapping
from io import BytesIO, StringIO
from six import string_types, PY2, PY3, text_type, binary_type
class Bunch(object):
'''
Collect a bunch of variables together in an object.
This is a slight modification of Alex Martelli's and Doug Hudgeon's Bunch pattern.
'''
def __init__(self, **kwargs):
self.update(**kwargs)
def update(self, **kwargs):
self.__dict__.update(kwargs)
def get(self, key):
return self.__dict__.get(key)
def isplaybook(obj):
'''
Inspects the object and returns if it is a playbook
Args:
obj (object): The object to be inspected by this function
Returns:
boolean: True if the object is a list and False if it is not
'''
return isinstance(obj, Iterable) and (not isinstance(obj, string_types) and not isinstance(obj, Mapping))
def isinventory(obj):
'''
Inspects the object and returns if it is an inventory
Args:
obj (object): The object to be inspected by this function
Returns:
boolean: True if the object is an inventory dict and False if it is not
'''
return isinstance(obj, Mapping) or isinstance(obj, string_types)
def check_isolation_executable_installed(isolation_executable):
'''
Check that process isolation executable (e.g. podman, docker, bwrap) is installed.
'''
cmd = [isolation_executable, '--version']
try:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
proc.communicate()
return bool(proc.returncode == 0)
except (OSError, ValueError) as e:
if isinstance(e, ValueError) or getattr(e, 'errno', 1) != 2: # ENOENT, no such file or directory
raise RuntimeError(f'{isolation_executable} unavailable for unexpected reason.')
return False
def stream_dir(directory):
buf = BytesIO()
with zipfile.ZipFile(buf, 'w', compression=zipfile.ZIP_DEFLATED, allowZip64=True) as archive:
if directory:
for dirpath, dirs, files in os.walk(directory):
relpath = os.path.relpath(dirpath, directory)
if relpath == ".":
relpath = ""
for fname in files:
archive.write(os.path.join(dirpath, fname), arcname=os.path.join(relpath, fname))
archive.close()
payload = base64.b85encode(buf.getvalue())
return b'\n'.join((json.dumps({'zipfile': len(payload)}).encode('utf-8'), payload))
def unstream_dir(data, directory):
# NOTE: caller needs to process exceptions
data = base64.b85decode(data)
buf = BytesIO(data)
with zipfile.ZipFile(buf, 'r') as archive:
# Fancy extraction in order to preserve permissions
# https://www.burgundywall.com/post/preserving-file-perms-with-python-zipfile-module
for info in archive.infolist():
archive.extract(info.filename, path=directory)
out_path = os.path.join(directory, info.filename)
perm = info.external_attr >> 16
os.chmod(out_path, perm)
def dump_artifact(obj, path, filename=None):
'''
Write the artifact to disk at the specified path
Args:
obj (string): The string object to be dumped to disk in the specified
path. The artifact filename will be automatically created
path (string): The full path to the artifacts data directory.
filename (string, optional): The name of file to write the artifact to.
If the filename is not provided, then one will be generated.
Returns:
string: The full path filename for the artifact that was generated
'''
p_sha1 = None
if not os.path.exists(path):
os.makedirs(path, mode=0o700)
else:
p_sha1 = hashlib.sha1()
p_sha1.update(obj.encode(encoding='UTF-8'))
if filename is None:
fd, fn = tempfile.mkstemp(dir=path)
else:
fn = os.path.join(path, filename)
if os.path.exists(fn):
c_sha1 = hashlib.sha1()
with open(fn) as f:
contents = f.read()
c_sha1.update(contents.encode(encoding='UTF-8'))
if not os.path.exists(fn) or p_sha1.hexdigest() != c_sha1.hexdigest():
lock_fp = os.path.join(path, '.artifact_write_lock')
lock_fd = os.open(lock_fp, os.O_RDWR | os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR)
fcntl.lockf(lock_fd, fcntl.LOCK_EX)
try:
with open(fn, 'w') as f:
os.chmod(fn, stat.S_IRUSR)
f.write(str(obj))
finally:
fcntl.lockf(lock_fd, fcntl.LOCK_UN)
os.close(lock_fd)
os.remove(lock_fp)
return fn
def cleanup_artifact_dir(path, num_keep=0):
# 0 disables artifact dir cleanup/rotation
if num_keep < 1:
return
all_paths = sorted([os.path.join(path, p) for p in os.listdir(path)],
key=lambda x: os.path.getmtime(x))
total_remove = len(all_paths) - num_keep
for f in range(total_remove):
shutil.rmtree(all_paths[f])
def dump_artifacts(kwargs):
'''
Introspect the kwargs and dump objects to disk
'''
private_data_dir = kwargs.get('private_data_dir')
if not private_data_dir:
private_data_dir = tempfile.mkdtemp()
kwargs['private_data_dir'] = private_data_dir
if not os.path.exists(private_data_dir):
raise ValueError('private_data_dir path is either invalid or does not exist')
if 'role' in kwargs:
role = {'name': kwargs.pop('role')}
if 'role_vars' in kwargs:
role['vars'] = kwargs.pop('role_vars')
play = [{'hosts': kwargs.pop('hosts', 'all'), 'roles': [role]}]
if kwargs.pop('role_skip_facts', False):
play[0]['gather_facts'] = False
kwargs['playbook'] = play
if 'envvars' not in kwargs:
kwargs['envvars'] = {}
roles_path = kwargs.pop('roles_path', None)
if not roles_path:
roles_path = os.path.join(private_data_dir, 'roles')
else:
roles_path += ':{}'.format(os.path.join(private_data_dir, 'roles'))
kwargs['envvars']['ANSIBLE_ROLES_PATH'] = roles_path
obj = kwargs.get('playbook')
if obj and isplaybook(obj):
path = os.path.join(private_data_dir, 'project')
kwargs['playbook'] = dump_artifact(json.dumps(obj), path, 'main.json')
obj = kwargs.get('inventory')
if obj and isinventory(obj):
path = os.path.join(private_data_dir, 'inventory')
if isinstance(obj, Mapping):
kwargs['inventory'] = dump_artifact(json.dumps(obj), path, 'hosts.json')
elif isinstance(obj, string_types):
if not os.path.exists(obj):
kwargs['inventory'] = dump_artifact(obj, path, 'hosts')
for key in ('envvars', 'extravars', 'passwords', 'settings'):
obj = kwargs.get(key)
if obj and not os.path.exists(os.path.join(private_data_dir, 'env', key)):
path = os.path.join(private_data_dir, 'env')
dump_artifact(json.dumps(obj), path, key)
kwargs.pop(key)
for key in ('ssh_key', 'cmdline'):
obj = kwargs.get(key)
if obj and not os.path.exists(os.path.join(private_data_dir, 'env', key)):
path = os.path.join(private_data_dir, 'env')
dump_artifact(str(kwargs[key]), path, key)
kwargs.pop(key)
def collect_new_events(event_path,old_events):
'''
Collect new events for the 'events' generator property
'''
dir_events = os.listdir(event_path)
dir_events_actual = []
for each_file in dir_events:
if re.match("^[0-9]+-.+json$", each_file):
if '-partial' not in each_file and each_file not in old_events.keys() :
dir_events_actual.append(each_file)
dir_events_actual.sort(key=lambda filenm: int(filenm.split("-", 1)[0]))
for event_file in dir_events_actual:
with codecs.open(os.path.join(event_path, event_file), 'r', encoding='utf-8') as event_file_actual:
try:
event = json.load(event_file_actual)
except ValueError:
break
old_events[event_file] = True
yield event, old_events
class OutputEventFilter(object):
'''
File-like object that looks for encoded job events in stdout data.
'''
EVENT_DATA_RE = re.compile(r'\x1b\[K((?:[A-Za-z0-9+/=]+\x1b\[\d+D)+)\x1b\[K')
def __init__(self, handle, event_callback,
suppress_ansible_output=False, output_json=False):
self._event_callback = event_callback
self._counter = 0
self._start_line = 0
self._handle = handle
self._buffer = StringIO()
self._last_chunk = ''
self._current_event_data = None
self.output_json = output_json
self.suppress_ansible_output = suppress_ansible_output
def flush(self):
self._handle.flush()
def write(self, data):
self._buffer.write(data)
# keep a sliding window of the last chunk written so we can detect
# event tokens and determine if we need to perform a search of the full
# buffer
should_search = '\x1b[K' in (self._last_chunk + data)
self._last_chunk = data
# Only bother searching the buffer if we recently saw a start/end
# token (\x1b[K)
while should_search:
value = self._buffer.getvalue()
match = self.EVENT_DATA_RE.search(value)
if not match:
break
try:
base64_data = re.sub(r'\x1b\[\d+D', '', match.group(1))
event_data = json.loads(base64.b64decode(base64_data).decode('utf-8'))
except ValueError:
event_data = {}
event_data = self._emit_event(value[:match.start()], event_data)
if not self.output_json:
stdout_actual = event_data['stdout'] if 'stdout' in event_data else None
else:
stdout_actual = json.dumps(event_data)
remainder = value[match.end():]
self._buffer = StringIO()
self._buffer.write(remainder)
if stdout_actual and stdout_actual != "{}":
if not self.suppress_ansible_output:
sys.stdout.write(
stdout_actual.encode('utf-8') if PY2 else stdout_actual
)
sys.stdout.write("\n")
sys.stdout.flush()
self._handle.write(stdout_actual + "\n")
self._handle.flush()
self._last_chunk = remainder
else:
# Verbose stdout outside of event data context
if data and '\n' in data and self._current_event_data is None:
# emit events for all complete lines we know about
lines = self._buffer.getvalue().splitlines(True) # keep ends
remainder = None
# if last line is not a complete line, then exclude it
if '\n' not in lines[-1]:
remainder = lines.pop()
# emit all complete lines
for line in lines:
self._emit_event(line)
if not self.suppress_ansible_output:
sys.stdout.write(
line.encode('utf-8') if PY2 else line
)
self._handle.write(line)
self._handle.flush()
self._buffer = StringIO()
# put final partial line back on buffer
if remainder:
self._buffer.write(remainder)
def close(self):
value = self._buffer.getvalue()
if value:
self._emit_event(value)
self._buffer = StringIO()
self._event_callback(dict(event='EOF'))
self._handle.close()
def _emit_event(self, buffered_stdout, next_event_data=None):
next_event_data = next_event_data or {}
if self._current_event_data:
event_data = self._current_event_data
stdout_chunks = [buffered_stdout]
elif buffered_stdout:
event_data = dict(event='verbose')
stdout_chunks = buffered_stdout.splitlines(True)
else:
event_data = dict()
stdout_chunks = []
for stdout_chunk in stdout_chunks:
if event_data.get('event') == 'verbose':
event_data['uuid'] = str(uuid.uuid4())
self._counter += 1
event_data['counter'] = self._counter
event_data['stdout'] = stdout_chunk[:-2] if len(stdout_chunk) > 2 else ""
n_lines = stdout_chunk.count('\n')
event_data['start_line'] = self._start_line
event_data['end_line'] = self._start_line + n_lines
self._start_line += n_lines
if self._event_callback:
self._event_callback(event_data)
if next_event_data.get('uuid', None):
self._current_event_data = next_event_data
else:
self._current_event_data = None
return event_data
def open_fifo_write(path, data):
'''open_fifo_write opens the fifo named pipe in a new thread.
This blocks the thread until an external process (such as ssh-agent)
reads data from the pipe.
'''
os.mkfifo(path, stat.S_IRUSR | stat.S_IWUSR)
threading.Thread(target=lambda p, d: open(p, 'wb').write(d),
args=(path, data)).start()
def args2cmdline(*args):
return ' '.join([pipes.quote(a) for a in args])
def ensure_str(s, encoding='utf-8', errors='strict'):
"""
Copied from six==1.12
Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if not isinstance(s, (text_type, binary_type)):
raise TypeError("not expecting type '%s'" % type(s))
if PY2 and isinstance(s, text_type):
s = s.encode(encoding, errors)
elif PY3 and isinstance(s, binary_type):
s = s.decode(encoding, errors)
return s
def sanitize_container_name(original_name):
"""
Docker and podman will only accept certain characters in container names
This takes a given name from user-specified values and replaces the
invalid characters so it can be used in docker/podman CLI commands
"""
return re.sub('[^a-zA-Z0-9_-]', '_', text_type(original_name))