
    Vh                       d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlmZmZmZ d dlmZ d dlmZmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dl m!Z!m"Z"m#Z# d dl$m%Z% d dl&m'Z'm(Z( d dl)m*Z* d dl+m,Z, d dl-m.Z. d dl/Z0d dl1Z0 e,       Z2 e.dg d      Z3dZ4dZ5dZ6dZ7dZ8dZ9dZ:dZ;ejx                  j{                  ejx                  j}                  e?      dd      Z@dZAdZBdZCd ZDd! ZEej                  reAZGn eEeA      ZGejx                  j}                  ejx                  j}                  ejx                  j}                  e?                  ZH e
j                  d" e
j                  eH      z        ZK e
j                  d#      ZL e
j                  d$      ZM G d% d&ej                        ZOd' ZP eQ       d(fd)ZR G d* d+      ZS G d, d-eS      ZT G d. d/eS      ZUd9d0ZVd9d1ZWd2 ZXd3 ZYd4 ZZ	 d:d5Z[d6 Z\	 	 d;d7Z]d9d8Z^y)<    )annotationsN)ASTImport
ImportFrom)BytesIO)__version__
__author__)	constants)AnsibleError)!InterpreterDiscoveryRequiredError)module_manifest)AnsibleJSONEncoder)to_bytesto_text	to_native)module_utils_loader)_get_collection_metadata_nested_dict_get)action_write_locks)Display)
namedtupleModuleUtilsProcessEntry)
name_partsis_ambiguoushas_redirected_childis_optionals"   #<<INCLUDE_ANSIBLE_MODULE_COMMON>>s   "<<ANSIBLE_VERSION>>"s)   "<<INCLUDE_ANSIBLE_MODULE_COMPLEX_ARGS>>"s   # POWERSHELL_COMMONs$   <<INCLUDE_ANSIBLE_MODULE_JSON_ARGS>>s   <<SELINUX_SPECIAL_FILESYSTEMS>>z# -*- coding: utf-8 -*-s   # -*- coding: utf-8 -*-z..module_utilsa.  %(shebang)s
%(coding)s
_ANSIBALLZ_WRAPPER = True # For test-module.py script to tell this is a ANSIBALLZ_WRAPPER
# This code is part of Ansible, but is an independent component.
# The code in this particular templatable string, and this templatable string
# only, is BSD licensed.  Modules which end up using this snippet, which is
# dynamically combined together by Ansible still belong to the author of the
# module, and they may assign their own license to the complete work.
#
# Copyright (c), James Cammarata, 2016
# Copyright (c), Toshio Kuratomi, 2016
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice,
#      this list of conditions and the following disclaimer in the documentation
#      and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
def _ansiballz_main():
    import os
    import os.path

    # Access to the working directory is required by Python when using pipelining, as well as for the coverage module.
    # Some platforms, such as macOS, may not allow querying the working directory when using become to drop privileges.
    try:
        os.getcwd()
    except OSError:
        try:
            os.chdir(os.path.expanduser('~'))
        except OSError:
            os.chdir('/')

%(rlimit)s

    import sys
    import __main__

    # For some distros and python versions we pick up this script in the temporary
    # directory.  This leads to problems when the ansible module masks a python
    # library that another import needs.  We have not figured out what about the
    # specific distros and python versions causes this to behave differently.
    #
    # Tested distros:
    # Fedora23 with python3.4  Works
    # Ubuntu15.10 with python2.7  Works
    # Ubuntu15.10 with python3.4  Fails without this
    # Ubuntu16.04.1 with python3.5  Fails without this
    # To test on another platform:
    # * use the copy module (since this shadows the stdlib copy module)
    # * Turn off pipelining
    # * Make sure that the destination file does not exist
    # * ansible ubuntu16-test -m copy -a 'src=/etc/motd dest=/var/tmp/m'
    # This will traceback in shutil.  Looking at the complete traceback will show
    # that shutil is importing copy which finds the ansible module instead of the
    # stdlib module
    scriptdir = None
    try:
        scriptdir = os.path.dirname(os.path.realpath(__main__.__file__))
    except (AttributeError, OSError):
        # Some platforms don't set __file__ when reading from stdin
        # OSX raises OSError if using abspath() in a directory we don't have
        # permission to read (realpath calls abspath)
        pass

    # Strip cwd from sys.path to avoid potential permissions issues
    excludes = set(('', '.', scriptdir))
    sys.path = [p for p in sys.path if p not in excludes]

    import base64
    import runpy
    import shutil
    import tempfile
    import zipfile

    if sys.version_info < (3,):
        PY3 = False
    else:
        PY3 = True

    ZIPDATA = %(zipdata)r

    # Note: temp_path isn't needed once we switch to zipimport
    def invoke_module(modlib_path, temp_path, json_params):
        # When installed via setuptools (including python setup.py install),
        # ansible may be installed with an easy-install.pth file.  That file
        # may load the system-wide install of ansible rather than the one in
        # the module.  sitecustomize is the only way to override that setting.
        z = zipfile.ZipFile(modlib_path, mode='a')

        # py3: modlib_path will be text, py2: it's bytes.  Need bytes at the end
        sitecustomize = u'import sys\nsys.path.insert(0,"%%s")\n' %% modlib_path
        sitecustomize = sitecustomize.encode('utf-8')
        # Use a ZipInfo to work around zipfile limitation on hosts with
        # clocks set to a pre-1980 year (for instance, Raspberry Pi)
        zinfo = zipfile.ZipInfo()
        zinfo.filename = 'sitecustomize.py'
        zinfo.date_time = %(date_time)s
        z.writestr(zinfo, sitecustomize)
        z.close()

        # Put the zipped up module_utils we got from the controller first in the python path so that we
        # can monkeypatch the right basic
        sys.path.insert(0, modlib_path)

        # Monkeypatch the parameters into basic
        from ansible.module_utils import basic
        basic._ANSIBLE_ARGS = json_params
%(coverage)s
        # Run the module!  By importing it as '__main__', it thinks it is executing as a script
        runpy.run_module(mod_name=%(module_fqn)r, init_globals=dict(_module_fqn=%(module_fqn)r, _modlib_path=modlib_path),
                         run_name='__main__', alter_sys=True)

        # Ansible modules must exit themselves
        print('{"msg": "New-style module did not handle its own exit", "failed": true}')
        sys.exit(1)

    def debug(command, zipped_mod, json_params):
        # The code here normally doesn't run.  It's only used for debugging on the
        # remote machine.
        #
        # The subcommands in this function make it easier to debug ansiballz
        # modules.  Here's the basic steps:
        #
        # Run ansible with the environment variable: ANSIBLE_KEEP_REMOTE_FILES=1 and -vvv
        # to save the module file remotely::
        #   $ ANSIBLE_KEEP_REMOTE_FILES=1 ansible host1 -m ping -a 'data=october' -vvv
        #
        # Part of the verbose output will tell you where on the remote machine the
        # module was written to::
        #   [...]
        #   <host1> SSH: EXEC ssh -C -q -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o
        #   PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o
        #   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
        #   LC_MESSAGES=en_US.UTF-8 /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping'"'"''
        #   [...]
        #
        # Login to the remote machine and run the module file via from the previous
        # step with the explode subcommand to extract the module payload into
        # source files::
        #   $ ssh host1
        #   $ /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping explode
        #   Module expanded into:
        #   /home/badger/.ansible/tmp/ansible-tmp-1461173408.08-279692652635227/ansible
        #
        # You can now edit the source files to instrument the code or experiment with
        # different parameter values.  When you're ready to run the code you've modified
        # (instead of the code from the actual zipped module), use the execute subcommand like this::
        #   $ /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping execute

        # Okay to use __file__ here because we're running from a kept file
        basedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'debug_dir')
        args_path = os.path.join(basedir, 'args')

        if command == 'explode':
            # transform the ZIPDATA into an exploded directory of code and then
            # print the path to the code.  This is an easy way for people to look
            # at the code on the remote machine for debugging it in that
            # environment
            z = zipfile.ZipFile(zipped_mod)
            for filename in z.namelist():
                if filename.startswith('/'):
                    raise Exception('Something wrong with this module zip file: should not contain absolute paths')

                dest_filename = os.path.join(basedir, filename)
                if dest_filename.endswith(os.path.sep) and not os.path.exists(dest_filename):
                    os.makedirs(dest_filename)
                else:
                    directory = os.path.dirname(dest_filename)
                    if not os.path.exists(directory):
                        os.makedirs(directory)
                    f = open(dest_filename, 'wb')
                    f.write(z.read(filename))
                    f.close()

            # write the args file
            f = open(args_path, 'wb')
            f.write(json_params)
            f.close()

            print('Module expanded into:')
            print('%%s' %% basedir)
            exitcode = 0

        elif command == 'execute':
            # Execute the exploded code instead of executing the module from the
            # embedded ZIPDATA.  This allows people to easily run their modified
            # code on the remote machine to see how changes will affect it.

            # Set pythonpath to the debug dir
            sys.path.insert(0, basedir)

            # read in the args file which the user may have modified
            with open(args_path, 'rb') as f:
                json_params = f.read()

            # Monkeypatch the parameters into basic
            from ansible.module_utils import basic
            basic._ANSIBLE_ARGS = json_params

            # Run the module!  By importing it as '__main__', it thinks it is executing as a script
            runpy.run_module(mod_name=%(module_fqn)r, init_globals=None, run_name='__main__', alter_sys=True)

            # Ansible modules must exit themselves
            print('{"msg": "New-style module did not handle its own exit", "failed": true}')
            sys.exit(1)

        else:
            print('WARNING: Unknown debug command.  Doing nothing.')
            exitcode = 0

        return exitcode

    #
    # See comments in the debug() method for information on debugging
    #

    ANSIBALLZ_PARAMS = %(params)s
    if PY3:
        ANSIBALLZ_PARAMS = ANSIBALLZ_PARAMS.encode('utf-8')
    try:
        # There's a race condition with the controller removing the
        # remote_tmpdir and this module executing under async.  So we cannot
        # store this in remote_tmpdir (use system tempdir instead)
        # Only need to use [ansible_module]_payload_ in the temp_path until we move to zipimport
        # (this helps ansible-test produce coverage stats)
        temp_path = tempfile.mkdtemp(prefix='ansible_' + %(ansible_module)r + '_payload_')

        zipped_mod = os.path.join(temp_path, 'ansible_' + %(ansible_module)r + '_payload.zip')

        with open(zipped_mod, 'wb') as modlib:
            modlib.write(base64.b64decode(ZIPDATA))

        if len(sys.argv) == 2:
            exitcode = debug(sys.argv[1], zipped_mod, ANSIBALLZ_PARAMS)
        else:
            # Note: temp_path isn't needed once we switch to zipimport
            invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
    finally:
        try:
            shutil.rmtree(temp_path)
        except (NameError, OSError):
            # tempdir creation probably failed
            pass
    sys.exit(exitcode)

if __name__ == '__main__':
    _ansiballz_main()
a  
        os.environ['COVERAGE_FILE'] = %(coverage_output)r + '=python-%%s=coverage' %% '.'.join(str(v) for v in sys.version_info[:2])

        import atexit

        try:
            import coverage
        except ImportError:
            print('{"msg": "Could not import `coverage` module.", "failed": true}')
            sys.exit(1)

        cov = coverage.Coverage(config_file=%(coverage_config)r)

        def atexit_coverage():
            cov.stop()
            cov.save()

        atexit.register(atexit_coverage)

        cov.start()
a  
        try:
            if PY3:
                import importlib.util
                if importlib.util.find_spec('coverage') is None:
                    raise ImportError
            else:
                import imp
                imp.find_module('coverage')
        except ImportError:
            print('{"msg": "Could not find `coverage` module.", "failed": true}')
            sys.exit(1)
a  
    import resource

    existing_soft, existing_hard = resource.getrlimit(resource.RLIMIT_NOFILE)

    # adjust soft limit subject to existing hard limit
    requested_soft = min(existing_hard, %(rlimit_nofile)d)

    if requested_soft != existing_soft:
        try:
            resource.setrlimit(resource.RLIMIT_NOFILE, (requested_soft, existing_hard))
        except ValueError:
            # some platforms (eg macOS) lie about their hard limit
            pass
c                    g }| j                         D ]7  }|j                         }|r|j                  d      r'|j                  |       9 dj	                  |      S )N#
)
splitlinesstrip
startswithappendjoin)sourcebuflinels       N/home/dcms/DCMS/lib/python3.12/site-packages/ansible/executor/module_common.py_strip_commentsr+     sW    
C!!# JJLALL&

4	
 ::c?    z*%s/(?P<path>ansible/modules/.*)\.(py|ps1)$zH/(?P<path>ansible_collections/[^/]+/[^/]+/plugins/modules/.*)\.(py|ps1)$s   (?:from +\.{2,} *module_utils.* +import |from +ansible_collections\.[^.]+\.[^.]+\.plugins\.module_utils.* +import |import +ansible_collections\.[^.]+\.[^.]+\.plugins\.module_utils.*|from +ansible\.module_utils.* +import |import +ansible\.module_utils\.)c                  6     e Zd Zd fd	Zd ZeZd Zd Z xZS )ModuleDepFinderc                   t        t        | 
  |i | || _        t	               | _        t	               | _        || _        || _        t        | j                  t        | j                  i| _        | j                  |       y)a  
        Walk the ast tree for the python module.
        :arg module_fqn: The fully qualified name to reach this module in dotted notation.
            example: ansible.module_utils.basic
        :arg is_pkg_init: Inform the finder it's looking at a package init (eg __init__.py) to allow
            relative import expansion to use the proper package level without having imported it locally first.

        Save submodule[.submoduleN][.identifier] into self.submodules
        when they are from ansible.module_utils or ansible_collections packages

        self.submodules will end up with tuples like:
          - ('ansible', 'module_utils', 'basic',)
          - ('ansible', 'module_utils', 'urls', 'fetch_url')
          - ('ansible', 'module_utils', 'database', 'postgres')
          - ('ansible', 'module_utils', 'database', 'postgres', 'quote')
          - ('ansible', 'module_utils', 'database', 'postgres', 'quote')
          - ('ansible_collections', 'my_ns', 'my_col', 'plugins', 'module_utils', 'foo')

        It's up to calling code to determine whether the final element of the
        tuple are module names or something else (function, class, or variable names)
        .. seealso:: :python3:class:`ast.NodeVisitor`
        N)superr.   __init___treeset
submodulesoptional_imports
module_fqnis_pkg_initr   visit_Importr   visit_ImportFrom
_visit_mapvisit)selfr6   treer7   argskwargs	__class__s         r*   r1   zModuleDepFinder.__init__  sq    . 	ot-t>v>
% #$& D%%--

 	

4r,   c                6   | j                   }| j                  }t        j                  |      D ]i  \  }}t	        |t
              s|D ]N  }t	        |t        t        f      r||_         ||j                     |       6t	        |t              sG ||       P k y)zOverridden ``generic_visit`` that makes some assumptions about our
        use case, and improves performance by calling visitors directly instead
        of calling ``visit`` to offload calling visitors.
        N)generic_visitr:   astiter_fields
isinstancelistr   r   parentr@   r   )r<   noderB   	visit_mapfieldvalueitems          r*   rB   zModuleDepFinder.generic_visit  s    
 **OO	OOD1 	,LE5%&! ,D!$(<=&*1	$..1$7#D#.%d+,	,r,   c                   |j                   D ]  }|j                  j                  d      s|j                  j                  d      s:t        |j                  j	                  d            }| j
                  j                  |       |j                  | j                  k7  s| j                  j                  |        | j                  |       y)z
        Handle import ansible.module_utils.MODLIB[.MODLIBn] [as asname]

        We save these as interesting submodules when the imported library is in ansible.module_utils
        or ansible.collections
        zansible.module_utils.ansible_collections..N)namesnamer#   tuplesplitr4   addrG   r2   r5   rB   )r<   rH   aliaspy_mods       r*   r8   zModuleDepFinder.visit_Import  s     ZZ 	6E

%%&=>JJ))*@Auzz//45##F+;;$**,))--f5	6 	4 r,   c                   |j                   dkD  r| j                  r|j                    dz   xs dn|j                    }| j                  rht        | j                  j	                  d            }|j
                  r#dj                  |d| |j
                  fz         }n.dj                  |d|       }n|j
                  }n|j
                  }d}|j                  d   j                  dk(  r| j                  j                  d       nn|j                  d      rt        |j	                  d            }nB|j                  d      r1|j                  d	      sd
|v rt        |j	                  d            }n	 |r}|j                  D ]n  }| j                  j                  ||j                  fz          |j                  | j                  k7  sF| j                  j                  ||j                  fz          p | j!                  |       y)a	  
        Handle from ansible.module_utils.MODLIB import [.MODLIBn] [as asname]

        Also has to handle relative imports

        We save these as interesting submodules when the imported library is in ansible.module_utils
        or ansible.collections
        r      NrO   _six)rY   zansible.module_utilsrN   zplugins.module_utilsz.plugins.module_utils.)levelr7   r6   rR   rS   moduler%   rP   rQ   r4   rT   r#   endswithrG   r2   r5   rB   )r<   rH   level_slice_offsetpartsnode_modulerV   rU   s          r*   r9   z ModuleDepFinder.visit_ImportFrom  s    ::><@<L<L$**q!8DSWS]S]R]doo33C89;;"%((51D2D+E+V"WK #&((51D2D+E"FK #kk ++K ::a='OO	*##$:;
 ;,,S12F##$:;##$:;?W[f?f
 {0056  F##Fejj]$:;;;$**,))--f

}.DE	F 	4 r,   F)	__name__
__module____qualname__r1   rB   r;   r8   r9   __classcell__r@   s   @r*   r.   r.     s    #J,  E!"?!r,   r.   c                    t         j                  j                  |       s+t        dt         j                  j	                  |       z        t        | d      5 }|j                         }d d d        |S # 1 sw Y   S xY w)Nz1imported module support code does not exist at %srb)ospathexistsr   abspathopenread)ri   fddatas      r*   _slurprp   @  sg    77>>$NQSQXQXQ`Q`aeQffgg	dD	 RwwyKKs   A22A<Fc                   t         j                  j                  |       j                         }d|z  }d|j	                         z  }d}|dk(  r|r|d   }nt
        j                  j                  |      rut
        j                  j                  ||      }	|j                  |	j                               }|r|dv rod|z  }
|j                  d	i       }|
|vrt        d
||      ||
   }n@t        d|d      ||v r.|j                  |j                  |      j                               }|s| }dj                  |      }|r|dz   dj                  |      z   }||fS )za
      Handles the different ways ansible allows overriding the shebang target for a module.
    zansible_%s_interpreterzINTERPRETER_%sNpythonansible_playbook_python	variables)autoauto_legacyauto_silentauto_legacy_silentzdiscovered_interpreter_%sansible_factszinterpreter discovery needed)interpreter_namediscovery_modezinterpreter discovery requiredrw   z#!{0} )rh   ri   basenamer"   upperCconfigget_configuration_definitionget_config_valuetemplategetr   formatr%   )interpreter	task_varstemplarr>   remote_is_localr{   interpreter_configinterpreter_config_keyinterpreter_outinterpreter_from_configdiscovered_interpreter_configfacts_from_task_varsshebangs                r*   _get_shebangr   H  s    ww''4::< 35EE-0@0F0F0HHO 8#'(ABO XX223IJ&'hh&?&?@Vbk&?&l#%../F/L/L/NOO #o9u&u0LO_0_-'0}}_b'I$08LL;<Zm}  O^  _  _&:;X&YO34Tgw  IV  W  W	y	(!**9==9K+L+R+R+TU% ooo.GD.499T?2O##r,   c                  J    e Zd Zd
dZed        Zd Zd Zd Zd Z	ddZ
d Zy	)ModuleUtilLocatorBasec                    || _         || _        || _        d| _        d| _        || _        d| _        d| _        d| _        d | _	        |r*t        | j                  |            dkD  r||d d g| _        y |g| _        y )NF rX   )_is_ambiguous_child_is_redirected_is_optionalfound
redirectedfq_name_partssource_codeoutput_path
is_package_collection_namelen!_get_module_utils_remainder_partscandidate_names)r<   r   r   child_is_redirectedr   s        r*   r1   zModuleUtilLocatorBase.__init__  s    ) %8!'
* $ C F F} UVYZZ$1="3E#FD $1?D r,   c                ^    | j                   D cg c]  }dj                  |       c}S c c}w NrO   )r   r%   )r<   ns     r*   candidate_names_joinedz,ModuleUtilLocatorBase.candidate_names_joined  s$    %)%9%9::::s   *c           
        | j                  |      }|sy	 t        | j                        }t        |dddj                  |      g      }|sy|j                  d      }|d u}|s|j                  d      }|r|j                  d      }|j                  d	      }	|j                  d
      }
dj                  dj                  |            }|
r|dj                  |
      z  }n|dz  }t        j                  ||	||| j                         d|v rd| _        dj                  |      }d| _        |d   }|j                  d      se|j!                  d      }t#        |      dk  rt%        dj                  ||            dj                  |d   |d   dj                  |dd              }t        j'                  dj                  ||             | j)                  ||      | _        yy# t        $ rT}| j                  rY d }~yt        dj                  dj                  |      | j                  t        |                  d }~ww xY w)NFzGerror processing module_util {0} loading redirected collection {1}: {2}rO   plugin_routingr   	tombstonedeprecationremoval_dateremoval_versionwarning_textz module_util {0} has been removedz ({0})redirectTansible_collections   zinvalid redirect for {0}: {1}z4ansible_collections.{0}.{1}.plugins.module_utils.{2}r   rX      z"redirecting module_util {0} to {1})r   r   r   
ValueErrorr   r   r   r%   r   r   r   display
deprecatedr   r   r#   rS   r   	Exceptionvvv_generate_redirect_shim_sourcer   )r<   r   module_utils_relative_partscollection_metadataverouting_entry	dep_or_tsremovedr   r   r   msg
source_pkgredirect_target_pkg
split_fqcns                  r*   _handle_redirectz&ModuleUtilLocatorBase._handle_redirect  sS   &*&L&LZ&X# +	d":4;P;P"Q ))<?OQ_adaiai  kF  bG  ?H  I "%%k2	4'%))-8I$==8L'mm,=>O$==8L4;;CHHZ<PQCx|44s
sOWlDLaLab&"DO*-J"DO"/
"; '112GH066s;
z?Q&#$C$J$J:Wj$kll&\&c&cqMqMHHZ^,'#
 KK<CCJPcde#BB:ObcDa  	d  h &sxx
';T=R=RT]^`Ta bd d	ds   G$ $	I-H<>>H<<Ic                    g S N r<   r   s     r*   r   z7ModuleUtilLocatorBase._get_module_utils_remainder_parts  s    	r,   c                B    dj                  | j                  |            S r   )r%   r   r   s     r*   _get_module_utils_remainderz1ModuleUtilLocatorBase._get_module_utils_remainder  s    xx>>zJKKr,   c                     y)NFr   r   s     r*   _find_modulez"ModuleUtilLocatorBase._find_module  s    r,   c                f   | j                   D ]@  }|r| j                  |      r nG| j                  |      r n4|r.| j                  |      s@ n | j                  rd| _        d| _        ny | j                  rdz   }n}d| _        t        j                  j                  | dz   | _
        || _        y )NTr   )r1   .py)r   r   r   r   r   r   r   rh   ri   r%   r   r   )r<   redirect_firstcandidate_name_parts
path_partss       r*   _locatezModuleUtilLocatorBase._locate  s    $($8$8 	 $"7"78L"M  !56!d&;&;<P&Q	 (("&#% ??-=J-J
77<<4u<1r,   c                &    dj                  ||      S )Nz8
import sys
import {1} as mod

sys.modules['{0}'] = mod
)r   )r<   fq_source_modulefq_target_modules      r*   r   z4ModuleUtilLocatorBase._generate_redirect_shim_source  s    
 F-.	/r,   NFFF)T)ra   rb   rc   r1   propertyr   r   r   r   r   r   r   r   r,   r*   r   r     s;    3* ; ;9vL24/r,   r   c                  ,     e Zd Zd fd	Zd Zd Z xZS )LegacyModuleUtilLocatorc                    t         t        |   |||       |dd dk7  rt        dj	                  |            |d   dk(  r
d}|g| _        || _        d| _        | j                  d	       y )
Nr   r   ansibler   z=this class can only locate from ansible.module_utils, got {0}six)r   r   r   zansible.builtinF)r   )	r0   r   r1   r   r   r   	_mu_pathsr   r   )r<   r   r   mu_pathsr   r@   s        r*   r1   z LegacyModuleUtilLocator.__init__  s{    %t5m\Sfg1!<<[bbcpqrru$ ?M$1?D ! 1E*r,   c                    |dd  S )Nr   r   r   s     r*   r   z9LegacyModuleUtilLocator._get_module_utils_remainder_parts      !"~r,   c           	     f   | j                  |      }t        |      dk(  r| j                  }n:| j                  D cg c]%  }t        j                  j
                  |g|d d  ' }}t        j                  j                  j                  dj                  |      |      x| _
        }|st        j                  j                  |j                        d   t        j                  j                  v r-|j                  j                  d      | _        |j                  }nyt!        |      | _        yc c}w )NrX   r   rO   /__init__.pyFT)r   r   r   rh   ri   r%   	importlib	machinery
PathFinder	find_spec_infosplitextoriginSOURCE_SUFFIXESr\   r   rp   r   )r<   r   rel_name_partspathspinfori   s          r*   r   z$LegacyModuleUtilLocator._find_module  s    ??
K ~!#NNE ^^%qRWW\\!:nSb&9: %E % &//::DDSXXjEY[`aa
T 0 0 =a @IDWDWDgDg g"kk22>BDO;;D!$<%s   *D.)FNF)ra   rb   rc   r1   r   r   rd   re   s   @r*   r   r     s    + r,   r   c                  ,     e Zd Zd fd	Zd Zd Z xZS )CollectionModuleUtilLocatorc                (   t         t        |   ||||       |d   dk7  rt        dj	                  |            t        |      dk\  r"|dd dk7  rt        dj	                  |            d	j                  |d
d       | _        | j                          y )Nr   r   zMCollectionModuleUtilLocator can only locate from ansible_collections, got {0}   r      )pluginsr   zoCollectionModuleUtilLocator can only locate below ansible_collections.(ns).(coll).plugins.module_utils, got {0}rO   rX   )	r0   r   r1   r   r   r   r%   r   r   )r<   r   r   r   r   r@   s        r*   r1   z$CollectionModuleUtilLocator.__init__1  s    )49-Wjlwx44krr  tA  B  C  C1$q);?Z)Z  N#VM24 4 !$q); <r,   c           	        t        |      dk  rd| _        d| _        ydj                  |dd       }t	        j
                  j                  |dd   }d }	 t        j                  |t        t        j
                  j                  |d                  }|d| _        n#	 t        j                  |t        |dz               }|y	|| _        y# t        $ r Y Cw xY w# t        $ r Y %w xY w)
Nr   r   TrO   r   r   z__init__.pyr   F)
r   r   r   r%   rh   ri   pkgutilget_datar   ImportError)r<   r   collection_pkg_nameresource_base_pathsrcs        r*   r   z(CollectionModuleUtilLocator._find_module>  s     z?Q!D"DO "hhz!A7WW\\:ab>:	""#6	"'',,OacpBq8rsC ?"DO&&':IFX[`F`<ab ;#  		  s$   =C	 "C 		CC	C$#C$c                    |dd  S )Nr   r   r   s     r*   r   z=CollectionModuleUtilLocator._get_module_utils_remainder_partsd  r   r,   r   )ra   rb   rc   r1   r   r   rd   re   s   @r*   r   r   0  s    $Lr,   r   c                Z    t        j                  | |      }|r|j                  |_        |S )N)filename	date_time)zipfileZipInfocompressioncompress_type)r   r  zfzinfos       r*   _make_zinfor  h  s,    OOE 
 nnLr,   c           
     X   |t        j                         dd }dt        t              z   dz   t        t              z   dz   dfddt        j                  d	
      D cg c]$  }t        j                  j                  |      s#|& }}|j                  t               	 t        |ddt        j                        }t'        ||      j(                  D 	cg c]  }	t+        |	dd	|	j,                  v        }
}	|
j                  t+        dd	d	d	             |
r|
j/                          |
j1                  d      \  }}}}|v r.|dd dk(  rt3        ||||      }n2|d   dk(  rt5        ||||      }nt6        j9                  d|gz         x|j:                  s*|rdj=                  ||j>                        }t#        |      |j@                  v r	 t        |jB                  ddt        j                        }t'        djE                  |j@                        ||jF                        |
jI                  fdj(                  D               |jB                  |jJ                  f|j@                  <   g }|j@                  dd D ]K  }|j                  |       tM        |      }|vs$|
j                  t+        |d	|jN                  |             M |
rD ]S  }|   d   }|jQ                  tS        |||      |   d          tU        |d       }t6        jW                  d!|z         U yc c}w # t        t         f$ r }t#        d| d|j$                        d}~ww xY wc c}	w # t        t         f$ r*}t#        d|j@                  d|j$                        d}~ww xY w)"a  
    Using ModuleDepFinder, make sure we have all of the module_utils files that
    the module and its module_utils files needs. (no longer actually recursive)
    :arg name: Name of the python module we're examining
    :arg module_fqn: Fully qualified name of the python module we're scanning
    :arg module_data: string Python code of the module we're scanning
    :arg zf: An open :python:class:`zipfile.ZipFile` object that holds the Ansible module payload
        which we're assembling
    Nr   sU   from pkgutil import extend_path
__path__=extend_path(__path__,__name__)
__version__="s   "
__author__="s   "
zansible/__init__.py)sH   from pkgutil import extend_path
__path__=extend_path(__path__,__name__)
z ansible/module_utils/__init__.py))r   r   F)subdirsz	<unknown>execzUnable to import z due to Tr   )r   r   basicr   r   r   )r   r   r   r   )r   r   r   z=ModuleDepFinder improperly found a non-module_utils import %szFCould not find imported module support code for {0}.  Looked for ({1})rO   c              3  \   K   | ]#  }|vrt        |d d|j                  v        % yw)TFr  N)r   r5   ).0mfinderpy_module_caches     r*   	<genexpr>z#recursive_finder.<locals>.<genexpr>  s=      "Z&'@X #:!T5VW[a[r[rVr"s"s "Zs   ),r   rX   r  surrogate_or_stricterrorszIncluding module_utils file %s),timegmtimer   r   r	   r   
_get_pathsrh   ri   isdirr$   _MODULE_UTILS_PATHcompilerC   PyCF_ONLY_ASTSyntaxErrorIndentationErrorr   r   r.   r4   r   r5   sortpopr   r   r   warningr   r   r   r   r   r%   r   extendr   rR   r   writestrr  r   vvvvv)rQ   r6   module_datar  r  r   module_utils_pathsr=   er  modules_to_processpy_module_namer   r   r   module_infor   accumulated_pkg_namepkgnormalized_namepy_module_file_namemu_filer  r  s                         @@r*   recursive_finderr2  r  s    KKM"1%	'45  "**!56 9?? "#&0
1O &9%C%CE%RgVXV]V]VcVcdeVf!gg01L{K9J9JK Z.F v|  vG  vG  Hpq1!T5aSYSjSjNjk  H  H 56Z\achv{|} !I[I_I_`aIbF&9;_,!A"==1.|;McvxKA"775nS_J]kvxK OO[-./ 0   Zaablny  oQ  oQ  RCs## $$7	e;22KIZIZ[D !+*C*C!DdKLbLbc!! "Z+1+<+<"Z 	Z 7B6M6M{OfOf5g112  ",,Sb1 	LC '',#$89Oo5"))*A/SXZeZpZp  J  +K  L		Lc n * B-n=a@
+Y2>N+A.	
 -6KL6@ABU h )* LdAEEJKKL HV -. 	e+B[B[]^]b]bcdd	esB   !$L4L4"L9 "M+&M0 9M(M##M(0N)?%N$$N)c           	         t        t        g d      t        t        dd            t        dg      z
  z        }| d d }t        |j	                  d |            S )N)      	   
                      i   )	bytearrayr3   rangebool	translate)b_module_data	textcharsstarts      r*   
_is_binaryrE    sT    #783uT5?Q;RUXZ^Y_U`;``aI%4 Ei011r,   c                    d}t         j                  |       }|st        j                  |       }|rB|j                  d      }d|v rt	        d      dj                  |j                  d            }|S t	        d      )ap  
    Get the fully qualified name for an ansible module based on its pathname

    remote_module_fqn is the fully qualified name.  Like ansible.modules.system.ping
    Or ansible_collections.Namespace.Collection_name.plugins.modules.ping
    .. warning:: This function is for ansible modules only.  It won't work for other things
        (non-module plugins, etc)
    Nri   rO   z7Module name (or path) was not a valid python identifier/z1Unable to determine module's fully qualified name)CORE_LIBRARY_PATH_REsearchCOLLECTION_PATH_REgroupr   r%   rS   )module_pathremote_module_fqnmatchri   s       r*   _get_ansible_module_fqnrO    s      !''4E"))+6 {{6"$; VWWHHTZZ_5
  LMMr,   c                   |j                  d      }dj                  |      dz   }| j                  t        |||       |       |d   dk(  rd}t	               }nd}t	        | j                               }t        |t        |            D ]<  }dj                  |d	|       d
z   }	|	|v r| j                  t        |	||       d       > y	)zKAdd a module from ansible or from an ansible collection into the module ziprO   rG  r   r  r   r   r   rX   Nr   r,   )rS   r%   r%  r  	frozensetnamelistr?  r   )
r  r  rM  rB  module_path_partsrL  rD  existing_pathsidxpackage_paths
             r*   _add_module_to_ziprW    s    )//4 ((,-5KKKKr2 y(" "2;;=1UC 123 

xx 1$3 78>I>) 	iB7	


r,   c                F   dx}}t        |      rdx}}n4t        |v rd}d}|j                  t        d      }nt        j	                  |      rd}d}nt
        |v rd}d}|j                  t
        d      }nt        j                  d|t        j                        st        j                  d	|t        j                        sot        j                  d
|t        j                        sJt        j                  d|t        j                        s%t        j                  d|t        j                        rd}d}nt        |v rd}d}nd|v rdx}}d}|dv r|||fS t               }	 t        |      }|dk(  rt        j                         dd }|d   dk  rJt!        j                   |dt         j"                  j$                  ij'                  d      }t)        d|       t+        |      }	 t-        t/        j0                  |t2        d            }	 t9        t:        |      }tB        jD                  jG                  tH        jJ                  d      }tB        jD                  jG                  ||d |      }d}tB        jD                  jM                  |      r?t        j                  d!|z         tO        |d"      5 }|jQ                         }ddd       nY| tR        jR                  v r,t        j                  d#| z         tR        jR                  |    }n+t        j                  d$| z         tR        jR                  d   }t        j                  d%       |5  t        j                  d&tU        |      z         tB        jD                  jM                  |      sRt        j                  d'       t               }t;        jV                  |d(|)      } tY        | ||| |       t        j                  d*       t[        | |||       | j]                          t_        j`                  |jc                               }tB        jD                  jM                  |      s	 tC        jd                  |       t        j                  d+       tO        |d,z   d-      5 }!|!ji                  |       ddd       t        j                  d.       tC        jj                  |d,z   |       t        j                  d/       ddd       |;t        j                  d0       	 tO        |d"      5 }!|!jQ                         }ddd       to        |d23      }tq        |      \  }"}#|"d4}"ts        |"|||#|5      \  }}$tH        jt                  jw                  d6|7      }%ty        |%tz              st{        |j}                  |%            }%|%rt~        t+        |%8      z  }&nd9}&tB        j                  j                  d:      }'|'r1tB        j                  d;   }(|(rt        t+        |'|(<      z  })n	t        })nd9})|ji                  t        t        t+        || |||t        ||)|&=	      z               |jc                         }n=|dk(  r%d>}t        j                  |||||||	|
|||||      }n|dk(  rt        t/        j0                  |t2        d            }*t        t-        |*            }+|j                  t        t        t-        t                          }|j                  t        |+      }|j                  t        t        d?jG                  tH        j                                    }|j                  t        |*      }d@t        |j                  dAtH        j                        d23      z   },|j                  dB|,      }|||fS # t        $ r t        j                  d       d| z  }Y Xw xY w# t4        $ r}t)        dt7        |      z        d}~ww xY w# t<        $ r, t        j?                  d|z         t:        j@                  }Y w xY w# 1 sw Y   xY w# tf        $ r$ tB        jD                  jM                  |      s Y w xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   _xY w# tl        $ r t)        d1      w xY w)Cz
    Given the source of the module, convert it to a Jinja2 template to insert
    module code and return whether it's a new or old style module.
    oldbinarynewrr   s(   from ansible.module_utils.basic import *
powershells,   #Requires -Module Ansible.ModuleUtils.Legacys   #Requires -Modules   #Requires -Versions   #AnsibleRequires -OSVersions   #AnsibleRequires -Powershells   #AnsibleRequires -CSharpUtiljsonargss	   WANT_JSONnon_native_want_jsonN)rY  r^  rZ  z)ANSIBALLZ: Could not determine module FQNzansible.modules.%sr   r   i  tzinfoz%cz7Cannot create zipfile due to pre-1980 configured date: )ANSIBLE_MODULE_ARGST)clsvault_to_textzDUnable to pass options to module, they must be JSON serializable: %szOBad module compression string specified: %s.  Using ZIP_STORED (no compression)ansiballz_cache-z"ANSIBALLZ: using cached module: %srg   zANSIBALLZ: Using lock for %sz$ANSIBALLZ: Using generic lock for %szANSIBALLZ: Acquiring lockzANSIBALLZ: Lock acquired: %szANSIBALLZ: Creating modulew)moder  z&ANSIBALLZ: Writing module into payloadzANSIBALLZ: Writing modulez-partwbzANSIBALLZ: Renaming modulezANSIBALLZ: Done creating modulez$ANSIBALLZ: Reading module after lockzvA different worker process failed to create module file. Look at traceback for that process for debugging information.r  r  z/usr/bin/pythonr   PYTHON_MODULE_RLIMIT_NOFILErt   )rlimit_nofiler   _ANSIBLE_COVERAGE_CONFIG_ANSIBLE_COVERAGE_OUTPUT)coverage_configcoverage_output)	zipdataansible_moduler6   paramsr   codingr  coveragerlimitz#!powershell,s   syslog.ansible_syslog_facilitys   syslog.LOG_USER)OrE  REPLACERreplaceNEW_STYLE_PYTHON_MODULE_RErI  REPLACER_WINDOWSre
IGNORECASEREPLACER_JSONARGSr   rO  r   r   debugr  r  datetimetimezoneutcstrftimer   dictreprjsondumpsr   	TypeErrorr   getattrr  AttributeErrorr#  
ZIP_STOREDrh   ri   r%   r   DEFAULT_LOCAL_TMPrj   rl   rm   r   idZipFiler2  rW  closebase64	b64encodegetvaluemakedirsOSErrorwriterenameIOErrorr   _extract_interpreterr   r   r   rE   intr   ANSIBALLZ_RLIMIT_TEMPLATEenvironr   ANSIBALLZ_COVERAGE_TEMPLATE!ANSIBALLZ_COVERAGE_CHECK_TEMPLATEr   ACTIVE_ANSIBALLZ_TEMPLATEENCODING_STRINGps_manifest_create_powershell_wrapperREPLACER_VERSIONr   REPLACER_COMPLEXREPLACER_SELINUXDEFAULT_SELINUX_SPECIAL_FSDEFAULT_SYSLOG_FACILITY)-module_namerB  rL  module_argsr   r   module_compressionasync_timeoutbecomebecome_methodbecome_userbecome_passwordbecome_flagsenvironmentr   module_substylemodule_styler   outputrM  r  date_stringrq  python_repred_paramsr)  compression_methodlookup_pathcached_module_filenamero  r'  lock	zipoutputr  fo_interpretero_argsr   rj  rt  rm  rn  rs  module_args_jsonpython_repred_argsfacilitys-                                                r*   _find_module_utilsr  /  s    &+*Ol - )11,	]	" "%--h8cd	#	*	*=	9"	]	*&%--.>@op	'	Fyy.r}}Myy7Vyy8-Wyy8-W&	m	+$		&)??,G @@lG33YF	?3K@ ("KKM"1%	Q<$"++YUx?P?P?T?TU^^_cdK!XYdXefgg+7	v#'

6?Qae(f#g 	4!(2D!E
 ggll1#6#68IJ!#kFWYk;l!m77>>01MM>AWWX,d3 -{%**,- - 0CCC<{JK)<<[I D{RS)<<TBMM56 ,E<r$xGH ww~~&<=MM">? '	I J\]B %[2C]TVXabMM"JK&r96GWHHJ$..y/A/A/CDG 77>>+6& KK4 MM"=>4w>E )() MM">?II4w>@VWMM"CDY,E\ DEh4d; +q"#&&(+
 '*?@ 4] Cv .M+M9gvgvw 112O[d1e-- 0 0 ?@M.+2 F F**..)CD jj)CDO 7$3$3:  =HX7$&('"
;
 

 
 
	 )	L	(
 " $>>;[6=+/96G
 
J	&#DJJ{@Rbf$gh &d+;&<=%--.>kIZ@[\%--.>@RS%--.>RSRnRnIo@pq &--.?AQR7PRSRkRk)l  vK  !L  L%--.@(K<11  ? 	AB0;>?"  	vehqrshttuu	v
  	4OOn  rD  D  E!(!3!3	4- -Z  ' & $&77>>+#> % $?&) )I,E ,Eh+ + h& (g h hhs    ^ '%_ _/ 5`'C=a1`4#$a1a$Aa1b a>!b #__	_,_''_,/1`$#`$'`14)a!a1 a!!a1$a.	)a11a;>bb b c                   d}g }| j                  dd      }|d   j                  d      rZ|d   j                         }t        j                   t	        |dd d            }|D cg c]  }t	        |d       }}|d   }|dd }||fS c c}w )	z
    Used to extract shebang expression from binary module data and return a text
    string with the shebang, or None if no shebang is detected.
    N   
rX   r   s   #!r   r  r  )rS   r#   r"   shlexr   )rB  r   r>   b_lines	b_shebang	cli_splitas          r*   r  r  %  s     KD!!%+GqzU#AJ$$&	 KK	!">S TU	 HQQ!WQ'<=Q	Ql}	 Rs   %B	c                0   |i n|}|i n|}t        |d      5 }|j                         }ddd       t        | |||||||||	|
|||      \  }}}|dk(  r||t        |d      fS |t	        |      \  }}|t        |||||      \  }}|j                  dd	      }||k7  rt        |d
d      |d<   t        j                  j                  |      j                  d      r|j                  d	t               dj                  |      }|||fS # 1 sw Y   xY w)a  
    Used to insert chunks of code into modules before transfer rather than
    doing regular python imports.  This allows for more efficient transfer in
    a non-bootstrapping scenario by not moving extra files over the wire and
    also takes care of embedding arguments in the transferred modules.

    This version is done in such a way that local imports can still be
    used in the module code, so IDEs don't have to be aware of what is going on.

    Example:

    from ansible.module_utils.basic import *

       ... will result in the insertion of basic.py into the module
       from the module_utils/ directory in the source tree.

    For powershell, this code effectively no-ops, as the exec wrapper requires access to a number of
    properties not available here.

    Nrg   )r  r  r  r  r  r  r  r   rZ  passthru)	nonstringrh  r  rX   r  )r  r  r   rr   )rl   rm   r  r   r  r   rS   r   rh   ri   r~   r#   insertb_ENCODING_STRINGr%   )r  rL  r  r   r   r  r  r  r  r  r  r  r  r   r  rB  r  r   r   r>   new_interpreterr  s                         r*   modify_moduler  <  sb   ,  'YI#+"K	k4	  !A !
 .@]\gitv  BI  K]N[dj  {HLWix  HTLWix.z*]L'
 x|WW
-STT	0?T"'3KGUYkz'{$G_ $))%3Go-%g6KWab
ww,77	Bq"34!JJw/M<11=! !s   DDc                ,   |d}t         j                  |       g }n|j                  | g       }i }i }t        |t              r|D ]  }	|j                  |	        |j                  |      }|D ]b  }	|	j                  d      s|	j                  d      d   }
|
|v s.|j                  |j                  d|
z        xs i j                                d |j                  |j                  | i       j                                |j                  |       |S )NzFinding module_defaults for action %s. The caller has not passed the action_groups, so any that may include this action will be ignored.)r   zgroup/r   zgroup/%s)
r   r#  r   rE   rF   updater   r#   rS   copy)actionr>   defaultsr   action_groupsr   group_namestmp_argsmodule_defaultsdefault
group_names              r*   get_action_args_with_defaultsr  v  s   < 	
 	C #''3HO (D! 	,G""7+	, &&7O" ]h' x04J[(!4!4Z*5L!M!SQS Y Y [\	] OOO''388:; OODOr,   r   r`   )
Nr  r   FNNNNNF)_
__future__r   rC   r  r  r  rh   r  r  r  r{  r   r   r   r   ior   ansible.releaser   r	   r   r
   r   ansible.errorsr   &ansible.executor.interpreter_discoveryr   ansible.executor.powershellr   r   ansible.module_utils.common.jsonr   +ansible.module_utils.common.text.convertersr   r   r   ansible.plugins.loaderr   2ansible.utils.collection_loader._collection_finderr   r   ansible.executorr   ansible.utils.displayr   collectionsr   importlib.utilr   importlib.machineryr   r   rw  r  r  rz  r}  r  r  r  ri   r%   dirname__file__r  ANSIBALLZ_TEMPLATEr  r  r  r+   DEFAULT_KEEP_REMOTE_FILESr  site_packagesr  escaperH  rJ  ry  NodeVisitorr.   rp   rR   r   r   r   r   r  r2  rE  rO  rW  r  r  r  r  r   r,   r*   <module>r     s5  & # 
    	    	  ' '  3 " ' T F ? T T 6 i
 0 ) "  
)$%>  AF  G 0- A ) ; 5  -.  WW\\"''//(";T>R C J ,% ! "  !3 !00B C
 0I JK!rzz"OR[RTR[R[\iRj"jk RZZ kl  (RZZ)	 H!coo H!V 8=wPU 6$r@/ @/J'3 'T5"7 5pqBh2B
F pus2l. LQ DI72t#r,   