U
    2d(                  
   @   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 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'Z0e	j'ed(d)d*Z1dS )-    N)ListOptional)cloudsconfigcontractentitlements
exceptions	livepatch)log)messages)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   sz  ddl m} t| }tjjtjjd}z|j||d}W nN t	j
k
r } z.t  tt| W 5 Q R X 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 ! }
|
rV| 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UrlErrorr   Zdisable_log_to_consoleLOGZ	exceptionstrZConnectivityErrorZmachine_token_filewriter   Zget_machine_idcache_cleargetZwrite_cacheZprocess_entitlements_deltar   UserFacingErrorr   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/   sL    

 


 	r0   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_instancer0   )r   r1   r   r+   ZtokenResponser   r.   r.   r/   auto_attachj   s    
r3   F )
assume_yes
allow_betaaccess_onlyvariant
extra_args)r   namer5   r6   r7   r8   r9   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   r:   r8   )r5   r6   Zcalled_namer7   r9   )r   Zentitlement_factoryenable)	r   r:   r5   r6   r7   r8   r9   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@   rA   out_r,   r.   r.   r/   _write_command_output_to_file   s
    (rH   r   c                 C   s0   | j pt| j| j| 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 ))r:   N)
issubclassr   ZrepoZRepoEntitlementZrepo_list_file_tmplrD   r:   ).0r<   r.   r.   r/   	<genexpr>   s   z#_get_state_files.<locals>.<genexpr>)Zcfg_pathr   log_fileZtimer_log_fileZdaemon_log_filer   Zua_filepathr   r   ZENTITLEMENT_CLASSESr   r.   r.   r/   _get_state_files   s    rN   )r   
output_dirc           
      C   s  t dd| t dd| t dtjd| t dd| t d	d
dd tD d| tD ]$}t d|d||ddgd qrt| }t rt	
 dt nt	 g}t|D ]p\}}z0tt|}ttj|d|| W q tk
r8 } ztd|t| W 5 d}~X Y qX q|ttd  D ]}	tj|	rNzt|	}W n@ tk
r } z td|	t| W Y qNW 5 d}~X Y nX t|}t rt|	| ttj|tj|	| qNd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.txtzxjournalctl --boot=0 -o short-precise {} -u cloud-init-local.service -u cloud-init-config.service -u cloud-config.service c                 S   s   g | ]}d |krd |qS )z.servicez-u {})rD   )rJ   sr.   r.   r/   
<listcomp>   s      z collect_logs.<locals>.<listcomp>z{}/journalctl.txtzsystemctl status {}z	{}/{}.txtr      )rA   Nz
user{}.logz&Failed to collect user log file: %s
%s*zFailed to load file: %s
%s)rH   rD   r	   ZLIVEPATCH_CMDjoinUA_SERVICESrN   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_filerC   osrM   	Exceptionr#   Zwarningr$   globr   isfilebasename)
r   rO   serviceZstate_filesZuser_log_filesZlog_file_idxrL   Zcontentr,   fr.   r.   r/   collect_logs   s~      


  

 ra   )r   r   c              
   C   s   d }zt  }W n tjk
r } zjt|tjr@tjtjddt|tj	rXttj
t|tjr~tjtjj|jdddttjW 5 d }~X Y nX |sttj|S )Nzauto-attach-cloud-type-error)Zmsg_code)
cloud_typez(auto-attach-unsupported-cloud-type-error)r   Zcloud_instance_factoryr   ZCloudFactoryError
isinstanceZCloudFactoryNoCloudErrorr(   r   ZUNABLE_TO_DETERMINE_CLOUD_TYPEZCloudFactoryNonViableCloudErrorZUNSUPPORTED_AUTO_ATTACHZ!CloudFactoryUnsupportedCloudErrorZNonAutoAttachImageErrorZ"UNSUPPORTED_AUTO_ATTACH_CLOUD_TYPErD   rb   )r   r2   r,   r.   r.   r/   get_cloud_instance!  s4    rd   )T)N)2r!   r\   ZloggingrZ   typingr   r   Zuaclientr   r   r   r   r   r	   r
   rW   r   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#   rV   rX   ZUAConfigr$   boolr0   r3   r=   intrH   rN   ra   rd   r.   r.   r.   r/   <module>   sv    	  > 
!  
P