o
    K&b                     @   s  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mZ d dlmZm	Z	 d dl
mZ d dlmZmZmZmZmZmZ d dlZd dlmZmZmZmZmZmZmZmZ d dlmZmZm Z m!Z!m"Z"m#Z# dd	e$ dd
dddg ej%j&j'ej(g dddg ej)j*j'ddddg dd
dZ+e,e-Z.dZ/dddZ0dZ1dZ2dZ3eddZ4e5 Z6G dd dZ7de8fddZ9d$ddZ:de8fd d!Z;d"d# Z<dS )%    N)OrderedDict
namedtuple)datetimetimezonewraps)AnyDictListOptionalTuplecast)aptevent_logger
exceptionsmessagessnapstatusutilversion)ATTACH_FAIL_DATE_FORMATBASE_CONTRACT_URLBASE_SECURITY_URLCONFIG_DEFAULTSCONFIG_FIELD_ENVVAR_ALLOWLISTDEFAULT_CONFIG_FILEzUContent provided in json response is currently considered Experimental and may changez0.1F idname
created_atproductstech_support_levelr   r   r    Zexternal_account_ids)Z_docZ_schema_versionr   
machine_idattached	effectiveexpiresoriginservicesexecution_statusexecution_detailsnoticescontractaccount	simulatedprivater   type)availableResourcesresourceEntitlementsZ_unset)
http_proxyhttps_proxyapt_http_proxyapt_https_proxyupdate_messaging_timerupdate_status_timermetering_timer)
contract_urldata_dirfeatureslog_file	log_levelsecurity_urlsettings_overridestimer_log_filelicense_check_log_file	ua_configDataPath)filenamer0   	permanentc                   @   s  e Zd Zedddedddedddedddedddeddded	dded
ddedddedddd
ZdZdZdZddee	e
f de	ddfddZedd Zede	fddZede	fddZedee	 fddZejde	fddZedee	 fddZejde	fd dZedee	 fd!d"Zejde	fd#d"Zedee	 fd$d%Zejde	fd&d%Zedee fd'd(Zejdefd)d(Zedee fd*d+Zejdefd,d+Zedd.d/Zejdefd0d/Zdeee	f fd1d2Zed3d4 Zed5d6 Zd7e	d8e	fd9d:Zd;e	d<e	fd=d>Zede	fd?d@Z ede	fdAdBZ!edCdD Z"edEdF Z#ede$fdGdHZ%edIdJ Z&edefdKdLZ'edMdN Z(edOdP Z)eddRdSZ*eddTdUZ+eddVdWZ,edXdY Z-dZd[ Z.dd\ee	 de	fd]d^Z/d\e	de0fd_d`Z1dae	ddfdbdcZ2d\e	ddfdddeZ3ddfe0fdgdhZ4dd\e	die0dee
 fdjdkZ5d\e	dle
ddfdmdnZ6dee	e
f fdodpZ7dee	e
f fdqdrZ8dee	e
f fdsdtZ9dee	e
f fdudvZ:dee	e
f fdwdxZ;dye<ee	e
f  dze	dee	e
f fd{d|Z=	dd}e	d~e0deee	e
f ef fddZ>dd~e0dee	e
f fddZ?dd Z@dd ZAdddZBdS )UAConfiginstance-idTFzmachine-access-cis.jsonzmachine-token.jsonlockzstatus.jsonznotices.jsonzmarker-reboot-cmds-requiredmarker-license-checkservices-once-enabledzjobs-status.json)
rI   zmachine-access-cismachine-tokenrJ   status-cacher,   marker-reboot-cmdsrK   rL   zjobs-statusNcfgseriesreturnc                 C   s0   |r	d| _ || _n
t | _ t| j | _|| _dS )r   N)cfg_pathrP   get_config_pathparse_configrQ   )selfrP   rQ    rW   1/usr/lib/python3/dist-packages/uaclient/config.py__init__   s   
zUAConfig.__init__c                 C   s   | j r| jd d }|gS g S )z?Return the list of accounts that apply to this authorized user.machineTokenInfoaccountInfo)is_attachedmachine_token)rV   r[   rW   rW   rX   accounts   s   zUAConfig.accountsc                 C      | j dtS )Nr;   )rP   getr   rV   rW   rW   rX   r;         zUAConfig.contract_urlc                 C   r_   )Nr@   )rP   r`   r   ra   rW   rW   rX   r@      rb   zUAConfig.security_urlc                 C      | j di dS NrD   r4   rP   r`   ra   rW   rW   rX   r4         zUAConfig.http_proxyvaluec                 C   .   d| j vr
i | j d< || j d d< |   d S rd   rP   	write_cfgrV   rg   rW   rW   rX   r4         

c                 C   rc   NrD   r5   re   ra   rW   rW   rX   r5      rf   zUAConfig.https_proxyc                 C   rh   rm   ri   rk   rW   rW   rX   r5      rl   c                 C   rc   NrD   r6   re   ra   rW   rW   rX   r6      rf   zUAConfig.apt_http_proxyc                 C   rh   rn   ri   rk   rW   rW   rX   r6      rl   c                 C   rc   NrD   r7   re   ra   rW   rW   rX   r7      rf   zUAConfig.apt_https_proxyc                 C   rh   ro   ri   rk   rW   rW   rX   r7      rl   c                 C   rc   NrD   r9   re   ra   rW   rW   rX   r9      rf   zUAConfig.update_status_timerc                 C   rh   rp   ri   rk   rW   rW   rX   r9      rl   c                 C   rc   NrD   r8   re   ra   rW   rW   rX   r8      rf   zUAConfig.update_messaging_timerc                 C   rh   rq   ri   rk   rW   rW   rX   r8      rl   Optional[int]c                 C   rc   NrD   r:   re   ra   rW   rW   rX   r:      rf   zUAConfig.metering_timerc                 C   rh   rs   ri   rk   rW   rW   rX   r:      rl   c                 C   s   |  d}d}tj|s|S t|}|d\}}ztd|g t||fW S  t	j
yV   t dkrFtd|| t||f Y S td|| t| | Y S w )a]  Return lock info if config lock file is present the lock is active.

        If process claiming the lock is no longer present, remove the lock file
        and log a warning.

        :param lock_path: Full path to the lock file.

        :return: A tuple (pid, string describing lock holder)
            If no active lock, pid will be -1.
        rJ   )r   :Zpsr   z.Found stale lock file previously held by %s:%sz1Removing stale lock file previously held by %s:%s)	data_pathospathexistsr   	load_filesplitZsubpintr   ZProcessExecutionErrorgetuidloggingdebugwarningunlink)rV   Z	lock_pathZno_lockZlock_contentlock_pidlock_holderrW   rW   rX   check_lock_info   s2   


zUAConfig.check_lock_infoc                 C   s
   | j d S )Nr<   )rP   ra   rW   rW   rX   r<     s   
zUAConfig.data_dirc                 C   s>   | j d}ztt| W S  ty   tttd  Y S w )Nr?   )rP   r`   getattrr~   upperAttributeErrorr   )rV   r?   rW   rW   rX   r?     s   zUAConfig.log_levellabeldescriptionc                 C   s<   |  dpg }||g}||vr|| | d| dS dS )zAdd a notice message to notices cache.

        Such notices are seen in the Notices section from ua status output.
        They are also present in the JSON status output.
        r,   N)
read_cacheappendwrite_cache)rV   r   r   r,   ZnoticerW   rW   rX   
add_notice  s   
zUAConfig.add_noticelabel_regexdescr_regexc                 C   s   g }|  d}|r$|D ]\}}t||rt||rq|||f q|r.| d| dS tj| drAt	
| d dS dS )zRemove matching notices if present.

        :param label_regex: Regex used to remove notices with matching labels.
        :param descr_regex: Regex used to remove notices with matching
            descriptions.
        r,   N)r   rematchr   r   rw   rx   ry   rv   r   Zremove_file)rV   r   r   r,   Zcached_noticesZnotice_labelZnotice_descrrW   rW   rX   remove_notice#  s   
zUAConfig.remove_noticec                 C      | j dtd S )Nr>   rP   r`   r   ra   rW   rW   rX   r>   7  s   zUAConfig.log_filec                 C   r   )NrB   r   ra   rW   rW   rX   rB   ;     zUAConfig.timer_log_filec                 C   r   )NrC   r   ra   rW   rW   rX   rC   A  r   zUAConfig.license_check_log_filec                 C   s   | j r| j S | j}|si S i | _ |di d}|si S tdd |dg D }tdd |dg D }| D ]\}}d|i}||v rM|| |d	< t|| j || j |< q;| j S )
zReturn a dictionary of entitlements keyed by entitlement name.

        Return an empty dict if no entitlements are present.
        rZ   contractInfoc                 s   s$    | ]}| d | dfV  qdS )r1   tokenNr`   .0erW   rW   rX   	<genexpr>Z  s
    
z(UAConfig.entitlements.<locals>.<genexpr>ZresourceTokensc                 s   s    | ]
}| d |fV  qdS )r1   Nr   r   rW   rW   rX   r   ^  s
    
r3   entitlementZresourceToken)_entitlementsr]   r`   dictitemsr   Zapply_series_overridesrQ   )rV   r]   r   Ztokens_by_nameZent_by_nameentitlement_nameZ	ent_valueZentitlement_cfgrW   rW   rX   entitlementsG  s4   

zUAConfig.entitlementsc                 C   s    | j s| jd d d | _ | j S )z6Return a datetime of the attached contract expiration.rZ   r   effectiveTo)_contract_expiry_datetimer]   ra   rW   rW   rX   contract_expiry_datetimel  s   z!UAConfig.contract_expiry_datetimec                 C   s
   t | jS )z<Report whether this machine configuration is attached to UA.)boolr]   ra   rW   rW   rX   r\   v  s   
zUAConfig.is_attachedc                 C   s   | j  t   }|jS )a  Report num days until contract expiration based on effectiveTo

        :return: A positive int representing the number of days the attached
            contract remains in effect. Return a negative int for the number
            of days beyond contract's effectiveTo date.
        )r   dater   ZutcnowZdays)rV   deltarW   rW   rX   contract_remaining_days{  s   z UAConfig.contract_remaining_daysc                 C   s.   | j d}|rt|tr|S td| i S )z>Return a dictionary of any features provided in uaclient.conf.r=   zDUnexpected uaclient.conf features value. Expected dict, but found %s)rP   r`   
isinstancer   r~   r   )rV   r=   rW   rW   rX   r=     s   
zUAConfig.featuresc                 C   sJ   | j s"| d}| jd}|r|r| |}|rt||d || _ | j S )zAReturn the machine-token if cached in the machine token response.rM   machine_token_overlay)	base_dictoverlay_dict)_machine_tokenr   r=   r`   parse_machine_token_overlaydepth_first_merge_overlay_dict)rV   Zraw_machine_tokenmachine_token_overlay_pathr   rW   rW   rX   r]     s    
zUAConfig.machine_tokenOptional[str]c                 C      | j r| j di dS d S )NactivityInfoZactivityTokenr]   r`   ra   rW   rW   rX   activity_token  
   zUAConfig.activity_tokenc                 C   r   )Nr   Z
activityIDr   ra   rW   rW   rX   activity_id  s   zUAConfig.activity_idc                 C   r   )Nr   ZactivityPingIntervalr   ra   rW   rW   rX   activity_ping_interval  r   zUAConfig.activity_ping_intervalc                 C   s&   | j r| j di di dS d S )NrZ   r   r   r   ra   rW   rW   rX   contract_id  s   zUAConfig.contract_idc              
   C   sj   t j|sttjj|dzt	|}t
|W S  ty4 } zttjjt||dd }~ww )N)	file_path)errorr   )rw   rx   ry   r   UserFacingErrorr   Z&INVALID_PATH_FOR_MACHINE_TOKEN_OVERLAYformatr   rz   jsonloads
ValueErrorZERROR_JSON_DECODING_IN_FILEstr)rV   r   Zmachine_token_overlay_contentr   rW   rW   rX   r     s&   z$UAConfig.parse_machine_token_overlaykeyc                 C   sh   | j d }|stj|tS || jv r,| j| }|jr$tj|t|jS tj||jS tj|t|S )zAReturn the file path in the data directory represented by the keyr<   )rP   rw   rx   joinPRIVATE_SUBDIR
data_pathsr0   rF   )rV   r   r<   rv   rW   rW   rX   rv     s   


zUAConfig.data_pathc                 C   s   |  |}tj|S N)rv   rw   rx   ry   rV   r   
cache_pathrW   rW   rX   cache_key_exists  s   
zUAConfig.cache_key_existsr   c                 C   s   t j|rt | dS dS )zDelete the given cache_path if it exists.

        (This is a separate method to allow easier disabling of deletion during
        tests.)
        N)rw   rx   ry   r   )rV   r   rW   rW   rX   _perform_delete  s   zUAConfig._perform_deletec                 C   sX   |st d|ds|dkrd| _d| _n
|dkr | dd | |}| | dS )zRemove specific cache file.z1Invalid or empty key provided to delete_cache_keymachine-accessrM   NrJ   r   zOperation in progress.*)RuntimeError
startswithr   r   r   rv   r   r   rW   rW   rX   delete_cache_key  s   
zUAConfig.delete_cache_keydelete_permanentc                 C   s.   | j  D ]}|s| j | js| | qdS )z
        Remove configuration cached response files class attributes.

        :param delete_permanent: even delete the "permanent" files
        N)r   keysrG   r   )rV   r   Zpath_keyrW   rW   rX   delete_cache  s
   
zUAConfig.delete_cachesilentc                 C   st   |  |}zt|}W n ty$   tj|s!|s!td| Y d S w z	t	j
|tjdW S  ty9   | Y S w )NzFile does not exist: %scls)rv   r   rz   	Exceptionrw   rx   ry   r~   r   r   r   ZDatetimeAwareJSONDecoderr   )rV   r   r   r   contentrW   rW   rX   r     s   
zUAConfig.read_cacher   c                 C   s   |  |}tj|}tj|s$t| tj|tkr$t|d |	ds-|dkr4d | _
d | _n|dkrJd|v rJ| dd|dd  t|tsWtj|tjd	}d
}|| jv rf| j| jsfd}tj|||d d S )Ni  r   rM   rJ   ru   r   zOperation in progress: {}   r   i  i  )mode)rv   rw   rx   dirnamery   makedirsbasenamer   chmodr   r   r   r   r   r{   r   r   r   dumpsr   ZDatetimeAwareJSONEncoderr   r0   
write_file)rV   r   r   filepathr<   r   rW   rW   rX   r   #  s,   



zUAConfig.write_cachec              	   C   s   ddl m} tj| jdd}||O }|r|S t|}g }|di D ]2}|d }z||}	W n tj	y?   	 |
| Y q#w tjjj}
|	jrP|dd|
krU|
| q#|r\||d< |S )	z1Remove beta services from response dict if neededr   entitlement_factoryzfeatures.allow_beta)configZpath_to_valuer)   r   r   r   )uaclient.entitlementsr   r   Zis_config_value_truerP   copydeepcopyr`   r   EntitlementNotFoundErrorr   r   UserFacingStatusACTIVErg   is_beta)rV   	show_betaresponser   Zconfig_allow_betaZnew_responseZreleased_resourcesresourceZresource_nameent_clsZenabled_statusrW   rW   rX   _handle_beta_resources;  s8   




zUAConfig._handle_beta_resourcesc           
      C   s   t j}|jj}tj}|  \}}| dpg }|dkr)|jj}tj	j
||dj}n%tj| drN|jj}d}|D ]\}}	|dkrF|	} nq:tjj
|d}|||| j| jdS )	a_  Return a dict with execution_status, execution_details and notices.

        Values for execution_status will be one of UserFacingConfigStatus
        enum:
            inactive, active, reboot-required
        execution_details will provide more details about that state.
        notices is a list of tuples with label and description items.
        r,   r   )pidr   rO   zconfiguration changeszReboot required	operation)r*   r+   r,   config_pathr   )r   UserFacingConfigStatusINACTIVErg   r   NO_ACTIVE_OPERATIONSr   r   r   Z	LOCK_HELDr   msgrw   rx   ry   rv   ZREBOOTREQUIREDENABLE_REBOOT_REQUIRED_TMPLrS   rP   )
rV   Z
userStatusZ
status_valZstatus_descr   r   r,   r   r   r   rW   rW   rX   _get_config_statusc  s:   	zUAConfig._get_config_statusc                 C   s   ddl m} ddlm} tt}tj| j	d|d< || }|D ]C}|
dr-tjjj}ntjjj}z
||
dd}W n tjyP   td	|
dd
 Y q w |d |
d|d |j|d q |d jdd d |S )z#Return unattached status as a dict.r   get_available_resourcesr   r=   r   	availabler   r   z@Ignoring availability of unknown service %s from contract serverzwithout a 'name' keyr)   presentedAs)r   r   r   c                 S      |  ddS Nr   r   r   xrW   rW   rX   <lambda>      z-UAConfig._unattached_status.<locals>.<lambda>r   )uaclient.contractr   r   r   r   r   DEFAULT_STATUSr   get_versionr=   r`   r   UserFacingAvailability	AVAILABLErg   UNAVAILABLEr   r   LOGr   r   r   sort)rV   r   r   r   	resourcesr   r   r   rW   rW   rX   _unattached_status  s4   



zUAConfig._unattached_statusc           	   	   C   s   d}d }|  }|tjjkrtjj}n|j|v r"tjj}||j }n| \}}|r-|j	}dd |
 D }|j|j|j|j|||j|vrJd|dS d|dS )Nr   c                 S   s$   g | ]}|j j|jj|jjd qS ))r   Zreason_codereason)r   r   Z	named_msgr   )r   servicerW   rW   rX   
<listcomp>  s    z5UAConfig._attached_service_status.<locals>.<listcomp>yesno)r   r   entitledr   status_detailsdescription_overrider   
blocked_by)contract_statusr   ZContractStatusZ
UNENTITLEDr   r  r   INAPPLICABLEZuser_facing_statusr   Zblocking_incompatible_servicesZpresentation_namer   rg   )	rV   entinapplicable_resourcesr  r  r  Z
ent_statusZdetailsr  rW   rW   rX   _attached_service_status  s6   


	z!UAConfig._attached_service_statusc                 C   s  ddl m} ddlm} tt}| jd }|d }tj	j
j}|tj| jd|d d|d	| d
p5g |d |d |dd|dg |d| jd d | jd d | jd dd| jd dg dd |drt| j|d< |dr|d |d< | jd}|s|| }dd t|dd dD }|D ]&}	z
||	dd}
W n
 tjy   Y qw |
| }|d | || q|d jdd d | jd i d!}|r|d"i d#}|r||d$ d%< |S )&z8Return configuration of attached status as a dictionary.r   r   r   rZ   r   r   Z	machineIdTr(   r,   r   r   	createdAtr   r!   r   externalAccountIDsr#   )r   r$   r%   r(   r,   r-   r.   r   r'   effectiveFromr&   r2   c                 S   s&   i | ]}| d s|d | dqS )r   r   r   r   r   r   rW   rW   rX   
<dictcomp>  s    z-UAConfig._attached_status.<locals>.<dictcomp>c                 S   r   r   r   r  rW   rW   rX   r    r  z+UAConfig._attached_status.<locals>.<lambda>r  r)   c                 S   r   r   r   r  rW   rW   rX   r    r  supportr   affordancessupportLevelr-   r"   )r  r   r   r   r   r   r  r]   r   r   r  rg   updater   r  r=   r`   r   r^   r   sortedr   r   r   r  r  r   )rV   r   r   r   rZ   r   r"   r  r  r   r   r  r#  r%  rW   rW   rX   _attached_status  sl   









zUAConfig._attached_statusr   r   c                 C   s`   |D ]'}| d|kr)| drdnd| di  drdnd| di d  S qddi dS )	z0Extract information from the entitlements array.r1   r  r  r  ZobligationsZenableByDefaultr$  )r  auto_enabledr$  r   )rV   r   r   r   rW   rW   rX   _get_entitlement_information  s   


z%UAConfig._get_entitlement_informationr   r   c                 C   sd  ddl m}m} ddlm} d}tt}z|| |}W n$ tj	y@ }	 zt
|	dr:|	jdkr:tjtjjtjjd|	d}	~	ww |di }
|d	i }|tj| jd
|
dd|
dd|
dd|
dg d|dd|d|dd|dg ddd ttj}|
dr|
d|d< t|d }|| }| dkrtjj|d d |t d}t!j"|j|jd t!#d|j d  d}|
dr|
d|d< t|d }|| }| dkrtj$j|d d |t d}t!j"|j|jd t!#d|j d  d}| %d}|r|d }n|| }|
d!g }d"d# t&|d$d% d&D }|D ]E}|dd}z||}W n tj'yP   Y q6w || }| (||}|d  )|d'|j|j*|d( |d) |j|vrud*nd+d, q6|d  j+d-d% d& | (|d.}|d( r|d/ d0}|r||d d1< || ,  | -||}||fS )2zGet a status dictionary based on a token.

        Returns a tuple with the status dictionary and an integer value - 0 for
        success, 1 for failure
        r   )r   get_contract_informationr   codei  )r   Zmsg_codeNr   r[   r   r   r   r   r  r!   )r   r   r    r!   r  r#   T)r   r-   r.   r/   r   r'   r-   )r   r   )	error_msgZ
error_codezThis token is not valid.

r   r   r&   rN   r)   r3   c                 S   s   g | ]
}|d  s|d qS )r   r   rW   r!  rW   rW   rX   r  z  s    z,UAConfig.simulate_status.<locals>.<listcomp>c                 S   s   | d S )Nr   rW   r  rW   rW   rX   r  |  s    z*UAConfig.simulate_status.<locals>.<lambda>r  r   r  r)  r  r  )r   r   r  r)  r   c                 S   r   r   r   r  rW   rW   rX   r    r  r#  r$  r%  r"   ).r  r   r+  r   r   r   r   r  r   ZContractAPIErrorhasattrr,  r   r   ZATTACH_INVALID_TOKENr   r   r`   r&  r   r  r=   r   nowr   Zutcr   Zparse_rfc3339_dateZtotal_secondsZATTACH_FORBIDDEN_EXPIREDr   strftimer   eventr   infoZATTACH_FORBIDDEN_NOT_YETr   r'  r   r*  r   r   r  r   r   )rV   r   r   r   r+  r   retr   Zcontract_informationr   Zcontract_infoZaccount_infor0  Zexpiration_datetimer   messageZeffective_datetimeZstatus_cacher  r   r  r   r   r   r  Zentitlement_informationr#  r%  rW   rW   rX   simulate_status%  s   











zUAConfig.simulate_statusc                 C   s   t  dkrtd| d}|s|  }n| js|  }n|  }||   t  dkrC| 	d| t
 sC| dtjjdd | ||}|S )a  Return status as a dict, using a cache for non-root users

        When unattached, get available resources from the contract service
        to report detailed availability of different resources for this
        machine.

        Write the status-cache when called by root.
        r   zDict[str, Any]rN   r   zfix operationr   )rw   r}   r   r   r  r\   r(  r&  r   r   r   Zshould_rebootr   r   r   r   r   )rV   r   r   rW   rW   rX   r     s(   	
zUAConfig.statusc              	   C   s  ddl m} ddlm} || }d}t }||d< |D ]*}|d |ks*|d|krEz||d }W n
 tjy<   Y qw |}|| }	 nq|du rRtd	|| j
ru| |	i }
|
d }|
d	 |d	< ||d< |d
krt|jrtd|d< n|d rtjjj}ntjjj}||d< |	j|d< |S )zReturn help information from an uaclient service as a dict

        :param name: Name of the service for which to return help data.

        :raises: UserFacingError when no help is available.
        r   r   r   Nr   r   zNo help available for '{}'r   r  enabledTZbetar   help)r  r   r   r   r   r`   r   r   r   r   r\   r  r   r   r	  r
  rg   r  Z	help_info)rV   r   r   r   r  Zhelp_resourceZresponse_dictr   Zhelp_ent_clsZhelp_entZservice_statusZ
status_msgr   rW   rW   rX   r8    sF   	

zUAConfig.helpc           
      C   s  dD ]$}t | |}|d u rtd qt|tr|dk r&d|}t|qt	d| j
tj t	d| jtj t	d| jtj t	d| jtj t| j
| j g }t rxt| j| j | jsjttjss| jsxttjrx|d ddlm} | }| \}}|tj j!kr|"| j| j | js||js| js||jr|d	 t#|dkrd
$|}	t%&t'j(j|	d d S d S )N)r8   r9   r:   z1No config set for {}, default value will be used.r   zQValue for the {} interval must be a positive integer. Default value will be used.ZhttpZhttpsr   )	livepatchr9  z, )r)   ))r   r~   r   r   r|   r   r   r   r   Zvalidate_proxyr6   ZPROXY_VALIDATION_APT_HTTP_URLr7   ZPROXY_VALIDATION_APT_HTTPS_URLr4   ZPROXY_VALIDATION_SNAP_HTTP_URLr5   ZPROXY_VALIDATION_SNAP_HTTPS_URLr   Zsetup_apt_proxyr   Zis_installedZconfigure_snap_proxyZget_config_option_valueZHTTP_PROXY_OPTIONZHTTPS_PROXY_OPTIONr   r   r9  ZLivepatchEntitlementZapplication_statusr   ZApplicationStatusZENABLEDZconfigure_livepatch_proxylenr   r2  r3  r   Z!PROXY_DETECTED_BUT_NOT_CONFIGURED)
rV   Zproprg   r-  Zservices_with_proxiesr9  Zlivepatch_entZlivepatch_status_r)   rW   rW   rX   process_config  s   










zUAConfig.process_configc                    s~   |st }tj}t j}d|vrtd |d< dD ]	}t |||< q fddtD |d< |t	j
|dd7 }t|| dS )	z?Write config values back to config_path or DEFAULT_CONFIG_FILE.r?   )r;   r@   r<   r>   rB   rC   c                    s   i | ]}|t  |qS rW   )r   )r   r   ra   rW   rX   r"  ]  s    z&UAConfig.write_cfg.<locals>.<dictcomp>rD   F)Zdefault_flow_styleN)r   r   ZUACLIENT_CONF_HEADERr   r   rP   r   r   UA_CONFIGURABLE_KEYSyamldumpr   r   )rV   r   r   Zcfg_dictattrrW   ra   rX   rj   H  s   

zUAConfig.write_cfg)NN)rR   rr   )rR   r   r   )F)C__name__
__module____qualname__rE   r   r   r   r   r	   r   r   rY   propertyr^   r;   r@   r   r4   setterr5   r6   r7   r|   r9   r8   r:   r   r   r<   r?   r   r   r>   rB   rC   r   r   r   r\   r   r=   r]   r   r   r   r   r   rv   r   r   r   r   r   r   r   r   r   r  r  r(  r
   r*  r6  r   r8  r<  rj   rW   rW   rW   rX   rH   h   s    







 
$



$	




		
(%#

'B


}$7KrH   rR   c                  C   sB   t jd} | r
| S t jt  t jt}t j|r|S tS )z4Get config path to be used when loading config dict.ZUA_CONFIG_FILE)	rw   environr`   rx   r   getcwdr   r   ry   )Zconfig_fileZ	local_cfgrW   rW   rX   rT   e  s   rT   c                 C   sz  t  t}| s
t } td|  tj| r!|t	
t|  i }tj D ]T\}}| }|dr||dd }|drt|dd }|drbtj|rZt	
t|}ntd|d	|vrm||i|d	< q(||d	 |< q(|tv r||||< q(|| tj|d
 |d
< dD ]}t|| std||| qtt| tD ]}td||| q|S )a  Parse known UA config file

    Attempt to find configuration in cwd and fallback to DEFAULT_CONFIG_FILE.
    Any missing configuration keys will be set to CONFIG_DEFAULTS.

    Values are overridden by any environment variable with prefix 'UA_'.

    @param config_path: Fullpath to ua configfile. If unspecified, use
        DEFAULT_CONFIG_FILE.

    @return: Dict of configuration values.
    z(Using UA client configuration file at %sZua_   NZ	features_	   r>  zCould not find yaml file: {}r=   r<   )r;   r@   zInvalid url in config. {}: {}z)Ignoring invalid uaclient.conf key: %s=%s) r   r   rT   r  r   rw   rx   ry   r&  r>  Z	safe_loadr   rz   rF  r   lowerr   endswithr   r   r   r   
expanduserZis_service_urlr'  setr   
differenceVALID_UA_CONFIG_KEYSr~   r   pop)r   rP   Zenv_keysr   rg   Z
field_nameZfeature_field_namerW   rW   rX   rU   t  sL   




rU   override_keyc                    s    fdd}|S )a  Decorator used to override function return by config settings.

    To identify if we should override the function return, we check
    if the config object has the expected override key, we use it
    has, we will use the key value as the function return. Otherwise
    we will call the function normally.

    @param override_key: key to be looked for in the settings_override
     entry in the config dict. If that key is present, we will return
     its value as the function return.
    c                    s   t   fdd}|S )Nc                     s<   t  } | di t}|tkrdkr|d fS |S   S )NrA   Z
cloud_type)rU   r`   UNSET_SETTINGS_OVERRIDE_KEY)rP   Zvalue_override)frQ  rW   rX   new_f  s   z>apply_config_settings_override.<locals>.wrapper.<locals>.new_fr   )rS  rT  rQ  )rS  rX   wrapper  s   z/apply_config_settings_override.<locals>.wrapperrW   )rQ  rV  rW   rU  rX   apply_config_settings_override  s   rW  c                 C   s   dd }|  D ]D\}}| |}t|tr#t|tr#t| | | qt|trHt|trHt|rBt|d trB|| | ||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   sl   g }t |}|D ]%}d}t| D ]\}}||||kr&t|| d}q|s.|| q	| | d S )NFT)MERGE_ID_KEY_MAPr`   	enumerater   r   extend)	Zbase_valuesZoverlay_valuesr   Zvalues_to_appendZid_keyZoverlay_valueZwas_replacedZbase_value_idx
base_valuerW   rW   rX   update_dict_list  s   


z8depth_first_merge_overlay_dict.<locals>.update_dict_listr   r  N)r   r`   r   r   r   listr:  )r   r   r\  r   rg   r[  rW   rW   rX   r     s   


r   r   )=r   r   r~   rw   r   collectionsr   r   r   r   	functoolsr   typingr   r	   r
   r   r   r   r>  Zuaclientr   r   r   r   r   r   r   r   Zuaclient.defaultsr   r   r   r   r   r   r  r   r   rg   r   r   r  r  Z	getLoggerrA  r  r   rX  rR  r=  rO  rE   Zget_event_loggerr2  rH   r   rT   rU   rW  r   rW   rW   rW   rX   <module>   sx     ( 



        
A!