HEX
Server: Apache
System: Linux server2.voipitup.com.au 4.18.0-553.109.1.lve.el8.x86_64 #1 SMP Thu Mar 5 20:23:46 UTC 2026 x86_64
User: posscale (1027)
PHP: 8.2.30
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //opt/saltstack/salt/lib/python3.10/site-packages/salt/client/__pycache__/__init__.cpython-310.pyc
o

�N�g�9�@s�dZddlZddlZddlZddlZddlZddlmZddlZddl	Zddl
ZddlZddlZddl
ZddlZddlmZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZmZmZmZm Z m!Z!m"Z"dZ#zddl$Z%dZ#Wn	e&y�Ynwe�'e(�Z)ej*�+ej,d�dddddfdd	�Z-Gd
d�d�Z.Gdd
�d
e/�Z0Gdd�d�Z1Gdd�d�Z2dS)a'
The client module is used to create a client connection to the publisher
The data structure needs to be:
    {'enc': 'clear',
     'load': {'fun': '<mod.callable>',
              'arg':, ('arg1', 'arg2', ...),
              'tgt': '<glob or id>',
              'key': '<read in the key file>'}
�N)�datetime)�AuthenticationError�AuthorizationError�EauthAuthenticationError�PublishError�SaltClientError�SaltInvocationError�SaltReqTimeoutErrorFT�mastercCs0|r|}n
ddl}|j�|�}t|||||d�S)a�
    .. versionadded:: 2014.7.0

    Read in the config and return the correct LocalClient object based on
    the configured transport

    :param str c_path: Path of config file to use for opts.

                       The default value is None.

    :param bool mopts: When provided the local client will use this dictionary of
                       options insead of loading a config file from the value
                       of c_path.

                       The default value is None.

    :param str skip_perm_errors: Ignore permissions errors while loading keys.

                                 The default value is False.

    :param IOLoop io_loop: io_loop used for events.
                           Pass in an io_loop if you want asynchronous
                           operation for obtaining events. Eg use of
                           set_event_handler() API. Otherwise, operation
                           will be synchronous.

    :param bool keep_loop: Do not destroy the event loop when closing the event
                           subsriber.

    :param bool auto_reconnect: When True the event subscriber will reconnect
                                automatically if a disconnect error is raised.

    .. versionadded:: 3004
    :param bool listen: Listen for events indefinitly. When option is set the
                        LocalClient object will listen for events until it's
                        destroy method is called.

                        The default value is False.
    rN)�mopts�skip_perm_errors�io_loop�auto_reconnect�listen)�salt.config�config�
client_config�LocalClient)�c_pathrrr
rr�opts�salt�r�H/opt/saltstack/salt/lib/python3.10/site-packages/salt/client/__init__.py�get_local_clientCs/�rc@sReZdZdZej�ejd�ddddddfdd�Z	dd�Z
d	d
�Zdd�ZdUdd�Z
dUdd�Z							dVdd�Zdd�Zejjjj							
	dWdd��Z	dXdd�Z								dYdd�Z					 dZd!d"�Z							d[d#d$�Z							d\d%d&�Z					d]d'd(�Z							d^d)d*�Z						d_d+d,�Z		-			d`d.d/�Zdad0d1�Z d2d3�Z!		-			
dbd4d5�Z"dad6d7�Z#dad8d9�Z$d:d;�Z%		-				dcd<d=�Z&		-					ddd>d?�Z'dad@dA�Z(dBdC�Z)dDdE�Z*					F	dedGdH�Z+ejjjj					F		
dfdIdJ��Z,dKdL�Z-dMdN�Z.dOdP�Z/dQdR�Z0dSdT�Z1dS)gra>
    The interface used by the :command:`salt` CLI tool on the Salt Master

    ``LocalClient`` is used to send a command to Salt minions to execute
    :ref:`execution modules <all-salt.modules>` and return the results to the
    Salt Master.

    Importing and using ``LocalClient`` must be done on the same machine as the
    Salt Master and it must be done using the same user that the Salt Master is
    running as. (Unless :conf_master:`external_auth` is configured and
    authentication credentials are included in the execution).

    .. note::
        The LocalClient uses a Tornado IOLoop, this can create issues when
        using the LocalClient inside an existing IOLoop. If creating the
        LocalClient in partnership with another IOLoop either create the
        IOLoop before creating the LocalClient, or when creating the IOLoop
        use ioloop.current() which will return the ioloop created by
        LocalClient.

    .. code-block:: python

        import salt.client

        local = salt.client.LocalClient()
        local.cmd('*', 'test.fib', [10])

    r
NFcCs�|r||_ntj�|�rt�d|jj|�tj	�
|�|_tjj�
�|_||_|��|_||_||_tjjjd|jd|j|j||d�|_tj�|j�|_tjj|j|jd�|_tj�|j|j�|_dS)a�
        :param str c_path: Path of config file to use for opts.

                           The default value is None.

        :param bool mopts: When provided the local client will use this dictionary of
                           options insead of loading a config file from the value
                           of c_path.

                           The default value is None.

        :param str skip_perm_errors: Ignore permissions errors while loading keys.

                                     The default value is False.

        :param IOLoop io_loop: io_loop used for events.
                               Pass in an io_loop if you want asynchronous
                               operation for obtaining events. Eg use of
                               set_event_handler() API. Otherwise, operation
                               will be synchronous.

        :param bool keep_loop: Do not destroy the event loop when closing the event
                               subsriber.

        :param bool auto_reconnect: When True the event subscriber will reconnect
                                    automatically if a disconnect error is raised.

        .. versionadded:: 3004
        :param bool listen: Listen for events indefinitly. When option is set the
                            LocalClient object will listen for events until it's
                            destroy method is called.

                            The default value is False.
        zP%s expects a file path not a directory path(%s) to its 'c_path' keyword argumentr
�sock_dir)rrr
�	keep_loop)�utilsN)r�os�path�isdir�log�warning�	__class__�__name__rrrr�userZget_specific_user�	salt_userr�_LocalClient__read_master_key�keyrr�event�	get_event�loaderZminion_mods�	functions�	returners)�selfrrrr
rrrrrr�__init__�s2,�
�zLocalClient.__init__c	Cs�|j}|dkr|j�dd�dkr|j�dd�}|�d�r#|j�dd�}tjj��r/|�dd�}t	j
�|jdd|�d��}z2tjj�
|jd||j�tjj�|d	��}tjj�|���Wd
�WS1shwYWd
Sttfy{YdSw)z@
        Read in the rotating master authentication key
        �rootr$Zsudo_�\�_Zcachedir�.�_key�rN�)r%r�get�
startswithrr�platformZ
is_windows�replacerr�joinZverifyZcheck_path_traversalr�filesZfopenZstringutilsZ
to_unicode�read�OSErrorr)r-Zkey_user�keyfiler'rrrZ__read_master_key�s&
�(��zLocalClient.__read_master_keyc
CsZtj�|jd�}z|�|�WStjjy,}ztd|���gWYd}~Sd}~ww)z?
        convert a seco.range range into a list target
        Zrange_serverzRange server exception: N)�seco�rangeZRanger�expandZRangeException�print)r-�tgtZrange_�errrrr�_convert_range_to_lists��z"LocalClient._convert_range_to_listcCs\|dur	|jdSt|t�r|St|t�r)zt|�WSty(|jdYSw|jdS)z+
        Return the timeout to use
        N�timeout)r�
isinstance�int�str�
ValueError)r-rFrrr�_get_timeouts



�
zLocalClient._get_timeoutTcKs^t�d|�t|�d|jd��}|j|df|g|||d�|��}d|vr-|j�|d�|S)z:
        Return the information about a given job
        z(Checking whether jid %s is still running�gather_job_timeoutzsaltutil.find_job)�arg�tgt_typerFr�jid)r �debugrHr6r�run_jobr(�	subscribe)r-rOrCrNr�kwargsrF�pub_datarrr�gather_job_infos ���
zLocalClient.gather_job_infocCs�|dkrtd��d|vrt|d�t�d|d�iSd|vr"iS|ddkr.td�iS|j�d�s>|d	s>td
�iS|sB|S|j�d�rT|j�d�|d�d�|j�d
�|d��|S)zX
        Common checks on the pub_data data structure returned from running pub
        r5z�Failed to authenticate! This is most likely because this user is not permitted to execute commands, but there is a small possibility that a disk error occurred (check disk/inode usage).�errorz_check_pub_data() error: %srO�0z<Failed to connect to the Master, is the Salt Master running?�
order_masters�minionszHNo minions matched the target. No command was sent, no jid was assigned.zsyndic/.*/{}�regex�salt/job/{})	rrBr rPrr6r(rR�format)r-rTrrrr�_check_pub_data5s2��zLocalClient._check_pub_datar�globr5c

Ks�tjj�||�}z|j|||||f||�|�|	d�|
��}Wn2ty)td��ty5}z�d}~wtyA}z�d}~wt	yP}
zt|
��d}
~
ww|j
||	d�S)a
        Asynchronously send a command to connected minions

        Prep the job directory and publish a command to any targeted minions.

        :return: A dictionary of (validated) ``pub_data`` or an empty
            dictionary on failure. The ``pub_data`` contains the job ID and a
            list of all minions that are expected to return data.

        .. code-block:: python

            >>> local.run_job('*', 'test.sleep', [300])
            {'jid': '20131219215650131543', 'minions': ['jerry']}
        )rOrFr�:The salt master could not be contacted. Is master running?N�r)rr�args�condition_input�pubrKrrr�	Exceptionr])r-rC�funrMrN�retrFrO�kwargrrSrTrD�general_exceptionrrrrQds<��	
������zLocalClient.run_jobcCs"tjj�|j�j||d�}|dS)N)rNrY)rrrY�	CkMinionsrZ
check_minions)r-rCZ	expr_formZ_resrrr�gather_minions�s�zLocalClient.gather_minionsc
ks��tjj�||�}z|j|||||f||�|�|
|	d�|��V}Wn8ty,td��ty;}
zt|
��d}
~
wtyJ}
zt|
��d}
~
wt	yY}zt|��d}~wwtj
jj�
|j||	d���)a
        Asynchronously send a command to connected minions

        Prep the job directory and publish a command to any targeted minions.

        :return: A dictionary of (validated) ``pub_data`` or an empty
            dictionary on failure. The ``pub_data`` contains the job ID and a
            list of all minions that are expected to return data.

        .. code-block:: python

            >>> local.run_job_async('*', 'test.sleep', [300])
            {'jid': '20131219215650131543', 'minions': ['jerry']}
        )rOrFr
rr_Nr`)rrrarb�	pub_asyncrKrrrrd�ext�tornado�gen�Returnr])r-rCrerMrNrfrFrOrgrr
rSrTrDrhrrr�
run_job_async�s@���
������zLocalClient.run_job_asyncc
KsB|j|||||f||dd�|��}	z|	dWSty YdSw)aT
        Asynchronously send a command to connected minions

        The function signature is the same as :py:meth:`cmd` with the
        following exceptions.

        :returns: A job ID or 0 on failure.

        .. code-block:: python

            >>> local.cmd_async('*', 'test.sleep', [300])
            '20131219215921857715'
        F)rOrgrrOr)rQ�KeyError)
r-rCrerMrNrfrOrgrSrTrrr�	cmd_async�s
���
�zLocalClient.cmd_async�cKs�|�d|�}|j|dfd|i|��}t|�}
t�|
�g}|
D]}|||vr,|�|�t|�|kr4nq|j}|r=|j}||||fd|||	|
d�|��S)a�
        Execute a command on a random subset of the targeted systems

        The function signature is the same as :py:meth:`cmd` with the
        following exceptions.

        :param subset: The number of systems to execute on
        :param cli: When this is set to True, a generator is returned,
                    otherwise a dictionary of the minion returns is returned

        .. code-block:: python

            >>> SLC.cmd_subset('*', 'test.ping', subset=1)
            {'jerry': True}
        �sub�sys.list_functionsrN�list)rNrfrg�progress�full_return)�pop�cmdrv�random�shuffle�append�len�cmd_cli)r-rCrerMrNrfrgZsubset�clirwrxrSZ
minion_retrYZf_tgt�minion�funcrrr�
cmd_subset�s6

���	�zLocalClient.cmd_subset�10%c
ksB�ddl}	ddl}	|	jj�||�}|||||||�d|j�dd��|�dd�d�}
d|vr3|d|
d<d|vr=|d|
d<d	|vrIt|d	�|
d	<i}d
|vrV|�d
�|d
<d|vra|�d�|d<d|vrl|�d�|d<d
|vrw|�d
�|d
<|j�	�D]\}}
||
vr�|
|
|<q||	j
jj|
|dd�}|�
�D]\}}|Vq�dS)a5
        Iteratively execute a command on subsets of minions at a time

        The function signature is the same as :py:meth:`cmd` with the
        following exceptions.

        :param batch: The batch identifier of systems to execute on

        :returns: A generator of minion returns

        .. code-block:: python

            >>> returns = local.cmd_batch('*', 'state.highstate', batch='10%')
            >>> for ret in returns:
            ...     print(ret)
            {'jerry': {...}}
            {'dave': {...}}
            {'stewart': {...}}
        rN�failhardF�raw)rCrerMrNrf�batchr�r�rFrLZ
batch_wait�eauth�username�password�tokenT)r��quiet)Zsalt.cli.batch�salt.utils.argsrrarbr6rrHry�itemsr�r�ZBatch�run)r-rCrerMrNrfrgr�rSrrr�r'�valr1rrr�	cmd_batch.sH�#
���zLocalClient.cmd_batchc
Ks�|jj}zm|j|||||||f|	dd�|
��}|s$|W|s#|j��SSi}|j|d|d|�|�||fi|
��D]}
|
rS|
��D]\}}|rJ|n|�di�||<qBq:tt	|d�t	|��D]}d||<q`|W|sq|j��SS|sz|j��ww)a�
        Synchronously execute a command on targeted minions

        The cmd method will execute and wait for the timeout period for all
        minions to reply, then it will return all minion data at once.

        .. code-block:: python

            >>> import salt.client
            >>> local = salt.client.LocalClient()
            >>> local.cmd('*', 'cmd.run', ['whoami'])
            {'jerry': 'root'}

        With extra keyword arguments for the command function to be run:

        .. code-block:: python

            local.cmd('*', 'test.arg', ['arg1', 'arg2'], kwarg={'foo': 'bar'})

        Compound commands can be used for multiple executions in a single
        publish. Function names and function arguments are provided in separate
        lists but the index values must correlate and an empty list must be
        used if no arguments are required.

        .. code-block:: python

            >>> local.cmd('*', [
                    'grains.items',
                    'sys.doc',
                    'cmd.run',
                ],
                [
                    [],
                    [],
                    ['uptime'],
                ])

        :param tgt: Which minions to target for the execution. Default is shell
            glob. Modified by the ``tgt_type`` option.
        :type tgt: string or list

        :param fun: The module and function to call on the specified minions of
            the form ``module.function``. For example ``test.ping`` or
            ``grains.items``.

            Compound commands
                Multiple functions may be called in a single publish by
                passing a list of commands. This can dramatically lower
                overhead and speed up the application communicating with Salt.

                This requires that the ``arg`` param is a list of lists. The
                ``fun`` list and the ``arg`` list must correlate by index
                meaning a function that does not take arguments must still have
                a corresponding empty list at the expected index.
        :type fun: string or list of strings

        :param arg: A list of arguments to pass to the remote function. If the
            function takes no arguments ``arg`` may be omitted except when
            executing a compound command.
        :type arg: list or list-of-lists

        :param timeout: Seconds to wait after the last minion returns but
            before all minions return.

        :param tgt_type: The type of ``tgt``. Allowed values:

            * ``glob`` - Bash glob completion - Default
            * ``pcre`` - Perl style regular expression
            * ``list`` - Python list of hosts
            * ``grain`` - Match based on a grain comparison
            * ``grain_pcre`` - Grain comparison with a regex
            * ``pillar`` - Pillar data comparison
            * ``pillar_pcre`` - Pillar data comparison with a regex
            * ``nodegroup`` - Match on nodegroup
            * ``range`` - Use a Range server for matching
            * ``compound`` - Pass a compound match string
            * ``ipcidr`` - Match based on Subnet (CIDR notation) or IPv4 address.

            .. versionchanged:: 2017.7.0
                Renamed from ``expr_form`` to ``tgt_type``

        :param ret: The returner to use. The value passed can be single
            returner, or a comma delimited list of returners to call in order
            on the minions

        :param kwarg: A dictionary with keyword arguments for the function.

        :param full_return: Output the job return only (default) or the full
            return including exit code and other job metadata.

        :param kwargs: Optional keyword arguments.
            Authentication credentials may be passed when using
            :conf_master:`external_auth`.

            For example: ``local.cmd('*', 'test.ping', username='saltdev',
            password='saltdev', eauth='pam')``.
            Or: ``local.cmd('*', 'test.ping',
            token='5871821ea51754fdcea8153c1c745433')``

        :returns: A dictionary with the result of the execution, keyed by
            minion ID. A compound command will return a sub-dictionary keyed by
            function name.
        T�rgrrOrYrfF)
r(�cpubrQ�	close_pub�get_cli_event_returnsrKr�r6rv�set)r-rCrerMrFrNrfrOrxrgrS�
was_listeningrT�fn_retZmid�data�failedrrrrzxsVt��
�
���
�	�
��zLocalClient.cmdc

ks��|jj}z[|j||||||f|dd�|
��|_|js |jVn5z#|j|jd|jd|�|�||||	fi|
��D]}|s>q9|Vq9WntyTtd�|jd���wW|s_|j�	�dSdS|si|j�	�ww)am
        Used by the :command:`salt` CLI. This method returns minion returns as
        they come back and attempts to block until all minions return.

        The function signature is the same as :py:meth:`cmd` with the
        following exceptions.

        :param verbose: Print extra information about the running command
        :returns: A generator
        Tr�rOrYa
This job's jid is: {0}
Exiting gracefully on Ctrl-c
The minions may not have all finished running and any remaining minions will return upon completion. To look up the return data for this job later, run the following command:

salt-run jobs.lookup_jid {0}N)
r(r�rQrTr�rK�KeyboardInterrupt�
SystemExitr\r�)
r-rCrerMrFrNrf�verbosergrwrSr�r�rrrrs\���	�
�
�������zLocalClient.cmd_clicks��|jj}	zP|j||||||f|dd�|��}
|
s|
Vn-|�d�r%|
V|j|
d|
df|�|�||d�|��D]}|s?q:|Vq:|�|
d�W|	sT|j��dSdS|	s^|j��ww)a�
        Yields the individual minion returns as they come in

        The function signature is the same as :py:meth:`cmd` with the
        following exceptions.

        Normally :py:meth:`cmd_iter` does not yield results for minions that
        are not connected. If you want it to return results for disconnected
        minions set `expect_minions=True` in `kwargs`.

        :return: A generator yielding the individual minion returns

        .. code-block:: python

            >>> ret = local.cmd_iter('*', 'test.ping')
            >>> for i in ret:
            ...     print(i)
            {'jerry': {'ret': True}}
            {'dave': {'ret': True}}
            {'stewart': {'ret': True}}
        Tr�Zyield_pub_datarOrY)rFrCrNN)r(r�rQr6�get_iter_returnsrK�_clean_up_subscriptionsr�)r-rCrerMrFrNrfrgrSr�rTr�rrr�cmd_iter[sP� ��	�
��
����zLocalClient.cmd_iterc
ks��|jj}zX|j||||||f|dd�|
��}|s|Vn5|j|d|df|||dd�|
��D]}
|
rGt||	g�rG|
D]
}|d|
|d<q<|
Vq0|�|d�W|s\|j��dSdS|sf|j��ww)a�
        Yields the individual minion returns as they come in, or None
            when no returns are available.

        The function signature is the same as :py:meth:`cmd` with the
        following exceptions.

        :returns: A generator yielding the individual minion returns, or None
            when no returns are available. This allows for actions to be
            injected in between minion returns.

        .. code-block:: python

            >>> ret = local.cmd_iter_no_block('*', 'test.ping')
            >>> for i in ret:
            ...     print(i)
            None
            {'jerry': {'ret': True}}
            {'dave': {'ret': True}}
            None
            {'stewart': {'ret': True}}
        Tr�rOrYF)rFrCrN�blockN)r(r�rQr��anyr�r�)r-rCrerMrFrNrfrg�show_jidr�rSr�rTr�r�rrr�cmd_iter_no_block�sP�#��	���
�	���zLocalClient.cmd_iter_no_blockc	Ks�|jj}
z5|j||||||f|dd�|	��}|s#|W|
s"|j��SS|�|d|d||||�W|
s9|j��SS|
sB|j��ww)z3
        Execute a salt command and return
        Tr�rOrY)r(r�rQr��get_cli_static_event_returns)r-rCrerMrFrNrfr�rgrSr�rTrrr�cmd_full_return�s8��	������zLocalClient.cmd_full_return�*cks�|rd|��}	t|	�tdt|	�d�n	|r td|���|dur)|jd}i}
t|�}t�}|j|||d�}|�|�}
|
ikrM|�t|
��|
Vt|�|��t|�krZdS|D]#}|ikrl|�t|��|Vt|�|��t|�kr|�|�dSq\dS)z�
        Starts a watcher looking at the return data for a specified JID

        :returns: all of the information for the JID
        �Executing job with jid �-�
�jid: NrF�rF)	rBr~rr��get_event_iter_returns�get_cache_returns�update�intersectionr�)r-rOrYrFrCrNr�r�rS�msgZfret�found�
event_iterrfr(rrr�get_cli_returnss8�



��zLocalClient.get_cli_returnsccs&�	|jjd||dd|jd�}|Vq)a4
        Raw function to just return events of jid excluding timeout logic

        Yield either the raw event data or None

        Pass a list of additional regular expressions as `tags_regex` to search
        the event bus for non-return data, such as minion lists returned from
        syndics.
        T�{�G�z�?)�wait�tag�
match_type�fullZno_blockr)r(r)r)r-r�r�r�rrr�get_returns_no_blockCs���z LocalClient.get_returns_no_blockcCs|jd�|jd�|�S)N�{}.get_load�master_job_cache)r,r\r)r-rOrrr�returns_for_jobYszLocalClient.returns_for_jobcks�t|t�st|t�r|h}n
t|ttf�rtt|��}|dur%|jd}t|�d|jd��}	tt���}
i}t�}t�}
z|�	|�sOt
�d�iVWdSWntyk}zt
jd|t
jd�WYd}~nd}~wwd}|jdr}|�d	|��d
�}n|�d|���}g}t�}t��|}t��|jd}d
}t
�d||t�|����	|D]�}|dur�n�d|�di�vr�dddd�iVd|�di�vr�|�|dd�d|�di�vr�|
�|dd�q�|d�d|�d��s�t
�d|d�q�d|dv�r
t
�d|d�q�|�dd��r|�|dd�|Vq�|�|dd�|ddd|ddii}d|dv�rJ|dd||ddd<d|dv�r_|dd||ddd<d |dv�rt|dd ||ddd <|�d!d��r�||dd�|d�t
�d"||dd�|Vq�t|�|��t|�k�r�|jd�s�t
�d#||��n�t|�|��t|�k�r�|jd�r�t|�t|�k�r�t|�d$k�r�t��|k�rݐno||D]}||v�r�t��|||<�q�t��|k�r4|�r4|j|t||�d%fi|��}d}d |v�rg}n
|�d&�|d ��}t��|	}|jd�r4||j�dd'�7}|D]�}|du�r?n�z!|ddd$k�r_t
�d(|dd�|�|dd�Wn�Wn+t�y�}zt|��d)�}|dk�r{t
�d*�nt
�d+|�WYd}~nd}~ww|�|d �d|�di�v�r�|�|dd��q6d,|�di�v�r�|�|d,��q6d|�di�v�rĐq6|ddik�rϐq6t|ddt��r�t
�d-|��q6d|ddv�r�|dddik�r��q6|dd|v�r	|�|dd�t��|||dd<d
}�q6t��}||k�o$|}|�r;||D]}|||k�r9d}n�q,|�r?n
|�rHt�d.�ndVq�|�r[|D]	}|j� |��qQ|�rot||�D]
}|d/d
iiV�qd|
|8}
|
�r�|
D]}|d/d
iiV�qxdSdS)0z�
        Watch the event system and return job data as it comes in

        :returns: all of the information for the JID
        NrFrL�jid does not existzReturner unavailable: %s)Zexc_info_on_loglevelFrXz(salt/job|syndic/.*)/rZ�	salt/job/Zsyndic_waitTz9get_iter_returns for jid %s sent to %s will timeout at %srVr�rzAuthorization error occurred.)�name�messagerY�missingr�z/ret/zSkipping non return event: %s�returnzMalformed event return: %sr��idrf�out�retcoderOZ	_cmd_metazjid %s return from %szjid %s found all minions %srrvr[�z&saltutil returning errors on minion %sz'"z"retcode missing from client returnzcPassing on saltutil error. Key '%s' missing from client return. This may be an error in the client.Zsyndicz!unexpected return from minion: %sr�r�)!rGr�rIrv�tuplerrHr6�timer�r r!rd�logging�DEBUGr�rPr�
fromtimestampr�r7�addr~r�rUr\rV�removerq�strip�sleepr(�unsubscribe)r-rOrYrFrCrN�expect_minionsr�rSrL�startZminion_timeoutsr�r��excZ	last_timeZret_iterZ
jinfo_iterZ	open_jids�
timeout_atZgather_syndic_waitZminions_runningr�rf�id_ZjinfoZmissing_key�nowZdoner�rrrr�\sf�


�

����
�����
���
�
��
������7�zLocalClient.get_iter_returnsc
Cs�t|�}|dur
|jd}tt���}||}t�d||t�|����t�}i}z|jd�	|jd�|�ikrAt�
d�|WSWntyY}ztd�	|jd|���d}~ww	|tt���}	t
d	|	�}
|jj|
||jd
�}|dur�d|vr�|�|d�|d||d<t|�|��t|�kr�t�d
|�	|SqZt|�|��t|�kr�t�d
|�	|Stt���|kr�t�d|||�	|St�d�q[)�U
        Get the returns for the command line interface via the event system
        NrFz4get_returns for jid %s sent to %s will timeout at %sr�r�r�zJMaster job cache returner [{}] failed to verify jid. Exception details: {}Tr��rr�r�zjid %s found all minionsz(jid %s minions %s did not return in timer�)r�rrHr�r rPrr�r,r\r!rdr�maxr(r)rr�r~r��infor�)r-rOrYrFr�r�r�rfr��	time_leftr�r�rrr�get_returnshsf
��
����

��
�
��zLocalClient.get_returnsc
Csri}|j|||d�}z|jd�|jd�|�}Wnty0}ztd�|jd|���d}~ww|D];}i}	d||vrG||�d�|	d<n	||�d�|	d<d||vr^||d|	d<||vrj||�|	�q3|	||<q3tt	|��
|��t|�kr~|S|D]6}
|
ikr�t�d	�q�|
�
�D]\}}	||vr�||�|	�q�|	||<q�tt	|��
|��t|�kr�|Sq�|S)
z�
        This method starts off a watcher looking at the return data for
        a specified jid, it returns all of the information for the jid
        r��
{}.get_jidr�z;Returner {} could not fetch jid data. Exception details: {}Nr�rfr��{�G�z�?)r�r,r\rrdrr6r�r~r�r�r�r�r�)r-rOrYrFrfr�r�r�r��m_dataZ	event_retrrr�get_full_returns�sL�
����


�zLocalClient.get_full_returnsc
Cs�i}z|jd�|jd�|�}Wnty(}ztd�|jd|���d}~ww|D];}i}d||vr?||�d�|d<n	||�d�|d<d||vrV||d|d<||vrb||�|�q+|||<q+|S)zO
        Execute a single pass to gather the contents of the job cache
        r�r�zXCould not examine master job cache. Error occurred in {} returner. Exception details: {}Nr�rfr�)r,r\rrdrr6r�)r-rOrfr�r�r�r�rrrr��s.����
zLocalClient.get_cache_returnsc	
Csht�d�t|�}|rd|��}	t|	�tdt|	�d�n	|r(td|���|dur1|jd}tt���}
|
|}t�}i}
z|jd�	|jd	�|�ikrXt�
d
�|
WSWntyp}ztd�	|jd	|���d}~ww	|tt���}t
d
|�}d|��}|jj|||jd�}|dur�d|vr�d|�di�vr�|�|dd�qq|�|d�d|di|
|d<|�dd�|
|dd<d|vr�|d|
|dd<t|�|��t|�kr�nNqqt|�|��t|�kr�nAtt���|k�r'|s�|�r&|j�dd��s|dv�r&t|�t|�k�r&tt|�|���}|D]
}ddd�|
|<�qnt�d�qr|�|�|
S)r�z1entered - function get_cli_static_event_returns()r�r�r�r�NrFr�r�r�zCLoad could not be retrieved from returner {}. Exception details: {}Tr�r�r�r�rYr�r�rf�successFr��minion_data_cache)r^Zpcrerv�	no_returnzMinion did not return)r�rfr�)r �tracer�rBr~rrHr�r,r\r!rdrr�r(r)rr6r�r�r��sortedrv�
differencer�r�)r-rOrYrFrCrNr��show_timeoutr�r�r�r�r�rfr�r�r�Zjid_tagr�Zfailr�rrrr��s�


�
�
����

�
�
�
+z(LocalClient.get_cli_static_event_returnsc
	ks��t�d�|rd|��}t|�tdt|�d�n	|	r%td|���d}d}
|j||f||||
�dd	�p:|p:|d
�|
��D]�}t�d|�|
d}
|rf|��D]\}}|�d
�duret|�|
d�VqR|��D]j\}}|�d
�dur�|dur�t	j
j�|j
���}|j
dr�t	j�|j
��d|��d�r�|r�||vr�|ddt	jjjd�iVqjtj�tj�|j
d|��s�|dd�|�t	jjjd�iVqjd|vr�td��||iVqjq@|�|�dS)r�zfunc get_cli_event_returns()r�r�r�r�Nrr�F)rFrCrNr�zreturn event: %sr�r�T)Zminion_count�return_countr�zminions/r�r�z&Minion did not return. [Not connected])r�rfr�Z
syndic_dirz�Minion did not return. [No response]
The minions may not have all finished running and any remaining minions will return upon completion. To look up the return data for this job later, run the following command:

salt-run jobs.lookup_jid {}rVzAuthorization error occurred)r r�rBr~r�ryrPr�r6rrrYrirZ
connected_ids�cache�factory�contains�defaultsZ	exitcodesZ
EX_GENERICrr�existsr:r\rr�)r-rOrYrFrCrNr�rwr�r�rSr�Zconnected_minionsr�rfr�Zmin_retrrrr�Ws��

��
������
�����	������0z!LocalClient.get_cli_event_returnsccs�t�d�|dur|jd}t��|}t�}|jd�|jd�|�ikr1t�d�iVdS	|jj	||j
d�}|dusEt��|krGdSd	|�d
i�vrPq1z||dkri|�|d�|dd
|dii}nWq1Wn	t
yuYq1wd|vr�|d||dd<|Vt�d�q2)zk
        Gather the return data from the event system, break hard when timeout
        is reached.
        z+entered - function get_event_iter_returns()NrFr�r�r�Tr�rYr�rOr�rfr�r�r�)r r�rr�r�r,r\r!r(r)rr6r�rqr�)r-rOrYrFr�r�r�rfrrrr��s@�

�
��
�z"LocalClient.get_event_iter_returnscCsF||jdvr|j�dd�}td|�d|����tjj�||jd�S)zD
        Resolve a nodegroup into its configured components
        Z
nodegroups�	conf_filezthe master config filezNode group z unavailable in )rr6rrrrYZnodegroup_comp)r-Zngr�rrr�_resolve_nodegroup�szLocalClient._resolve_nodegroupc
	Ks.|dkr|�|�}d}|dkrPt�}	t�d|�t|t�r!|��}|D]!}
|
�d�r?t|
�dkr?|�|
dd��}|	�	|�q#|	�
|
�q#t�d|	�d�|	�}|d	kr]tr]|�
|�}d
}|j�d�ru|rp|d�|jd�7}n|jd}d
||||j|||d�}|r�||d<|j|d<|jdr�||d<|S)zI
        Set up the payload_kwargs to be sent down to the master
        Z	nodegroupZcompoundz%compound resolution: original tgt: %szN@�Nz compound resolution: new_tgt: %s� r@rvZ
ext_job_cachez,{}Zpublish)rzrCrerMr'rNrfrOrSr$rX�to)r�rvr rPrGrI�splitr7r~�extendr}r:�	HAS_RANGErErr6r\r'r%)
r-rCrerMrNrfrOrFrSZnew_tgt�wordZresolved�payload_kwargsrrr�	_prep_pub�sJ




�

zLocalClient._prep_pub�c	Ks�|j�dd�dkr"tj�tj�|jdd��s"t�d|jd�t�|j	|||||||fi|	��}
d�
tjj
�|jd�t|jd	��}tjjjj|jd
|d���}z|r^|jj|d�s^t��|j|
|d�}
Wnty{}z	t�|�td
��d}~ww|
s�|��}||jkr�|
Wd�S||_|j|
d<|�|
�}
|
�dd�}|dur�t|t�r�|�dd�}|�dd�}|dkr�t|��|dkr�t|��t|��|
s�|
Wd�SWd�n1s�wY|
dd|
ddd�S)��
        Take the required arguments and publish the given command.
        Arguments:
            tgt:
                The tgt is a regex or a glob used to match up the ids on
                the minions. Salt works by always publishing every command
                to all of the minions and then the minions determine if
                the command is for them based on the tgt value.
            fun:
                The function name to be called on the remote host(s), this
                must be a string in the format "<modulename>.<function name>"
            arg:
                The arg option needs to be a tuple of arguments to pass
                to the calling function, if left blank
        Returns:
            jid:
                A string, as returned by the publisher, which is the job
                id, this will inform the client where to get the job results
            minions:
                A set, the targets that the tgt passed should match.
        �ipc_moder5�tcpr�publish_pull.ipc�4Unable to connect to the salt master publisher at %sztcp://{}:{}�	interface�ret_port�clear)�crypt�
master_urir��fSalt request timed out. The master is not responding. You may need to run your command with `--async` in order to bypass the congested event bus. With `--async`, the CLI tool will print the job id (jid) and exit immediately without listening for responses. You can then use `salt-run jobs.lookup_jid` to look up the results of the job in the job cache later.Nr'rVr�r�rr�loadrOrY�rOrY) rr6rrr�r:r rVrr�r\rr�network�
ip_bracketrI�channel�clientZ
ReqChannelr�r(�connect_pubr	�sendr&r'ryrG�dictrrr)r-rCrerMrNrfrOrFrrSr�rr
�payloadrDr'rV�err_name�err_msgrrrrc5sp"�����
�
���
�


�+�.zLocalClient.pubc
	ks��|j�dd�dkr#tj�tj�|jdd��s#t�d|jd�t�|j	|||||||fi|
��}dt
jj�
|jd�d	t|jd
�}t
jjjj|j|d|d���}
z|	rb|jj|d
�sbt��|
j||d
�V}Wntyvtd��w|s�|��}||jkr�t
jjj�|��||_|j|d<|
�|�V}|�dd�}|dur�t|t�r�|�dd�}|�dd�}|dkr�t |��|dkr�t!|��t"|��|s�t
jjj�|��Wd�n1s�wYt
jjj�|dd|ddd���)r�r�r5r�rr�r�ztcp://r�:rr)r
rrr�rr'rVNr�r�rrrrOrYr)#rr6rrr�r:r rVrr�rrrr	rIr
rZAsyncReqChannelr�r(rr	r
r&r'rlrmrnroryrGrrrr)r-rCrerMrNrfrOrFr
rrSr�rr
rr'rVrrrrrrk�sv�$��������

���


��
-�zLocalClient.pub_asynccC�|��dS�N��destroy�r-rrr�__del__szLocalClient.__del__cCs6|j�d�r|j�d|��d�|j�d|���dS)NrXz
syndic/.*/rZr�)rr6r(r�)r-Zjob_idrrrr�sz#LocalClient._clean_up_subscriptionscCs"|jdur|j��d|_dSdSr)r(rrrrrrs


�zLocalClient.destroycCs|Srrrrrr�	__enter__szLocalClient.__enter__cGrrr)r-rarrr�__exit__szLocalClient.__exit__)T)rr^r5Nr5NF)rr^r5Nr5NTN)rr^r5r5N)rr^r5NrsFFF)rr^r5Nr�)rNr^r5r5FN)rNr^r5FNF)rNr^r5N)rNr^r5NFF)rNr^r5FN)Nr�r^FFr)Nr�r^FT)Nr�r^FFF)Nr�r^FFFF)rr^r5r5r�F)rr^r5r5r�NT)2r#�
__module__�__qualname__�__doc__rrr:�syspaths�
CONFIG_DIRr.r&rErKrUr]rQrjrrlrmrn�	coroutinerprrr�r�rzrr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rcrkrr�rrrrrrrr�s&
�H

3
�8
�;
�
�=
�N
�!
�K
�H
�L
�,
�
4
�

::#
�`
�
g,	F
�
d�ircs8eZdZdZ�fdd�Zdd�Zdd�Zdd	�Z�ZS)
�FunctionWrappera
    Create a function wrapper that looks like the functions dict on the minion
    but invoked commands on the minion via a LocalClient.

    This allows SLS files to be loaded with an object that calls down to the
    minion when the salt functions dict is referenced.
    cs4t���||_||_t|jd�|_|��|_dS)Nr�)�superr.rr�r�local� _FunctionWrapper__load_functionsr+)r-rr��r"rrr.%s

zFunctionWrapper.__init__cCs||jvrt�|�|�S)z�
        Since the function key is missing, wrap this call to a command to the
        minion of said key if it is available in the self.functions set
        )r+rq�run_key)r-r'rrr�__missing__,s

zFunctionWrapper.__missing__cCst|j�|jd��|jg��S)zE
        Find out what functions are available on the minion
        ru)r�r#rzr�r6rrrrZ__load_functions5s�z FunctionWrapper.__load_functionscs��fdd�}|S)zc
        Return a function that executes the arguments passed via the local
        client
        cs@t|�}|��D]\}}|�|�d|���q�j��j�|�S)z+
            Run a remote call
            �=)rvr�r}r#rzr�)rarSr3Z_val�r'r-rrr�Csz%FunctionWrapper.run_key.<locals>.funcr)r-r'r�rr)rr&=s	zFunctionWrapper.run_key)	r#rrrr.r'r$r&�
__classcell__rrr%rr!s	r!c@s:eZdZdZej�ejd�dfdd�Z	dd�Z
dd	�ZdS)
�Callera�
    ``Caller`` is the same interface used by the :command:`salt-call`
    command-line tool on the Salt Minion.

    .. versionchanged:: 2015.8.0
        Added the ``cmd`` method for consistency with the other Salt clients.
        The existing ``function`` and ``sminion.functions`` interfaces still
        exist but have been removed from the docs.

    Importing and using ``Caller`` must be done on the same machine as a
    Salt Minion and it must be done using the same user that the Salt Minion is
    running as.

    Usage:

    .. code-block:: python

        import salt.client
        caller = salt.client.Caller()
        caller.cmd('test.ping')

    Note, a running master or minion daemon is not required to use this class.
    Running ``salt-call --local`` simply sets :conf_minion:`file_client` to
    ``'local'``. The same can be achieved at the Python level by including that
    setting in a minion config file.

    .. versionadded:: 2014.7.0
        Pass the minion config as the ``mopts`` dictionary.

    .. code-block:: python

        import salt.client
        import salt.config
        __opts__ = salt.config.minion_config('/etc/salt/minion')
        __opts__['file_client'] = 'local'
        caller = salt.client.Caller(mopts=__opts__)
    r�NcCs6ddl}|r
||_n|j�|�|_|j�|j�|_dS�Nr)�salt.minionrrZ
minion_configr�ZSMinion�sminion�r-rrrrrrr.vs
zCaller.__init__cOs|jj||i|��S)aF
        Call an execution module with the given arguments and keyword arguments

        .. versionchanged:: 2015.8.0
            Added the ``cmd`` method for consistency with the other Salt clients.
            The existing ``function`` and ``sminion.functions`` interfaces still
            exist but have been removed from the docs.

        .. code-block:: python

            caller.cmd('test.arg', 'Foo', 'Bar', baz='Baz')

            caller.cmd('event.send', 'myco/myevent/something',
                data={'foo': 'Foo'}, with_env=['GIT_COMMIT'], with_grains=True)
        )r.r+)r-rerarSrrrrz�sz
Caller.cmdcOs8|jj|}tj�|tjj�|�|�\}}||i|��S)z-
        Call a single salt function
        )r.r+rr�Zload_args_and_kwargsrraZparse_input)r-rerarSr�rrr�function�s
�zCaller.function)r#rrrrrr:rrr.rzr0rrrrr+Os
&
r+c@s2eZdZdZej�ejd�dfdd�Z	dd�Z
dS)�ProxyCallera4
    ``ProxyCaller`` is the same interface used by the :command:`salt-call`
    with the args ``--proxyid <proxyid>`` command-line tool on the Salt Proxy
    Minion.

    Importing and using ``ProxyCaller`` must be done on the same machine as a
    Salt Minion and it must be done using the same user that the Salt Minion is
    running as.

    Usage:

    .. code-block:: python

        import salt.client
        caller = salt.client.ProxyCaller()
        caller.cmd('test.ping')

    Note, a running master or minion daemon is not required to use this class.
    Running ``salt-call --local`` simply sets :conf_minion:`file_client` to
    ``'local'``. The same can be achieved at the Python level by including that
    setting in a minion config file.

    .. code-block:: python

        import salt.client
        import salt.config
        __opts__ = salt.config.proxy_config('/etc/salt/proxy', minion_id='quirky_edison')
        __opts__['file_client'] = 'local'
        caller = salt.client.ProxyCaller(mopts=__opts__)

    .. note::

        To use this for calling proxies, the :py:func:`is_proxy functions
        <salt.utils.platform.is_proxy>` requires that ``--proxyid`` be an
        argument on the commandline for the script this is used in, or that the
        string ``proxy`` is in the name of the script.
    �proxyNcCs.ddl}|p|j�|�|_|j�|j�|_dSr,)r-rZproxy_configrr�ZSProxyMinionr.r/rrrr.�szProxyCaller.__init__c
Os�|jj|}||d�}|�|�t|jdg�p|j�ddg�}t|t�r'|g}|D])}|�d�}||jjvr>t	d|�d���|jj||j||||�}	|	durR|	Sq)|	S)aF
        Call an execution module with the given arguments and keyword arguments

        .. code-block:: python

            caller.cmd('test.arg', 'Foo', 'Bar', baz='Baz')

            caller.cmd('event.send', 'myco/myevent/something',
                data={'foo': 'Foo'}, with_env=['GIT_COMMIT'], with_grains=True)
        )rMreZmodule_executorsZdirect_callz.executez
Executor 'z' is not availableN)
r.r+r��getattrrr6rGrI�	executorsr)
r-rerarSr�r�r4r��fnameZreturn_datarrrrz�s(

�


��zProxyCaller.cmd)r#rrrrrr:rrr.rzrrrrr1�s&r1)3rr�rr{�sysr�rZ
salt.cacherZsalt.channel.clientrZsalt.defaults.exitcodesZsalt.ext.tornado.genZsalt.loaderZsalt.payloadZ
salt.syspathsrr�Zsalt.utils.eventZsalt.utils.filesZsalt.utils.jidZsalt.utils.minionsZsalt.utils.networkZsalt.utils.platformZsalt.utils.stringutilsZsalt.utils.userZsalt.utils.verifyZsalt.exceptionsrrrrrrr	r�Z
seco.ranger?�ImportError�	getLoggerr#r rr:rrrrr!r+r1rrrr�<module>sx

$
�

�A'3N