| 1 |
# shebang placeholder |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import datetime |
| 6 |
|
| 7 |
# For test-module.py script to tell this is a ANSIBALLZ_WRAPPER |
| 8 |
_ANSIBALLZ_WRAPPER = True |
| 9 |
|
| 10 |
# This code is part of Ansible, but is an independent component. |
| 11 |
# The code in this particular templatable string, and this templatable string |
| 12 |
# only, is BSD licensed. Modules which end up using this snippet, which is |
| 13 |
# dynamically combined together by Ansible still belong to the author of the |
| 14 |
# module, and they may assign their own license to the complete work. |
| 15 |
# |
| 16 |
# Copyright (c), James Cammarata, 2016 |
| 17 |
# Copyright (c), Toshio Kuratomi, 2016 |
| 18 |
# |
| 19 |
# Redistribution and use in source and binary forms, with or without modification, |
| 20 |
# are permitted provided that the following conditions are met: |
| 21 |
# |
| 22 |
# * Redistributions of source code must retain the above copyright |
| 23 |
# notice, this list of conditions and the following disclaimer. |
| 24 |
# * Redistributions in binary form must reproduce the above copyright notice, |
| 25 |
# this list of conditions and the following disclaimer in the documentation |
| 26 |
# and/or other materials provided with the distribution. |
| 27 |
# |
| 28 |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
| 29 |
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
| 30 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
| 31 |
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
| 32 |
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 33 |
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 34 |
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| 35 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE |
| 36 |
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 37 |
|
| 38 |
|
| 39 |
def _ansiballz_main( |
| 40 |
zip_data: str, |
| 41 |
ansible_module: str, |
| 42 |
module_fqn: str, |
| 43 |
params: str, |
| 44 |
profile: str, |
| 45 |
date_time: datetime.datetime, |
| 46 |
extensions: dict[str, dict[str, object]], |
| 47 |
secrets: frozenset[str], |
| 48 |
rlimit_nofile: int, |
| 49 |
) -> None: |
| 50 |
import os |
| 51 |
import os.path |
| 52 |
|
| 53 |
# Access to the working directory is required by Python when using pipelining, as well as for the coverage module. |
| 54 |
# Some platforms, such as macOS, may not allow querying the working directory when using become to drop privileges. |
| 55 |
try: |
| 56 |
os.getcwd() |
| 57 |
except OSError: |
| 58 |
try: |
| 59 |
os.chdir(os.path.expanduser('~')) |
| 60 |
except OSError: |
| 61 |
os.chdir('/') |
| 62 |
|
| 63 |
if rlimit_nofile: |
| 64 |
import resource |
| 65 |
|
| 66 |
existing_soft, existing_hard = resource.getrlimit(resource.RLIMIT_NOFILE) |
| 67 |
|
| 68 |
# adjust soft limit subject to existing hard limit |
| 69 |
requested_soft = min(existing_hard, rlimit_nofile) |
| 70 |
|
| 71 |
if requested_soft != existing_soft: |
| 72 |
try: |
| 73 |
resource.setrlimit(resource.RLIMIT_NOFILE, (requested_soft, existing_hard)) |
| 74 |
except ValueError: |
| 75 |
# some platforms (eg macOS) lie about their hard limit |
| 76 |
pass |
| 77 |
|
| 78 |
import sys |
| 79 |
import __main__ |
| 80 |
|
| 81 |
# For some distros and python versions we pick up this script in the temporary |
| 82 |
# directory. This leads to problems when the ansible module masks a python |
| 83 |
# library that another import needs. We have not figured out what about the |
| 84 |
# specific distros and python versions causes this to behave differently. |
| 85 |
# |
| 86 |
# Tested distros: |
| 87 |
# Fedora23 with python3.4 Works |
| 88 |
# Ubuntu15.10 with python2.7 Works |
| 89 |
# Ubuntu15.10 with python3.4 Fails without this |
| 90 |
# Ubuntu16.04.1 with python3.5 Fails without this |
| 91 |
# To test on another platform: |
| 92 |
# * use the copy module (since this shadows the stdlib copy module) |
| 93 |
# * Turn off pipelining |
| 94 |
# * Make sure that the destination file does not exist |
| 95 |
# * ansible ubuntu16-test -m copy -a 'src=/etc/motd dest=/var/tmp/m' |
| 96 |
# This will traceback in shutil. Looking at the complete traceback will show |
| 97 |
# that shutil is importing copy which finds the ansible module instead of the |
| 98 |
# stdlib module |
| 99 |
scriptdir = None |
| 100 |
try: |
| 101 |
scriptdir = os.path.dirname(os.path.realpath(__main__.__file__)) |
| 102 |
except (AttributeError, OSError): |
| 103 |
# Some platforms don't set __file__ when reading from stdin |
| 104 |
# OSX raises OSError if using abspath() in a directory we don't have |
| 105 |
# permission to read (realpath calls abspath) |
| 106 |
pass |
| 107 |
|
| 108 |
# Strip cwd from sys.path to avoid potential permissions issues |
| 109 |
excludes = {'', '.', scriptdir} |
| 110 |
sys.path = [p for p in sys.path if p not in excludes] |
| 111 |
|
| 112 |
import base64 |
| 113 |
import shutil |
| 114 |
import tempfile |
| 115 |
import zipfile |
| 116 |
|
| 117 |
def invoke_module(modlib_path: str, json_params: bytes) -> None: |
| 118 |
# When installed via setuptools (including python setup.py install), |
| 119 |
# ansible may be installed with an easy-install.pth file. That file |
| 120 |
# may load the system-wide install of ansible rather than the one in |
| 121 |
# the module. sitecustomize is the only way to override that setting. |
| 122 |
z = zipfile.ZipFile(modlib_path, mode='a') |
| 123 |
|
| 124 |
# py3: modlib_path will be text, py2: it's bytes. Need bytes at the end |
| 125 |
sitecustomize = 'import sys\nsys.path.insert(0, "%s")\n' % modlib_path |
| 126 |
sitecustomize = sitecustomize.encode('utf-8') |
| 127 |
# Use a ZipInfo to work around zipfile limitation on hosts with |
| 128 |
# clocks set to a pre-1980 year (for instance, Raspberry Pi) |
| 129 |
zinfo = zipfile.ZipInfo() |
| 130 |
zinfo.filename = 'sitecustomize.py' |
| 131 |
zinfo.date_time = date_time.utctimetuple()[:6] |
| 132 |
z.writestr(zinfo, sitecustomize) |
| 133 |
z.close() |
| 134 |
|
| 135 |
# Put the zipped up module_utils we got from the controller first in the python path so that we |
| 136 |
# can monkeypatch the right basic |
| 137 |
sys.path.insert(0, modlib_path) |
| 138 |
|
| 139 |
from ansible.module_utils._internal._ansiballz import _loader |
| 140 |
|
| 141 |
_loader.run_module( |
| 142 |
json_params=json_params, |
| 143 |
profile=profile, |
| 144 |
module_fqn=module_fqn, |
| 145 |
modlib_path=modlib_path, |
| 146 |
extensions=extensions, |
| 147 |
secrets=secrets, |
| 148 |
) |
| 149 |
|
| 150 |
def debug(command: str, modlib_path: str, json_params: bytes) -> None: |
| 151 |
# The code here normally doesn't run. It's only used for debugging on the |
| 152 |
# remote machine. |
| 153 |
# |
| 154 |
# The subcommands in this function make it easier to debug ansiballz |
| 155 |
# modules. Here's the basic steps: |
| 156 |
# |
| 157 |
# Run ansible with the environment variable: ANSIBLE_KEEP_REMOTE_FILES=1 and -vvv |
| 158 |
# to save the module file remotely:: |
| 159 |
# $ ANSIBLE_KEEP_REMOTE_FILES=1 ansible host1 -m ping -a 'data=october' -vvv |
| 160 |
# |
| 161 |
# Part of the verbose output will tell you where on the remote machine the |
| 162 |
# module was written to:: |
| 163 |
# [...] |
| 164 |
# <host1> SSH: EXEC ssh -C -q -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o |
| 165 |
# PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o |
| 166 |
# ControlPath=/home/badger/.ansible/cp/ansible-ssh-%h-%p-%r -tt rhel7 '/bin/sh -c '"'"'LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 |
| 167 |
# LC_MESSAGES=en_US.UTF-8 /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping'"'"'' |
| 168 |
# [...] |
| 169 |
# |
| 170 |
# Login to the remote machine and run the module file via from the previous |
| 171 |
# step with the explode subcommand to extract the module payload into |
| 172 |
# source files:: |
| 173 |
# $ ssh host1 |
| 174 |
# $ /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping explode |
| 175 |
# Module expanded into: |
| 176 |
# /home/badger/.ansible/tmp/ansible-tmp-1461173408.08-279692652635227/ansible |
| 177 |
# |
| 178 |
# You can now edit the source files to instrument the code or experiment with |
| 179 |
# different parameter values. When you're ready to run the code you've modified |
| 180 |
# (instead of the code from the actual zipped module), use the execute subcommand like this:: |
| 181 |
# $ /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping execute |
| 182 |
|
| 183 |
# Okay to use __file__ here because we're running from a kept file |
| 184 |
basedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'debug_dir') |
| 185 |
args_path = os.path.join(basedir, 'args') |
| 186 |
|
| 187 |
if command == 'explode': |
| 188 |
# transform the ZIPDATA into an exploded directory of code and then |
| 189 |
# print the path to the code. This is an easy way for people to look |
| 190 |
# at the code on the remote machine for debugging it in that |
| 191 |
# environment |
| 192 |
z = zipfile.ZipFile(modlib_path) |
| 193 |
for filename in z.namelist(): |
| 194 |
if filename.startswith('/'): |
| 195 |
raise Exception('Something wrong with this module zip file: should not contain absolute paths') |
| 196 |
|
| 197 |
dest_filename = os.path.join(basedir, filename) |
| 198 |
if dest_filename.endswith(os.path.sep) and not os.path.exists(dest_filename): |
| 199 |
os.makedirs(dest_filename) |
| 200 |
else: |
| 201 |
directory = os.path.dirname(dest_filename) |
| 202 |
if not os.path.exists(directory): |
| 203 |
os.makedirs(directory) |
| 204 |
with open(dest_filename, 'wb') as writer: |
| 205 |
writer.write(z.read(filename)) |
| 206 |
|
| 207 |
# write the args file |
| 208 |
with open(args_path, 'wb') as writer: |
| 209 |
writer.write(json_params) |
| 210 |
|
| 211 |
print('Module expanded into:') |
| 212 |
print(basedir) |
| 213 |
|
| 214 |
elif command == 'execute': |
| 215 |
# Execute the exploded code instead of executing the module from the |
| 216 |
# embedded ZIPDATA. This allows people to easily run their modified |
| 217 |
# code on the remote machine to see how changes will affect it. |
| 218 |
|
| 219 |
# Set pythonpath to the debug dir |
| 220 |
sys.path.insert(0, basedir) |
| 221 |
|
| 222 |
# read in the args file which the user may have modified |
| 223 |
with open(args_path, 'rb') as reader: |
| 224 |
json_params = reader.read() |
| 225 |
|
| 226 |
from ansible.module_utils._internal._ansiballz import _loader |
| 227 |
|
| 228 |
_loader.run_module( |
| 229 |
json_params=json_params, |
| 230 |
profile=profile, |
| 231 |
module_fqn=module_fqn, |
| 232 |
modlib_path=modlib_path, |
| 233 |
secrets=secrets, |
| 234 |
extensions=extensions, |
| 235 |
) |
| 236 |
|
| 237 |
else: |
| 238 |
print(f'FATAL: Unknown debug command {command!r}. Doing nothing.') |
| 239 |
|
| 240 |
# |
| 241 |
# See comments in the debug() method for information on debugging |
| 242 |
# |
| 243 |
|
| 244 |
encoded_params = params.encode() |
| 245 |
|
| 246 |
# There's a race condition with the controller removing the |
| 247 |
# remote_tmpdir and this module executing under async. So we cannot |
| 248 |
# store this in remote_tmpdir (use system tempdir instead) |
| 249 |
# Only need to use [ansible_module]_payload_ in the temp_path until we move to zipimport |
| 250 |
# (this helps ansible-test produce coverage stats) |
| 251 |
# IMPORTANT: The real path must be used here to ensure a remote debugger such as PyCharm (using pydevd) can resolve paths correctly. |
| 252 |
temp_path = os.path.realpath(tempfile.mkdtemp(prefix='ansible_' + ansible_module + '_payload_')) |
| 253 |
|
| 254 |
try: |
| 255 |
zipped_mod = os.path.join(temp_path, 'ansible_' + ansible_module + '_payload.zip') |
| 256 |
|
| 257 |
with open(zipped_mod, 'wb') as modlib: |
| 258 |
modlib.write(base64.b64decode(zip_data)) |
| 259 |
|
| 260 |
if len(sys.argv) == 2: |
| 261 |
debug(sys.argv[1], zipped_mod, encoded_params) |
| 262 |
else: |
| 263 |
invoke_module(zipped_mod, encoded_params) |
| 264 |
finally: |
| 265 |
shutil.rmtree(temp_path, ignore_errors=True) |