U
    lHJe*#                  
   @   s  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	m
Z
mZmZmZ d dlmZ d dlmZ d dlmZmZmZ d dlmZ d dlmZ d d	lmZmZmZ d d
lmZmZmZ e e!e"Z#dZ$dZ%e	j&e'e(ddddZ)d'e	j&ejddddZ*dddddde	j&e'e(e(e(e'eee'  dddZ+ddde	j&ee' e(dddZd(e'eee,  dddd Z-e	j&d!d"d#Z.e	j&e'd$d%d&Z/dS ))    N)ListOptional)cloudsconfigcontractentitlements
exceptions	livepatch)log)status)systemtimerutil)AutoAttachCloudInstance)identity)CLOUD_BUILD_INFODEFAULT_CONFIG_FILEDEFAULT_LOG_PREFIX)AttachmentDataattachment_data_filetimer_jobs_state_file)zua-timer.servicezua-timer.timerzua-auto-attach.pathzua-auto-attach.servicezua-reboot-cmds.servicezubuntu-advantage.service
   )cfgtokenallow_enablereturnc              
   C   sf  ddl m} t| }tjjtjjd}z|j||d}W n: t	j
k
rt } ztt| t	 W 5 d}~X Y nX | j| tj  |di dt| }| d| zt| i | jj| W n\ t	j
t	jfk
r& }	 z4tt|d	 tj| d
 ||  |  |	W 5 d}	~	X Y nX t }
|
rB| d|
 tt|d	 ||  t !  dS )a:  
    Common functionality to take a token and attach via contract backend
    :raise UrlError: On unexpected connectivity issues to contract
        server or inability to access identity doc from metadata service.
    :raise ContractAPIError: On unexpected errors when talking to the contract
        server.
    r   )update_motd_messages)Ztz)Zcontract_tokenZattachment_dtNZmachineTokenInfoZ	machineIdz
machine-id)attached_atr   zinstance-id)"Zuaclient.timer.update_messagingr   r   UAContractClientdatetimeZnowtimezoneZutcZadd_contract_machiner   ZUrlErrorLOGZ	exceptionstrZConnectivityErrorZmachine_token_filewriter   Zget_machine_idcache_cleargetZwrite_cacheZprocess_entitlements_deltar   ZUbuntuProErrorr   r   	ua_statusr   Zupdate_activity_tokenr   Zget_instance_idr   start)r   r   r   r   contract_clientr   Znew_machine_tokeneZ
machine_idexcZcurrent_iid r,   2/usr/lib/python3/dist-packages/uaclient/actions.pyattach_with_token.   sJ    

 

 	r.   T)r   cloudr   c                 C   s0   t | }|j|d}|d }t| ||d dS )aS  
    :raise UrlError: On unexpected connectivity issues to contract
        server or inability to access identity doc from metadata service.
    :raise ContractAPIError: On unexpected errors when talking to the contract
        server.
    :raise NonAutoAttachImageError: If this cloud type does not have
        auto-attach support.
    )instanceZcontractToken)r   r   N)r   r   Z%get_contract_token_for_cloud_instancer.   )r   r/   r   r)   ZtokenResponser   r,   r,   r-   auto_attachh   s    
r1   F )
assume_yes
allow_betaaccess_onlyvariant
extra_args)r   namer3   r4   r5   r6   r7   c          	      C   s,   t j| ||d}|| |||||d}| S )z
    Constructs an entitlement based on the name provided. Passes kwargs onto
    the entitlement constructor.
    :raise EntitlementNotFoundError: If no entitlement with the given name is
        found, then raises this error.
    )r   r8   r6   )r3   r4   Zcalled_namer5   r7   )r   Zentitlement_factoryenable)	r   r8   r3   r4   r5   r6   r7   Zent_clsentitlementr,   r,   r-   enable_entitlement_by_name   s      r;   )simulate_with_tokenshow_all)r   r<   r=   c                C   s4   |rt j| ||d\}}nt j| |d}d}||fS )z6
    Construct the current Pro status dictionary.
    )r   r   r=   )r   r=   r   )r'   Zsimulate_statusr   )r   r<   r=   r   Zretr,   r,   r-   r      s    	r   )filenamereturn_codesr   c              
   C   sf   zt j|  |d\}}W n: tjk
rT } zt d|t| W 5 d}~X Y nX t || dS )zCHelper which runs a command and writes output or error to filename.)Zrcsz{}-errorN)r   Zsubpsplitr   ZProcessExecutionError
write_fileformatr#   )cmdr>   r?   out_r*   r,   r,   r-   _write_command_output_to_file   s
    (rF   r   c                 C   s(   | j pt| jtjjtfdd tjD S )Nc                 s   s,   | ]$}t |tjjr|jj|jd V  qdS ))r8   N)
issubclassr   ZrepoZRepoEntitlementZrepo_list_file_tmplrB   r8   ).0r:   r,   r,   r-   	<genexpr>   s   z#_get_state_files.<locals>.<genexpr>)	Zcfg_pathr   log_filer   Zua_filepathr   r   ZENTITLEMENT_CLASSESr   r,   r,   r-   _get_state_files   s    rL   )r   
output_dirc           
      C   s  t dd| t dd| t dtjd| t dd| t d	d
| t dddd tD d| tD ]$}t d|d||ddgd qt| }t rt	
 dt nt	 g}t|D ]p\}}z0tt|}ttj|d|| W q tk
rH } ztd|t| W 5 d}~X Y qX q|ttd  D ]}	tj|	r^zt|	}W n@ tk
r } z td|	t| W Y q^W 5 d}~X Y nX t|}t rt|	| ttj|tj|	| q^dS )zG
    Write all relevant Ubuntu Pro logs to the specified directory
    zcloud-idz{}/cloud-id.txtzpro status --format jsonz{}/ua-status.jsonz	{} statusz{}/livepatch-status.txtzsystemctl list-timers --allz{}/systemd-timers.txtzujournalctl --boot=0 -o short-precise -u cloud-init-local.service -u cloud-init-config.service -u cloud-config.servicez{}/cloud-init-journal.txtzjournalctl -o short-precise {} c                 S   s   g | ]}d |krd |qS )z.servicez-u {})rB   )rH   sr,   r,   r-   
<listcomp>   s      z collect_logs.<locals>.<listcomp>z{}/pro-journal.txtzsystemctl status {}z	{}/{}.txtr      )r?   Nz
user{}.logz&Failed to collect user log file: %s
%s*zFailed to load file: %s
%s)rF   rB   r	   ZLIVEPATCH_CMDjoinUA_SERVICESrL   r   Zwe_are_currently_rootpro_logZget_all_user_log_filesUSER_LOG_COLLECTED_LIMITZget_user_log_file	enumerateZredact_sensitive_logsr   Z	load_filerA   osrK   	Exceptionr"   Zwarningr#   globr   isfilebasename)
r   rM   serviceZstate_filesZuser_log_filesZlog_file_idxrJ   Zcontentr*   fr,   r,   r-   collect_logs   s      
	
  

 r_   )T)N)0r    rZ   ZloggingrX   typingr   r   Zuaclientr   r   r   r   r   r	   r
   rU   r   r'   r   r   r   Zuaclient.cloudsr   r   Zuaclient.defaultsr   r   r   Zuaclient.files.state_filesr   r   r   Z	getLoggerZreplace_top_level_logger_name__name__r"   rT   rV   ZUAConfigr#   boolr.   r1   r;   intrF   rL   r_   r,   r,   r,   r-   <module>   sn    	  = 
!  
