Current File : //usr/lib/python3/dist-packages/uaclient/__pycache__/util.cpython-312.pyc
�

Uٵg�=���ddlZddlZddlZddlZddlZddlZddlZddlZddlm	Z	ddl
mZmZm
Z
mZmZddlmZmZddlmZddlmZe�Zdedefd	�Zej6ee��ZGd
�dej<�ZGd�d
ej@�Z!d�Z"	d8deeefdeeefdedeeeffd�Z#dgfdede
edefd�Z$	d9dede%de%de%fd�Z&deeefdede%fd�Z'gd�Z(e(fde
edefd�Z)d eede%de%fd!�Z*d"edejfd#�Z+d$edefd%�Z,d&�Z-d'�Z.d(d)d*d+d,d-�Z/d.edefd/�Z0d0e
ede
efd1�Z1de%fd2�Z2d3ed4edefd5�Z3d6e
efd7�Z4y):�N��wraps)�Any�Dict�List�Optional�Union)�
exceptions�messages)�CONFIG_FIELD_ENVVAR_ALLOWLIST)�MessagingOperations�name�returnc�\�|dk(ry|jd�}d|d<dj|�S)z1Replace the name of the root logger from __name__��.�	ubuntupror)�split�join)r�namess  �//usr/lib/python3/dist-packages/uaclient/util.py�replace_top_level_logger_namers0���r�z���J�J�s�O�E��E�!�H��8�8�E�?��c�"��eZdZdZ�fd�Z�xZS)�DatetimeAwareJSONEncoderzBA json.JSONEncoder subclass that writes out isoformat'd datetimes.c�v��t|tj�r|j�St�|�|�S�N)�
isinstance�datetime�	isoformat�super�default)�self�o�	__class__s  �rr"z DatetimeAwareJSONEncoder.default"s.����a��*�*�+��;�;�=� ��w��q�!�!r)�__name__�
__module__�__qualname__�__doc__r"�
__classcell__�r%s@rrrs���L�"�"rrc�2��eZdZdZ�fd�Zed��Z�xZS)�DatetimeAwareJSONDecodera,
    A JSONDecoder that parses some ISO datetime strings to datetime objects.

    Important note: the "some" is because we seem to only be able extend
    Python's json library in a way that lets us convert string values within
    JSON objects (e.g. '{"lastModified": "2019-07-25T14:35:51"}'). Strings
    outside of JSON objects (e.g. '"2019-07-25T14:35:51"') will not be passed
    through our decoder.

    (N.B. This will override any object_hook specified using arguments to it,
    or used in load or loads calls that specify this as the cls.)
    c�f��d|vr|jd�t�|�|d|ji|��y)N�object_hook)�popr!�__init__r/)r#�args�kwargsr%s   �rr1z!DatetimeAwareJSONDecoder.__init__6s4����F�"��J�J�}�%�
���$�G�D�,<�,<�G��Grc��|j�D]'\}}t|t�s�	t|�}|||<�)|S#t$r|}Y�wxYwr)�itemsr�str�parse_rfc3339_date�
ValueError)r$�key�value�	new_values    rr/z$DatetimeAwareJSONDecoder.object_hook;s_���'�'�)�		#�J�C���%��%�&� 2��!�I�#��#��		#����	"�&� %�I�&�s�=�A�
A)r&r'r(r)r1�staticmethodr/r*r+s@rr-r-(s"����H�
���rr-c������fd�}|S)a�Decorator to retry on exception for retry_sleeps.

    @param retry_sleeps: List of sleep lengths to apply between
       retries. Specifying a list of [0.5, 1] tells subp to retry twice
       on failure; sleeping half a second before the first retry and 1 second
       before the second retry.
    @param exception: The exception class to catch and retry for the provided
       retry_sleeps. Any other exception types will not be caught by the
       decorator.
    c�4���t�����fd��}|S)Nc����j�}		�|i|��S#�$r[}|s|�tjdt|�t	|��tj|jd��Yd}~nd}~wwxYw�m)Nz%s: Retrying %d more times.r)�copy�LOG�debugr6�len�time�sleepr0)r2r3�sleeps�e�	exception�f�retry_sleepss    ���r�	decoratorz)retry.<locals>.wrapper.<locals>.decoratorWsz���!�&�&�(�F��.��d�-�f�-�-�� �.�!����I�I�5�s�1�v�s�6�{���J�J�v�z�z�!�}�-�-��
.��s��A<�AA7�7A<r)rIrKrHrJs` ��r�wrapperzretry.<locals>.wrapperVs!���	�q��	.�
�	.��r�)rHrJrLs`` r�retryrNJs����"�Nrr�	orig_dict�new_dict�pathc��i}|j�D]�\}}|j|t�}|s|n|dz|z}t|t�r(||vrt||||��}|s�P|||<�Vt||<�`||k7s�ftjd|t|��|||<��|j�D]\}}||vs�|||<�|S)z<Return a dictionary of delta between orig_dict and new_dict.r)rQz'Contract value for '%s' changed to '%s')	r5�get�DROPPED_KEYr�dict�get_dict_deltasrArBr6)	rOrPrQ�deltasr9r:r;�key_path�	sub_deltas	         rrVrVjs����F��o�o�'�$�
��U��L�L��k�2�	�"�3��s�
�S�(8���e�T�"��h��+��8�C�=�x��	��"+�F�3�K�)��s��
�i�
��I�I�9���I��
�
$�F�3�K�%$�&�n�n�&� �
��U��i���F�3�K� ��Mr�msg�
valid_choicesc
�>�ddlm}|j�}d}dj|dj	|D�cgc]}|j���c}��}	|j
|�td�j�}||vr	|S|j
|��Ccc}w)aGInteractive prompt message, returning a valid choice from msg.

    Expects a structured msg which designates choices with square brackets []
    around the characters which indicate a valid choice.

    Uppercase and lowercase responses are allowed. Loop on invalid choices.

    :return: Valid response character chosen.
    r)�event_loggerrz{} is not one of: {}z, z> )	�uaclientr]�get_event_logger�formatr�upper�info�input�lower)rZr[r]�eventr:�choice�	error_msgs       r�prompt_choicesrh�s���&��)�)�+�E��E�&�-�-�
�t�y�y�}�E�V�&�,�,�.�E�F��I��
�
�
�3���d��!�!�#���M�!���L�	�
�
�9����Fs�B�
assume_yesr"c��|ry|stj}t|�j�j	�}|dk(r|S|dvryy)a�
    Display a confirmation prompt, returning a bool indicating the response

    :param msg: String custom prompt text to emit from input call.
    :param assume_yes: Boolean set True to skip confirmation input and return
        True.
    :param default: Boolean to return when user doesn't enter any text

    This function will only prompt a single time, and defaults to "no" (i.e. it
    returns False).
    Tr)�y�yesF)r�
PROMPT_YES_NOrcrd�strip)rZrir"r:s    r�prompt_for_confirmationro�sM������$�$���#�J����$�$�&�E���{�������r�config�
path_to_valuec�0�|}i}|jd�}|d}|D]-}||k(rd}t|t�r|j||�}�-yt	|�}|j�dk(ry|j�dk(ryt
j|d|���)	aJCheck if value parameter can be translated into a boolean 'True' value.

    @param config: A config dict representing
                   /etc/ubuntu-advantange/uaclient.conf
    @param path_to_value: The path from where the value parameter was
                          extracted.
    @return: A boolean value indicating if the value paramater corresponds
             to a 'True' boolean value.
    @raises exceptions.UbuntuProError when the value provide by the
            path_to_value parameter can not be translated into either
            a 'False' or 'True' boolean value.
    r����falseF�trueTzboolean string: true or false)rq�expected_valuer:)rrrUrSr6rdr
�InvalidBooleanConfigValue)rprqr:�
default_value�paths�
leaf_valuer9�	value_strs        r�is_config_value_truer|�s���
�E��M�����$�E��r��J�����*��#�M��e�T�"��I�I�c�=�1�E����E�
�I�����F�"��	���	�g�	%���2�2�'�:��
�	
r)z(Bearer )[^\']+z(\'attach\', \')[^\']+z(\'machineToken\': \')[^\']+�(\'token\': \')[^\']+z((\'X-aws-ec2-metadata-token\': \')[^\']+z*(.*\[PUT\] response.*api/token,.*data: ).*z(https://bearer:)[^\@]+z1(/snap/bin/canonical-livepatch\s+enable\s+)[^\s]+z>(Contract\s+value\s+for\s+'resourceToken'\s+changed\s+to\s+).*z(\'resourceToken\': \')[^\']+z(\'contractToken\': \')[^\']+zF(https://contracts.canonical.com/v1/resources/livepatch\?token=)[^\s]+z(\"identityToken\": \")[^\"]+zT(response:\s+http://metadata/computeMetadata/v1/instance/service-accounts.*data: ).*r}z(\'userCode\': \')[^\']+z(\'magic_token=)[^\']+z(--registration-key=\")[^\"]+z(--registration-key=\')[^\']+z(--registration-key=)[^ ]+z(--registration-key \")[^\"]+z(--registration-key \')[^\']+z(--registration-key )[^\s]+z
(-p \")[^\"]+z
(-p \')[^\']+z(-p )[^\s]+�
redact_regexsc�F�|}|D]}tj|d|�}�|S)z4Redact known sensitive information from log content.z\g<1><REDACTED>)�re�sub)�logr~�redacted_log�redact_regexs    r�redact_sensitive_logsr�s3���L�%�N���v�v�l�,>��M��N��r�msg_opsc�x�|sy|D]2}t|t�rt|��|\}}||d<|di|��r�2yy)ahEmit messages to the console for user interaction

    :param msg_op: A list of strings or tuples. Any string items are printed.
        Any tuples will contain a callable and a dict of args to pass to the
        callable. Callables are expected to return True on success and
        False upon failure.

    :return: True upon success, False on failure.
    TriFrM)rr6�print)r�ri�msg_op�functorr2s     r�handle_message_operationsr�sN��������f�c�"��&�M�"�M�G�T�!+�D����?�T�?���r�dt_strc���tjdd|�}tjdd|�}|jdd�}tjdd|�}tjj	|d	�S)
aT
    Parse a datestring in rfc3339 format. Originally written for compatibility
    with golang's time.MarshalJSON function. Also handles output of pythons
    isoformat datetime method.

    This drops subseconds.

    :param dt_str: a date string in rfc3339 format

    :return: datetime.datetime object of time represented by dt_str
    z(\d{2}:\d{2}:\d{2})\.\d+z\g<1>z(\d{2}:\d{2}:\d{2})$z\g<1>Z�Zz+00:00z(-|\+)(\d{2}):(\d{2})$z\g<1>\g<2>\g<3>z%Y-%m-%dT%H:%M:%S%z)r�r��replacer�strptime)r��dt_str_without_subseconds�
dt_str_with_z�dt_str_without_z�dt_str_with_pythonish_tzs     rr7r7&s���(!#���#�X�v�!���F�F���,E��M�%�,�,�S�(�;�� "�v�v�!�#5�7G� �����%�%� �"7��r�messagec�~�tjj�*dtjjj�vrx|j	dd�}|j	t
jdzd�}|j	t
jdzd�}|jdd�j�}|S)z}
    Verify if the system can output unicode characters and if not,
    remove those characters from the message string.
    zUTF-8u—�-� r�ascii�ignore)
�sys�stdout�encodingrar�r�
OKGREEN_CHECK�FAIL_X�encode�decode)r�s r�handle_unicode_charactersr�]s���	�
�
���#��#�*�*�-�-�3�3�5�5�
�/�/�(�C�0��
�/�/�(�"8�"8�3�">��C���/�/�(�/�/�C�"7��<���.�.��(�3�:�:�<���Nrc���tjj�D��cic]4\}}|j�tvs|jd�s|dk(r||��6c}}Scc}}w)N�UA_FEATURES�UA_CONFIG_FILE)�os�environr5rdr�
startswith)�k�vs  r�get_pro_environmentr�ws]���J�J�$�$�&���A�q��7�7�9�5�5��<�<�
�&�� � �		
�1�����s�9Ac�n�d�}|j�D]�\}}|j|�}t|t�r t|t�rt	|||��Gt|t
�rDt|t
�r4t
|�r"t|dt�r|||||����	|||<��|||<��y)a�Merge the contents of overlay dict into base_dict not only on top-level
    keys, but on all on the depths of the overlay_dict object. For example,
    using these values as entries for the function:

    base_dict = {"a": 1, "b": {"c": 2, "d": 3}}
    overlay_dict = {"b": {"c": 10}}

    Should update base_dict into:

    {"a": 1, "b": {"c": 10, "d": 3}}

    @param base_dict: The dict to be updated
    @param overlay_dict: The dict with information to be added into base_dict
    c��dddd�}g}|j|�}|D]]}d}t|�D]7\}}	|	j|�|j|�k(s�*t|	|�d}�9|r�M|j|��_|j	|�y)Nr�type�selector)�availableResources�resourceEntitlements�	overridesFT)rS�	enumerate�depth_first_merge_overlay_dict�append�extend)
�base_values�overlay_valuesr9�merge_id_key_map�values_to_append�id_key�
overlay_value�was_replaced�base_value_idx�
base_values
          r�update_dict_listz8depth_first_merge_overlay_dict.<locals>.update_dict_list�s���"(�$*�#�
��
��!�%�%�c�*��+�	7�M� �L�.7��.D�
(�*��
��>�>�&�)�]�->�->�v�-F�F�2�:�}�M�#'�L�
(�
 � �'�'�
�6�	7�	���+�,rr)r9N)r5rSrrUr��listrC)�	base_dict�overlay_dictr�r9r:r�s      rr�r��s��� -�(#�(�(�*�
#�
��U��]�]�3�'�
��j�$�'�J�u�d�,C�*�9�S�>�5�A�
�
�D�
)�j���.E��:��:�j��m�T�#B� ��3���C�@�E�"'�	�#��"�I�c�N�
#r�amd64�i386�ppc64el�arm64�armhf)�x86_64�i686�ppc64le�aarch64�armv7l�archc�N�|j�}tj||�Sr)rd�ARCH_ALIASESrS)r��
arch_lowers  r�standardize_arch_namer��s ������J����J�
�3�3r�archesc��t�}|D]}|jt|���tt	|��Sr)�set�addr��sortedr�)r��deduplicated_archesr�s   r�deduplicate_archesr��s>���%���=����� 5�d� ;�<�=��$�*�+�,�,rc�0�tj�dk(S)Nr)r��getuidrMrr�we_are_currently_rootr��s��
�9�9�;�!��r�filename�
new_extensionc�V�tjj|�\}}|dz|zS)Nr)r�rQ�splitext)r�r�r�
_extensions    r�set_filename_extensionr��s*���w�w�'�'��1��D�*��#�:�
�%�%r�package_listc
�z�djtjdj|�ddddd���dzS)N�
r��PFz  )�width�break_long_words�break_on_hyphens�initial_indent�subsequent_indent)r�textwrap�wrap)r�s r�create_package_list_strr��sF��	
�	�	��M�M�����&��!&�!&�#�"&�

�		
��
	�r)r)rFF)5r�json�loggingr�r�r�r�rD�	functoolsr�typingrrrrr	r^r
r�uaclient.defaultsr�uaclient.typesr
�objectrTr6r�	getLoggerr&rA�JSONEncoderr�JSONDecoderr-rNrVrh�boolror|�REDACT_SENSITIVE_LOGSr�r�r7r�r�r�r�r�r�r�r�r�rMrr�<module>r�sD�����	�	�
����3�3�)�;�.��h��������g���5�h�?�@��"�t�/�/�"��t�/�/��D�BFH���C��H�~��)-�c�3�h���?B��	�#�s�(�^��<!�R�����c���C��6>C��	��#��6:��	��4$
��c�3�h��$
��$
��$
�N��@%:���S�	�����
�)�
*��8<��	��44�s�4�x�'8�'8�4�n�s��s��4�1#�j�������4��4��4�
-�t�C�y�-�T�#�Y�-��t��&�S�&��&��&�
��s�)�r