o
    Jhp:                     @   sT  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(m)Z) e* Z+e,e-e.Z/dZ0dZ1dej2dej3de j fddZ4	d8dej2deej5 dej3de j de6f
ddZ7	d8dej2de8de6de6ddf
ddZ9	d9dej2dej:ddfddZ;dd ddd!dej2d"e8d#e6d$e8de6d%e	ee8  fd&d'Z<ddd(dej2d)e	e8 d*e6fd+d,Zd-e8ddfd.d/Z=	d:d-e8d0e	ee>  ddfd1d2Z?dej2fd3d4Z@dej2d5e8fd6d7ZAd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only_series_check_marker_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_attach9   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>r   s    z,_enable_default_services.<locals>.<listcomp>)failed_servicesc                 S   s   g | ]}|t jfqS r*   )r   !E_ATTACH_FAILURE_DEFAULT_SERVICES)r9   r/   r*   r*   r+   r;      s    )enable_entitlement_by_namer/   r0   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_servicesF   s^   

rQ   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}|rzt|}W n
 tjyi   Y nw t|
}|j|jkr~tj|j|jdtjtjj|j|jd t !| |!|	 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)r9   rP   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.entitlementsrU   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
   MissingSeriesInDistroInfoFileeolAttachFailureRestrictedReleaserb   rc   r   addNoticeLIMITED_TO_RELEASEr   r'   %EntitlementsAPTDirectivesAreNotUniquedeleteget_machine_idcache_clearr   get_enabled_by_default_servicesr   rQ   r   r   r   start)r   rR   rS   r.   rU   r#   machine_token_filer    r!   new_machine_tokencurrent_seriesrZ   support_resourceonly_seriesallowed_releasecurrent_releaserP   
machine_idr-   r*   r*   r+   attach_with_token   s   










r   Tcloudc                 C   s   | | }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.
    )rR   rS   N)acquire_pro_tokenr   )r   r   rS   rR   r*   r*   r+   auto_attach   s   
r    )access_onlyr0   r.   
extra_argsr/   r   r0   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/   r0   r   r   )title)r   entitlement_factoryr@   infor   ENABLING_TMPLr5   r   enabler   ProgressWrapperENABLED_TMPL)	r   r/   r   r0   r.   r   entitlementrM   rN   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   rR   r   r   r   r   )r(   simulate_statusr   )r   r   r   r   rJ   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warningr6   
write_filer5   splitresearchr?   join)r   cmdapparmor_rekernel_logs_rP   apparmor_logskernel_liner*   r*   r+   _write_apparmor_logs_to_file0  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   r5   r6   )r   r   r   outerrrP   r*   r*   r+   _write_command_output_to_fileI  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)r9   entitlement_clsr%   r*   r+   r^   ^  s    
z#_get_state_files.<locals>.<genexpr>)	cfg_pathr   log_filer   ua_filepathr   r   ENTITLEMENT_CLASSESr%   r*   r%   r+   _get_state_filesW  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 {})r5   )r9   sr*   r*   r+   r;     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   r5   r   LIVEPATCH_CMDr   UA_SERVICESr   r   r   jsondumpsr   DatetimeAwareJSONEncoderget_pro_environmentr   we_are_currently_rootr7   get_all_user_log_filesUSER_LOG_COLLECTED_LIMITget_user_log_file	enumerateredact_sensitive_logs	load_fileosr   rE   r   r   r6   globr   isfilebasenamer   r   shutilcopy)r   r   r1   
pro_statusr   env_varsstate_filesuser_log_fileslog_file_idxr   contentrP   fr*   r*   r+   collect_logsf  s   

	



r   )F)Tr   )Brj   r   r   loggingr   r   r   typingr   r   uaclientr   r   r   r   r   r	   r
   r   r   r7   r   r   r   r(   r   r   r   uaclient.defaultsr   r   r   r   uaclient.filesr   r   uaclient.files.state_filesr   r   r   r   r   get_event_loggerr@   	getLoggerreplace_top_level_logger_name__name__r   r   r   UAConfigri   r,   EnableByDefaultServiceboolrQ   r6   r   AutoAttachInstancer   r>   r   intr   r   r   r*   r*   r*   r+   <module>   s    (


F
b


%


