U
    2d5C                     @   s\  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 d dl	m
Z
 d dlmZmZmZmZmZ d dlmZmZ d dlmZ d dlmZ e Zeedd	d
ZeeeZG dd dejZ G dd dej!Z"G dd dej#Z$edd Z%dd Z&d[eeef eeef eeeef dddZ'dg feee edddZ(d\ee)e)e)dddZ*eeef ee)d d!d"Z+d#d$d%d&d'd(d)d*d+d,d-d.d/d0d&d1d2d3d4d5d6d7d8d9d:d;gZ,e,fee ed<d=d>Z-ee e)d?d@dAZ.ee j dBdCdDZ/eedEdFdGZ0dHdI Z1dJdK Z2dLdMdNdOdPdQZ3eedRdSdTZ4ee ee dUdVdWZ5e)dXdYdZZ6dS )]    N)contextmanagerwraps)AnyDictListOptionalUnion)
exceptionsmessages)CONFIG_FIELD_ENVVAR_ALLOWLIST)MessagingOperations)namereturnc                 C   s(   | dkrdS |  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_name   s
    
r   c                   @   s.   e Zd ZejdejdiZejedddZ	dS )LogFormatterzERROR: %(message)szDEBUG: %(message)s)recordr   c                 C   s    | j |jd}t||S )Nz%(message)s)FORMATSgetZlevelnologging	Formatterformat)selfr   Zlog_fmtr   r   r   r   %   s    zLogFormatter.formatN)
__name__
__module____qualname__r   ZERRORDEBUGr   Z	LogRecordstrr   r   r   r   r   r      s     r   c                       s    e Zd ZdZ fddZ  ZS )DatetimeAwareJSONEncoderzBA json.JSONEncoder subclass that writes out isoformat'd datetimes.c                    s    t |tjr| S t |S N)
isinstancedatetimeZ	isoformatsuperdefault)r    o	__class__r   r   r+   -   s    z DatetimeAwareJSONEncoder.default)r!   r"   r#   __doc__r+   __classcell__r   r   r-   r   r&   *   s   r&   c                       s,   e Zd ZdZ fddZedd Z  ZS )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                    s.   d|kr| d t j|d| ji| d S )Nobject_hook)popr*   __init__r2   )r    argskwargsr-   r   r   r4   A   s    
z!DatetimeAwareJSONDecoder.__init__c              	   C   sN   |   D ]@\}}t|trzt|}W n tk
r>   |}Y nX || |< q| S r'   )itemsr(   r%   parse_rfc3339_date
ValueError)r,   keyvalue	new_valuer   r   r   r2   F   s    


z$DatetimeAwareJSONDecoder.object_hook)r!   r"   r#   r/   r4   staticmethodr2   r0   r   r   r-   r   r1   3   s   r1   c               	   c   s~   t d} | j}dd |D }|s6td dV  dS |d }|j}|t jkrXdV  dS |d z
dV  W 5 || X dS )a  
    A context manager that disables logging to console in its body

    N.B. This _will not_ disable console logging if it finds the console
    handler is configured at DEBUG level; the assumption is that this means we
    want as much output as possible, even if it risks duplication.

    This context manager will allow us to gradually move away from using the
    logging framework for user-facing output, by applying it to parts of the
    codebase piece-wise. (Once the conversion is complete, we should have no
    further use for it and it can be removed.)

    (Note that the @contextmanager decorator also allows this function to be
    used as a decorator.)
    r   c                 S   s   g | ]}|j d kr|qS )zupro-console)r   ).0Zhandlerr   r   r   
<listcomp>h   s    
 z*disable_log_to_console.<locals>.<listcomp>z0disable_log_to_console: no console handler foundNr   i  )r   	getLoggerZhandlersLOGdebuglevelr$   ZsetLevel)Zupro_loggerZlog_handlersZpotential_handlersZconsole_handlerZ	old_levelr   r   r   disable_log_to_consoleU   s$    




rD   c                    s    fdd}|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                    s   t   fdd}|S )Nc               
      st     }z| |W S   k
rl } z:|s.|dt| }tt||  t|d W 5 d }~X Y qX qd S )Nz Retrying %d more times.r   )copylenrA   rB   r%   timesleepr3   )r5   r6   ZsleepseZ	retry_msg)	exceptionfretry_sleepsr   r   	decorator   s    z)retry.<locals>.wrapper.<locals>.decoratorr   )rK   rM   rJ   rL   )rK   r   wrapper   s    zretry.<locals>.wrapperr   )rJ   rL   rO   r   rN   r   retry   s    rP   r   )	orig_dictnew_dictpathr   c           
      C   s   i }|   D ]\}}||t}|s(|n
|d | }t|trp||krft||| |d}|rn|||< qt||< q||krd| d t| d }	t|	 |||< q|  D ]\}}|| kr|||< q|S )z<Return a dictionary of delta between orig_dict and new_dict.r   )rS   zContract value for 'z' changed to '')	r7   r   DROPPED_KEYr(   dictget_dict_deltasr%   rA   rB   )
rQ   rR   rS   Zdeltasr:   r;   r<   Zkey_pathZ	sub_deltalogr   r   r   rW      s>    
  




rW   )msgvalid_choicesr   c                 C   sd   ddl m} | }d}d|ddd |D }||  td }||krTq`|| q4|S )	aG  Interactive 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_loggerr   z{} is not one of: {}z, c                 S   s   g | ]}|  qS r   )upper)r>   Zchoicer   r   r   r?      s     z"prompt_choices.<locals>.<listcomp>z> )uaclientr\   get_event_loggerr   r   infoinputlower)rY   rZ   r\   eventr;   Z	error_msgr   r   r   prompt_choices   s    
 
rd   F)rY   
assume_yesr+   r   c                 C   s>   |rdS | st j} t|   }|dkr.|S |dkr:dS dS )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   )yZyesF)r   ZPROMPT_YES_NOra   rb   strip)rY   re   r+   r;   r   r   r   prompt_for_confirmation   s    rh   )configpath_to_valuer   c                 C   s   | }i }| d}|d }|D ].}||kr.d}t|trF|||}q dS qt|}| dkrfdS | dkrvdS ttj	j
|d|dd	S )
aK  Check 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.UserFacingError when the value provide by the
            path_to_value parameter can not be translated into either
            a 'False' or 'True' boolean value.
    r   ZfalseFtrueTzboolean string: true or false)rj   Zexpected_valuer;   N)r   r(   rV   r   r%   rb   r
   ZUserFacingErrorr   ZERROR_INVALID_CONFIG_VALUEr   )ri   rj   r;   Zdefault_valuepathsZ
leaf_valuer:   Z	value_strr   r   r   is_config_value_true   s,    

rn   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_regexsr   c                 C   s    | }|D ]}t |d|}q|S )z4Redact known sensitive information from log content.z\g<1><REDACTED>)resub)rX   ro   Zredacted_logZredact_regexr   r   r   redact_sensitive_logs;  s    rr   )msg_opsr   c                 C   sX   ddl m} | }| sdS | D ]2}t|tr:|| q |\}}|f |s  dS q dS )ah  Emit 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.
    r   r[   TF)r^   r\   r_   r(   r%   r`   )rs   r\   rc   Zmsg_opZfunctorr5   r   r   r   handle_message_operationsE  s    

rt   )dt_strr   c                 C   sD   t dd| }t dd|}|dd}t dd|}tj|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)rp   rq   replacer)   strptime)ru   Zdt_str_without_subsecondsZdt_str_with_zZdt_str_without_zZdt_str_with_pythonish_tzr   r   r   r8   a  s(        	   r8   )messager   c                 C   s`   t jjdksdt jj kr\| dd} | tjd d} | tjd d} | dd	 } | S )	z}
    Verify if the system can output unicode characters and if not,
    remove those characters from the message string.
    NzUTF-8u   —- r   asciiignore)
sysstdoutencodingr]   rw   r   ZOKGREEN_CHECKZFAIL_Xencodedecode)ry   r   r   r   handle_unicode_characters  s    
r   c                   C   s   dd t j D S )Nc                 S   s4   i | ],\}}|  tks*|d s*|dkr||qS )ZUA_FEATURESZUA_CONFIG_FILE)rb   r   
startswith)r>   kvr   r   r   
<dictcomp>  s   
 z'get_pro_environment.<locals>.<dictcomp>)osenvironr7   r   r   r   r   get_pro_environment  s    r   c                 C   s   dd }|  D ]\}}| |}t|trFt|trFt| | | qt|trt|trt|rt|d tr|| | ||d q|| |< q|| |< qdS )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           
      S   sx   dddd}g }| |}|D ]J}d}t| D ]*\}}	|	 || |kr.t|	| d}q.|s|| q| | d S )Nr   typeZselector)ZavailableResourcesZresourceEntitlementsZ	overridesFT)r   	enumeratedepth_first_merge_overlay_dictappendextend)
Zbase_valuesZoverlay_valuesr:   Zmerge_id_key_mapZvalues_to_appendZid_keyZoverlay_valueZwas_replacedZbase_value_idx
base_valuer   r   r   update_dict_list  s    

z8depth_first_merge_overlay_dict.<locals>.update_dict_listr   )r:   N)r7   r   r(   rV   r   listrF   )Z	base_dictZoverlay_dictr   r:   r;   r   r   r   r   r     s    

r   Zamd64Zi386Zppc64elZarm64Zarmhf)Zx86_64Zi686Zppc64leZaarch64Zarmv7l)archr   c                 C   s   |   }t||S r'   )rb   ARCH_ALIASESr   )r   Z
arch_lowerr   r   r   standardize_arch_name  s    r   )archesr   c                 C   s*   t  }| D ]}|t| q
tt|S r'   )setaddr   sortedr   )r   Zdeduplicated_archesr   r   r   r   deduplicate_arches  s    r   )r   c                   C   s   t  dkS )Nr   )r   getuidr   r   r   r   we_are_currently_root  s    r   )r   )r   FF)7r)   Zjsonr   r   rp   r~   rG   
contextlibr   	functoolsr   typingr   r   r   r   r	   r^   r
   r   Zuaclient.defaultsr   Zuaclient.typesr   objectrU   r%   r   r@   r!   rA   r   r   ZJSONEncoderr&   ZJSONDecoderr1   rD   rP   rW   rd   boolrh   rn   ZREDACT_SENSITIVE_LOGSrr   rt   r8   r   r   r   r   r   r   r   r   r   r   r   <module>   s   		"
)  
 
 
!       * 7
5	