HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //usr/lib/python3/dist-packages/uaclient/__pycache__/util.cpython-310.pyc
o

nHJe?=�@sBddlZddlZddlZddlZddlZddlZddlZddlZddlm	Z	ddl
mZmZm
Z
mZmZddlmZmZddlmZddlmZe�Zdedefd	d
�Ze�ee��ZGdd�dej�ZGd
d�dej �Z!dd�Z"	dFdeeefdeeefdedeeeffdd�Z#dgfdede
edefdd�Z$	dGdede%de%de%fdd�Z&d eeefd!ede%fd"d#�Z'gd$�Z(e(fd%e
edefd&d'�Z)d(eede%fd)d*�Z*d+edejfd,d-�Z+d.edefd/d0�Z,d1d2�Z-d3d4�Z.d5d6d7d8d9d:�Z/d;edefd<d=�Z0d>e
ede
efd?d@�Z1de%fdAdB�Z2dCe
efdDdE�Z3dS)H�N��wraps)�Any�Dict�List�Optional�Union)�
exceptions�messages)�CONFIG_FIELD_ENVVAR_ALLOWLIST)�MessagingOperations�name�returncCs(|dkrdS|�d�}d|d<d�|�S)z1Replace the name of the root logger from __name__��.�	ubuntupror)�split�join)r
�names�r�//usr/lib/python3/dist-packages/uaclient/util.py�replace_top_level_logger_names


rcs eZdZdZ�fdd�Z�ZS)�DatetimeAwareJSONEncoderzBA json.JSONEncoder subclass that writes out isoformat'd datetimes.cs t|tj�r
|��St��|�S�N)�
isinstance�datetime�	isoformat�super�default)�self�o��	__class__rrr"sz DatetimeAwareJSONEncoder.default)�__name__�
__module__�__qualname__�__doc__r�
__classcell__rrr!rrsrcs,eZdZdZ�fdd�Zedd��Z�ZS)�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.)
    cs.d|vr	|�d�t�j|d|ji|��dS)N�object_hook)�popr�__init__r))r�args�kwargsr!rrr+6s
z!DatetimeAwareJSONDecoder.__init__c	CsL|��D]\}}t|t�r#zt|�}Wnty|}Ynw|||<q|Sr)�itemsr�str�parse_rfc3339_date�
ValueError)r �key�value�	new_valuerrrr);s
���z$DatetimeAwareJSONDecoder.object_hook)r#r$r%r&r+�staticmethodr)r'rrr!rr((s

r(cs��fdd�}|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.
    cst�����fdd��}|S)Nc
sp���}	z�|i|��WS�y6}z|s|�t�dt|�t|��t�|�d��WYd}~nd}~wwq)NTz%s: Retrying %d more times.r)�copy�LOG�debugr/�len�time�sleepr*)r,r-�sleeps�e)�	exception�f�retry_sleepsrr�	decoratorWs����z)retry.<locals>.wrapper.<locals>.decoratorr)r?rA�r>r@)r?r�wrapperVs
zretry.<locals>.wrapperr)r>r@rCrrBr�retryJsrDr�	orig_dict�new_dict�pathc	Cs�i}|��D]C\}}|�|t�}|s|n|d|}t|t�r8||vr3t||||d�}|r2|||<qt||<q||krIt�d|t|��|||<q|��D]\}}||vrZ|||<qN|S)z<Return a dictionary of delta between orig_dict and new_dict.r)rGz'Contract value for '%s' changed to '%s')	r.�get�DROPPED_KEYr�dict�get_dict_deltasr7r8r/)	rErFrG�deltasr2r3r4�key_path�	sub_deltarrrrKjs4

��
���rK�msg�
valid_choicescCsfddlm}|��}d}d�|d�dd�|D���}	|�|�td	���}||vr-	|S|�|�q)
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, cSsg|]}|���qSr)�upper)�.0�choicerrr�
<listcomp>�sz"prompt_choices.<locals>.<listcomp>Tz> )�uaclientrR�get_event_logger�formatr�info�input�lower)rOrPrR�eventr3�	error_msgrrr�prompt_choices�s
�

��r_F�
assume_yesrcCs>|rdS|s	tj}t|�����}|dkr|S|dvrdSdS)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_NOr[r\�strip)rOr`rr3rrr�prompt_for_confirmation�sre�config�
path_to_valuecCs�|}i}|�d�}|d}|D]}||krd}t|t�r#|�||�}qdSt|�}|��dkr2dS|��dkr:dStj|d|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)rg�expected_valuer3)rrrJrHr/r\r	�InvalidBooleanConfigValue)rfrgr3�
default_value�paths�
leaf_valuer2�	value_strrrr�is_config_value_true�s(


�rq)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: ).*rrz(\'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_regexscCs |}|D]	}t�|d|�}q|S)z4Redact known sensitive information from log content.z\g<1><REDACTED>)�re�sub)�logrs�redacted_log�redact_regexrrr�redact_sensitive_logssry�msg_opscCs\ddlm}|��}|sdS|D]}t|t�r|�|�q|\}}|di|��s+dSqdS)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.
    rrQTFNr)rWrRrXrr/rZ)rzrRr]�msg_op�functorr,rrr�handle_message_operationss
�r}�dt_strcCsDt�dd|�}t�dd|�}|�dd�}t�dd|�}tj�|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)rtru�replacer�strptime)r~�dt_str_without_subseconds�
dt_str_with_z�dt_str_without_z�dt_str_with_pythonish_tzrrrr0(s��	��r0�messagecCs`tjjdusdtjj��vr.|�dd�}|�tjdd�}|�tjdd�}|�dd��	�}|S)	z}
    Verify if the system can output unicode characters and if not,
    remove those characters from the message string.
    NzUTF-8u—�-� r�ascii�ignore)
�sys�stdout�encodingrSr�r
�
OKGREEN_CHECK�FAIL_X�encode�decode)r�rrr�handle_unicode_characters_sr�cCsdd�tj��D�S)NcSs4i|]\}}|��tvs|�d�s|dkr||�qS)�UA_FEATURES�UA_CONFIG_FILE)r\r�
startswith)rT�k�vrrr�
<dictcomp>zs��z'get_pro_environment.<locals>.<dictcomp>)�os�environr.rrrr�get_pro_environmentys�r�cCs�dd�}|��D]D\}}|�|�}t|t�r#t|t�r#t|||�qt|t�rHt|t�rHt|�rBt|dt�rB|||||d�q	|||<q|||<qdS)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
Ssxdddd�}g}|�|�}|D]%}d}t|�D]\}}	|	�|�|�|�kr,t|	|�d}q|s4|�|�q|�|�dS)Nr
�type�selector)�availableResources�resourceEntitlements�	overridesFT)rH�	enumerate�depth_first_merge_overlay_dict�append�extend)
�base_values�overlay_valuesr2�merge_id_key_map�values_to_append�id_key�
overlay_value�was_replaced�base_value_idx�
base_valuerrr�update_dict_list�s"�

�
�z8depth_first_merge_overlay_dict.<locals>.update_dict_listr)r2N)r.rHrrJr��listr9)�	base_dict�overlay_dictr�r2r3r�rrrr��s


�r��amd64�i386�ppc64el�arm64�armhf)�x86_64�i686�ppc64le�aarch64�armv7l�archcCs|��}t�||�Sr)r\�ARCH_ALIASESrH)r��
arch_lowerrrr�standardize_arch_name�sr��archescCs*t�}|D]	}|�t|��qtt|��Sr)�set�addr��sortedr�)r��deduplicated_archesr�rrr�deduplicate_arches�sr�cCst��dkS)Nr)r��getuidrrrr�we_are_currently_root�sr��package_listcCs2td�tjd�|�dddddd���td�dS)N�
r��PFz  )�width�break_long_words�break_on_hyphens�initial_indent�subsequent_indentr)�printr�textwrap�wrap)r�rrr�print_package_list�s���r�)r)rFF)4r�json�loggingr�rtr�r�r:�	functoolsr�typingrrrrrrWr	r
�uaclient.defaultsr�uaclient.typesr�objectrIr/r�	getLoggerr#r7�JSONEncoderr�JSONDecoderr(rDrKr_�boolrerq�REDACT_SENSITIVE_LOGSryr}r0r�r�r�r�r�r�r�r�rrrr�<module>s�		"!�
�
��

� ����
�' ��
�
�
�7
5�	�