
Ke*#                 @   sL  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 j  e j! e"   Z# d1 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 d d d d e	 j& e' e( e( e( e' e e e' d  d! d"   Z+ d# 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/ d0    Z/ d S)2    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ua-timer.serviceua-timer.timerua-auto-attach.pathua-auto-attach.serviceua-reboot-cmds.serviceubuntu-advantage.service
   )cfgtokenallow_enablereturnc              C   s  d d l  m } t j |   } t j j d t j j  } y | j d | d |  } WnG t	 j
 k
 r } z$ t j t |   t	 j    WYd d } ~ Xn X|  j j |  t j j   | j d i   j d t j |    } |  j d	 |  y  t j |  i  |  j j |  Wnq t	 j
 t	 j f k
 r}	 zE t j t d
 |   t j d |   | |   | j   |	  WYd d }	 ~	 Xn Xt j   }
 |
 r|  j d |
  t j t d
 |   | |   t  j!   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_messagesZtzZcontract_tokenZattachment_dtNZmachineTokenInfoZ	machineIdz
machine-idattached_atr   zinstance-id)"Zuaclient.timer.update_messagingr"   r   UAContractClientdatetimeZnowZ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 r0   2/usr/lib/python3/dist-packages/uaclient/actions.pyattach_with_token.   s@    
		


r2   T)r   cloudr!   c             C   sE   t  j |   } | j d |  } | d } t |  d | 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contractTokenr   r    N)r   r$   Z%get_contract_token_for_cloud_instancer2   )r   r3   r    r-   ZtokenResponser   r0   r0   r1   auto_attachh   s
    		
r5   
assume_yesF
allow_betaaccess_onlyvariant 
extra_args)r   namer6   r7   r8   r9   r;   c      	      C   sR   t  j d |  d | d |  } | |  d | d | d | d | d | } | j   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<   r9   r6   r7   Zcalled_namer8   r;   )r   Zentitlement_factoryenable)	r   r<   r6   r7   r8   r9   r;   Zent_clsentitlementr0   r0   r1   enable_entitlement_by_name   s    		r?   simulate_with_tokenshow_all)r   r@   rA   c            C   sU   | r- t  j d |  d | d |  \ } } n t  j d |  d |  } d } | | f S)z6
    Construct the current Pro status dictionary.
    r   r   rA   r   )r+   Zsimulate_statusr   )r   r@   rA   r   Zretr0   r0   r1   r      s    		r   )filenamereturn_codesr!   c             C   s   y% t  j |  j   d | \ } } WnG t j k
 rn } z$ t  j d j |  t |   WYd d } ~ Xn Xt  j | |  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'   )cmdrB   rC   out_r.   r0   r0   r1   _write_command_output_to_file   s
    %2rJ   )r   c             C   s8   |  j  p t |  j t j j t f d d   t j D  S)Nc             s   s<   |  ]2 } t  | t j j  r | j j d  | j  Vq d S)r<   N)
issubclassr   ZrepoZRepoEntitlementZrepo_list_file_tmplrF   r<   ).0r>   r0   r0   r1   	<genexpr>   s   z#_get_state_files.<locals>.<genexpr>)	Zcfg_pathr   log_filer   Zua_filepathr   r   ZENTITLEMENT_CLASSES)r   r0   r0   r1   _get_state_files   s    		rP   )r   
output_dirc       
      C   s  t  d d j |   t  d d j |   t  d j t j  d j |   t  d d j |   t  d	 d
 j |   t  d j d j d d   t D   d j |   x< t D]4 } t  d j |  d j | |  d d d g q Wt |   } t j   rt	 j
   d t  n t	 j   g } x t |  D] \ } } yD t j t j |   } t j t j j | d j |   |  Wq8t k
 r} z t j d | t |   WYd d } ~ Xq8Xq8Wx | t j t d  D] }	 t j j |	  ry t j |	  } WnA t k
 rS} z! t j d |	 t |   wWYd d } ~ Xn Xt j |  } t j   rt j |	 |  t j t j j | t j j |	   |  qWd 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 j  |   q S)z.servicez-u {})rF   )rL   sr0   r0   r1   
<listcomp>   s   	 z collect_logs.<locals>.<listcomp>z{}/pro-journal.txtzsystemctl status {}z	{}/{}.txtrC   r      Nz
user{}.logz&Failed to collect user log file: %s
%s*zFailed to load file: %s
%s)rJ   rF   r	   ZLIVEPATCH_CMDjoinUA_SERVICESrP   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_filerE   osrO   	Exceptionr&   Zwarningr'   globr   isfilebasename)
r   rQ   serviceZstate_filesZuser_log_filesZlog_file_idxrN   Zcontentr.   fr0   r0   r1   collect_logs   s^    "*rc   )r   r   r   r   r   r   )0r%   r^   Zloggingr\   Ztypingr   r   Zuaclientr   r   r   r   r   r	   r
   rY   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&   rX   rZ   ZUAConfigr'   boolr2   r5   r?   intrJ   rP   rc   r0   r0   r0   r1   <module>   sJ   .     ;5%
