o
    Pf8                     @   sP  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m	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 d dl
mZ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m Z  d d	l!m"Z"m#Z# d d
l$m%Z%m&Z&m'Z'm(Z( e) Z*e+e,e-Z.dZ/dZ0dej1dej2de j fddZ3	d8dej1deej4 dej2de j de5f
ddZ6	d8dej1de7de5de5ddf
ddZ8	d9dej1dej9ddfddZ:dd ddd!dej1d"e7d#e5d$e7de5d%e	ee7  fd&d'Z;ddd(dej1d)e	e7 d*e5fd+d,Zd-e7ddfd.d/Z<	d:d-e7d0e	ee=  ddfd1d2Z>dej1fd3d4Z?dej1d5e7fd6d7Z@dS );    N)ListOptional)apicloudsconfigcontractentitlementsevent_logger
exceptions	livepatch)log)messagessecret_manager)status)systemtimerutil)APPARMOR_PROFILESCLOUD_BUILD_INFODEFAULT_CONFIG_FILEDEFAULT_LOG_PREFIX)machine_tokennotices)AttachmentDataattachment_data_filemachine_id_filetimer_jobs_state_file)zapt-news.servicezesm-cache.servicezua-timer.servicezua-timer.timerzua-auto-attach.pathzua-auto-attach.servicezua-reboot-cmds.servicezubuntu-advantage.service
   cfgcontract_clientattached_atc                 C   s<   ddl m} tt|d tj| d ||  |  d S )Nr   update_motd_messagesr    r   )uaclient.timer.update_messagingr"   r   writer   	ua_statusr   update_activity_token)r   r   r    r"    r)   2/usr/lib/python3/dist-packages/uaclient/actions.py_handle_partial_attach8   s
   r+   Fservices_to_be_enabledsilentc              
   C   sD  d}g }g }z'|D ]"}t | |j|j|d\}	}
||	M }|	s$||j q	tj|jd q	W nJ tjyH } zt|j t	| || |d }~w tj
yY   ||j d}Y n tyw } zd}||j || W Y d }~nd }~ww |st	| || t| |rtjdd t||D dtjdd |D dd S )	NT)r   namevariantr-   )serviceFc                 S   s,   g | ]\}}|t jjt|t d fqS ))	error_msglog_path)r   UNEXPECTED_ERRORformatstrpro_logget_user_or_root_log_file_path).0r.   	exceptionr)   r)   r*   
<listcomp>q   s    z,_enable_default_services.<locals>.<listcomp>)failed_servicesc                 S   s   g | ]}|t jfqS r)   )r   !E_ATTACH_FAILURE_DEFAULT_SERVICES)r8   r.   r)   r)   r*   r:      s    )enable_entitlement_by_namer.   r/   appendeventservice_processedr
   ConnectivityErrorservice_failedr+   UbuntuProError	Exceptionservices_failedAttachFailureUnknownErrorzipAttachFailureDefaultServices)r   r,   r   r    r-   retr;   unexpected_errorsenable_by_default_serviceent_retreasonexcer)   r)   r*   _enable_default_servicesE   s^   

rP   tokenallow_enablereturnc              
   C   s  ddl m} ddlm} tj| t| }t	
| }tjjtjjd}|j||d}	t j}
|	di di }tdd	 |d
g D }|di di dd}|rvt|}||
krjtj|j|jdtjtjj|j|jd ||	 z||  W n tjy } z|   |d}~ww tj!"  |	di dt!| }t#| |rt	$| |% }t&| ||||d t't(|d ||  t)*  dS )aC  
    Common functionality to take a token and attach via contract backend
    :raise ConnectivityError: 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   )+check_entitlement_apt_directives_are_uniquer!   )tz)contract_tokenattachment_dtmachineTokenInfocontractInfoc                 s   s,    | ]}| d dkr| d |fV  qdS )typesupportN)get)r8   rO   r)   r)   r*   	<genexpr>   s    z$attach_with_token.<locals>.<genexpr>resourceEntitlementsr[   affordances
onlySeriesN)releaseseries_codename	machineId)r   r,   r   r    r-   r#   )+uaclient.entitlementsrT   r%   r"   r   secrets
add_secretr   get_machine_token_filer   UAContractClientdatetimenowtimezoneutcadd_contract_machiner   get_release_infoseriesr\   dictget_distro_infor
   AttachFailureRestrictedReleasera   rb   r   addNoticeLIMITED_TO_RELEASEr&   %EntitlementsAPTDirectivesAreNotUniquedeleteget_machine_idcache_clearr   get_enabled_by_default_servicesr   rP   r   r   r   start)r   rQ   rR   r-   rT   r"   machine_token_filer   r    new_machine_tokencurrent_seriesrY   support_resourceonly_seriesallowed_releaserO   
machine_idr,   r)   r)   r*   attach_with_token   sv   









r   Tcloudc                 C   s0   t | }|j|d}|d }t| ||d dS )a\  
    :raise ConnectivityError: 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.
    )instancecontractToken)rQ   rR   N)r   rh   %get_contract_token_for_cloud_instancer   )r   r   rR   r   tokenResponserQ   r)   r)   r*   auto_attach   s   
r    )access_onlyr/   r-   
extra_argsr.   r   r/   r   c          	      C   sf   t j| ||||d}|sttjj|jd |t	
 \}}|r/|s/ttjj|jd ||f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.   r/   r   r   )title)r   entitlement_factoryr?   infor   ENABLING_TMPLr4   r   enabler   ProgressWrapperENABLED_TMPL)	r   r.   r   r/   r-   r   entitlementrL   rM   r)   r)   r*   r=      s   r=   )simulate_with_tokenshow_allr   r   c                C   s:   |rt j| ||d\}}||fS t j| |d}d}||fS )z6
    Construct the current Pro status dictionary.
    )r   rQ   r   r   r   r   )r'   simulate_statusr   )r   r   r   r   rI   r)   r)   r*   r     s   	
	r   filenamec              
   C   s   g d}d}d}z	t |\}}W n' tjy8 } ztdt| t d| t| W Y d}~dS d}~ww |r[g }|	dD ]}t
||rO|| qBt | d| dS dS )z
    Helper which gets ubuntu_pro apparmor logs from the kernel from the last
    day and writes them to the specified filename.
    )
journalctlz-bz-kz--since=1 day agoz7apparmor=\".*(profile=\"ubuntu_pro_|name=\"ubuntu_pro_)Nz!Failed to collect kernel logs:
%s{}-error
)r   subpr
   ProcessExecutionErrorLOGwarningr5   
write_filer4   splitresearchr>   join)r   cmdapparmor_rekernel_logs_rO   apparmor_logskernel_liner)   r)   r*   _write_apparmor_logs_to_file)  s$   $
r   return_codesc              
   C   sr   zt j|  |d\}}W n tjy, } zt d|t| W Y d}~dS d}~ww t |d|| dS )zCHelper which runs a command and writes output or error to filename.)rcsr   Nzstdout:
{}

stderr:
{})r   r   r   r
   r   r   r4   r5   )r   r   r   outerrrO   r)   r)   r*   _write_command_output_to_fileB  s   $r   c                    s,    j pt jtjjtg fddtjD S )Nc                 3   s(    | ]}t |tjjr| jV  qd S N)
issubclassr   repoRepoEntitlement	repo_file)r8   entitlement_clsr$   r)   r*   r]   W  s    
z#_get_state_files.<locals>.<genexpr>)	cfg_pathr   log_filer   ua_filepathr   r   ENTITLEMENT_CLASSESr$   r)   r$   r*   _get_state_filesP  s   
r   
output_dirc                 C   s  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 q9t| dd\}}td|t	j
|tjd t }td|t	
| t| }t rt dt nt g}t|D ]7\}}	ztt|	}
ttj|d||
 W q ty } ztd|	t| W Y d}~qd}~ww |ttd  D ]K}tj|rzt|}
W n ty } ztd|t| W Y d}~qd}~ww t|
}
t r	t||
 ttj|tj ||
 qt!d| t"D ]1}tj|rRz	t#$|| W q" tyQ } ztd|t| W Y d}~q"d}~ww q"dS )zG
    Write all relevant Ubuntu Pro logs to the specified directory
    zcloud-idz{}/cloud-id.txtz	{} 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 |v rd |qS )z.servicez-u {})r4   )r8   sr)   r)   r*   r:   z  s    z collect_logs.<locals>.<listcomp>z{}/pro-journal.txtzsystemctl status {}z	{}/{}.txtr      )r   Fr   z{}/pro-status.json)clsz{}/environment_vars.jsonNz
user{}.logz&Failed to collect user log file: %s
%s*zFailed to load file: %s
%sz{}/apparmor_logs.txtzFailed to copy file: %s
%s)%r   r4   r   LIVEPATCH_CMDr   UA_SERVICESr   r   r   jsondumpsr   DatetimeAwareJSONEncoderget_pro_environmentr   we_are_currently_rootr6   get_all_user_log_filesUSER_LOG_COLLECTED_LIMITget_user_log_file	enumerateredact_sensitive_logs	load_fileosr   rD   r   r   r5   globr   isfilebasenamer   r   shutilcopy)r   r   r0   
pro_statusr   env_varsstate_filesuser_log_fileslog_file_idxr   contentrO   fr)   r)   r*   collect_logs_  s   

	



r   )F)Tr   )Ari   r   r   loggingr   r   r   typingr   r   uaclientr   r   r   r   r   r	   r
   r   r   r6   r   r   r   r'   r   r   r   uaclient.defaultsr   r   r   r   uaclient.filesr   r   uaclient.files.state_filesr   r   r   r   get_event_loggerr?   	getLoggerreplace_top_level_logger_name__name__r   r   r   UAConfigrh   r+   EnableByDefaultServiceboolrP   r5   r   AutoAttachCloudInstancer   r=   r   intr   r   r   r)   r)   r)   r*   <module>   s    (


F
V


%


