HEX
Server: Apache
System: Linux scp1.abinfocom.com 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64
User: confeduphaar (1010)
PHP: 8.1.33
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //proc/self/root/lib/python3/dist-packages/uaclient/__pycache__/util.cpython-38.pyc
U

��Jh�=�@s`ddlZddlZddlZddlZddlZddlZddlZddlZddlm	Z	ddl
mZmZm
Z
mZmZddlmZmZddlmZddlmZe�Zeed�dd	�Ze�ee��ZGd
d�dej�ZGdd
�d
ej �Z!dd�Z"d\eeefeeefeeeefd�dd�Z#dgfee
eed�dd�Z$d]ee%e%e%d�dd�Z&eeefee%d�dd�Z'ddd d!d"d#d$d%d&d'd(d)d*d+d!d,d-d.d/d0d1d2d3d4d5d6gZ(e(fe
eed7�d8d9�Z)eee%e%d:�d;d<�Z*eejd=�d>d?�Z+eed@�dAdB�Z,dCdD�Z-dEdF�Z.dGdHdIdJdKdL�Z/eedM�dNdO�Z0e
ee
edP�dQdR�Z1e%dS�dTdU�Z2eeedV�dWdX�Z3e
edY�dZd[�Z4dS)^�N��wraps)�Any�Dict�List�Optional�Union)�
exceptions�messages)�CONFIG_FIELD_ENVVAR_ALLOWLIST)�MessagingOperations)�name�returncCs(|dkrdS|�d�}d|d<d�|�S)z1Replace the name of the root logger from __name__��.Z	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�datetimeZ	isoformat�super�default)�self�o��	__class__rrr"sz DatetimeAwareJSONEncoder.default)�__name__�
__module__�__qualname__�__doc__r�
__classcell__rrrrrsrcs,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|kr|�d�t�j|d|ji|��dS)N�object_hook)�popr�__init__r')r�args�kwargsrrrr)6s
z!DatetimeAwareJSONDecoder.__init__c	CsN|��D]@\}}t|t�rzt|�}Wntk
r>|}YnX|||<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%rrrrr&(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
sl���}z�||�WS�k
rd}z2|s.|�t�dt|�t|��t�|�d��W5d}~XYqXqdS)Nz%s: Retrying %d more times.r)�copy�LOG�debugr-�len�time�sleepr()r*r+Zsleeps�e)�	exception�f�retry_sleepsrr�	decoratorWs�z)retry.<locals>.wrapper.<locals>.decoratorr)r<r>�r;r=)r<r�wrapperVs
zretry.<locals>.wrapperr)r;r=r@rr?r�retryJsrAr)�	orig_dict�new_dict�pathrc	Cs�i}|��D]�\}}|�|t�}|s(|n
|d|}t|t�rp||krft||||d�}|rn|||<q�t||<q||krt�d|t|��|||<q|��D]\}}||kr�|||<q�|S)z<Return a dictionary of delta between orig_dict and new_dict.r)rDz'Contract value for '%s' changed to '%s')	r,�get�DROPPED_KEYr�dict�get_dict_deltasr5r6r-)	rBrCrDZdeltasr0r1r2Zkey_pathZ	sub_deltarrrrHjs2
�

�

rH)�msg�
valid_choicesrcCsdddlm}|��}d}d�|d�dd�|D���}|�|�td���}||krTq`|�|�q4|S)	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)�.0Zchoicerrr�
<listcomp>�sz"prompt_choices.<locals>.<listcomp>z> )�uaclientrKZget_event_logger�formatr�info�input�lower)rIrJrKZeventr1Z	error_msgrrr�prompt_choices�s
�
rTF)rI�
assume_yesrrcCs>|rdS|stj}t|�����}|dkr.|S|dkr:dSdS)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)�yZyesF)r
Z
PROMPT_YES_NOrRrS�strip)rIrUrr1rrr�prompt_for_confirmation�srX)�config�
path_to_valuercCs�|}i}|�d�}|d}|D].}||kr.d}t|t�rF|�||�}qdSqt|�}|��dkrfdS|��dkrvdStj|d|d��d	S)
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���ZfalseF�trueTzboolean string: true or false)rZZexpected_valuer1N)rrrGrEr-rSr	ZInvalidBooleanConfigValue)rYrZr1Z
default_value�pathsZ
leaf_valuer0Z	value_strrrr�is_config_value_true�s(


�r^z(Bearer )[^\']+z(\'attach\', \')[^\']+z(\'machineToken\': \')[^\']+z(\'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: ).*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_regexsrcCs |}|D]}t�|d|�}q|S)z4Redact known sensitive information from log content.z\g<1><REDACTED>)�re�sub)�logr_Zredacted_logZredact_regexrrr�redact_sensitive_logssrc)�msg_opsrUrcCsJ|sdS|D]8}t|t�r$t|�q|\}}||d<|f|�sdSqdS)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.
    TrUF)rr-�print)rdrUZmsg_opZfunctorr*rrr�handle_message_operationss


rf)�dt_strrcCsDt�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)r`ra�replacer�strptime)rgZdt_str_without_subsecondsZ
dt_str_with_zZdt_str_without_zZdt_str_with_pythonish_tzrrrr.&s(��	��r.)�messagercCs`tjjdksdtjj��kr\|�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�encodingrLrir
Z
OKGREEN_CHECKZFAIL_X�encode�decode)rkrrr�handle_unicode_characters]s
��rucCsdd�tj��D�S)NcSs4i|],\}}|��tks*|�d�s*|dkr||�qS)ZUA_FEATURESZUA_CONFIG_FILE)rSr�
startswith)rM�k�vrrr�
<dictcomp>xs
�z'get_pro_environment.<locals>.<dictcomp>)�os�environr,rrrr�get_pro_environmentws�r|cCs�dd�}|��D]�\}}|�|�}t|t�rFt|t�rFt|||�qt|t�r�t|t�r�t|�r�t|dt�r�|||||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]J}d}t|�D]*\}}	|	�|�|�|�kr.t|	|�d}q.|s|�|�q|�|�dS)Nr
�typeZselector)ZavailableResourcesZresourceEntitlementsZ	overridesFT)rE�	enumerate�depth_first_merge_overlay_dict�append�extend)
Zbase_valuesZoverlay_valuesr0Zmerge_id_key_mapZvalues_to_appendZid_keyZ
overlay_valueZwas_replacedZbase_value_idx�
base_valuerrr�update_dict_list�s�

z8depth_first_merge_overlay_dict.<locals>.update_dict_listr)r0N)r,rErrGr�listr7)Z	base_dictZoverlay_dictr�r0r1r�rrrr�s

rZamd64Zi386Zppc64elZarm64Zarmhf)Zx86_64Zi686Zppc64leZaarch64Zarmv7l)�archrcCs|��}t�||�Sr)rS�ARCH_ALIASESrE)r�Z
arch_lowerrrr�standardize_arch_name�sr�)�archesrcCs*t�}|D]}|�t|��q
tt|��Sr)�set�addr��sortedr�)r�Zdeduplicated_archesr�rrr�deduplicate_arches�sr�)rcCst��dkS)Nr)rz�getuidrrrr�we_are_currently_root�sr�)�filename�
new_extensionrcCstj�|�\}}|d|S)Nr)rzrD�splitext)r�r�r
Z
_extensionrrr�set_filename_extension�sr��Zpackage_listc
Cs&d�tjd�|�dddddd��dS)N�
rm�PFz  )�widthZbreak_long_wordsZbreak_on_hyphensZinitial_indentZsubsequent_indent)r�textwrapZwrapr�rrr�create_package_list_str�s��
��r�)r)rFF)5rZjsonZloggingrzr`rpr�r8�	functoolsr�typingrrrrrrOr	r
Zuaclient.defaultsrZuaclient.typesr�objectrFr-rZ	getLoggerr!r5ZJSONEncoderrZJSONDecoderr&rArHrT�boolrXr^ZREDACT_SENSITIVE_LOGSrcrfr.rur|rr�r�r�r�r�r�rrrr�<module>s�		"!�


���(� ���7
5�	�