
    g8                        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jT                         Z+ ejX                   ejZ                  e.            Z/dZ0dZ1dejd                  dejf                  de j                   fdZ4	 d-dejd                  deejj                     dejf                  de j                   de6f
dZ7	 d-dejd                  de8de6de6ddf
dZ9	 d.dejd                  dejt                  ddfdZ;ddddddejd                  de8de6de8de6d e	ee8      fd!Z<ddd"dejd                  d#e	e8   d$e6fd%Zd&e8ddfd'Z=	 d/d&e8d(e	ee>      ddfd)Z?dejd                  fd*Z@dejd                  d+e8fd,ZAy)0    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                     ddl m} t        j                  t	        |             t        j                  |         ||        |j                          y )Nr   update_motd_messagesr"   r    )uaclient.timer.update_messagingr%   r   writer   	ua_statusr   update_activity_token)r    r!   r"   r%   s       2/usr/lib/python3/dist-packages/uaclient/actions.py_handle_partial_attachr-   9   s=    
 E~+FG))+    Fservices_to_be_enabledsilentc                    d}g }g }	 |D ]k  }t        | |j                  |j                  |      \  }	}
||	z  }|	s|j                  |j                         Lt        j                  |j                         m 	 |st        | ||       t        j                  |       |rot        j                  t        ||      D cg c]C  \  }}|t        j                   j#                  t%        |      t'        j(                               fE c}}      t        j*                  |D cg c]  }|t        j,                  f c}      y # t        j                  $ r3}t        j                  j                         t        | ||       |d }~wt        j                  $ r! |j                  j                         d}Y At        $ r9}d}|j                  j                         |j                  |       Y d }~}d }~ww xY wc c}}w c c}w )NT)r    namevariantr0   )serviceF)	error_msglog_path)failed_services)enable_entitlement_by_namer2   r3   appendeventservice_processedr   ConnectivityErrorservice_failedr-   UbuntuProError	Exceptionservices_failedAttachFailureUnknownErrorzipr   UNEXPECTED_ERRORformatstrpro_logget_user_or_root_log_file_pathAttachFailureDefaultServices!E_ATTACH_FAILURE_DEFAULT_SERVICES)r    r/   r!   r"   r0   retr7   unexpected_errorsenable_by_default_serviceent_retreasonexcer2   	exceptions                  r,   _enable_default_servicesrR   F   s    CO$)? 	P%8.33199	OGV 7NC&&'@'E'EF''0I0N0N'O	P2 sO[Ao.66 ,/'):,! (i  1188&))n%,%K%K%M 9 !  99 !0! 8EEF! +  '' 6;;<sO[A	$$ 8==> $8==>  ##$!!s7   A0E =AG>
!HG;.F3G;:G;.G66G;tokenallow_enablereturnc                    ddl m} ddlm} t        j
                  j                  |       t        j                  |       }t        j                  |       }t        j                  j                  t        j                  j                        }|j                  ||      }	t!        j"                         j$                  }
|	j'                  di       j'                  di       }t)        d |j'                  d	g       D              }|j'                  d
i       j'                  di       j'                  dd      }|rt!        j*                  |      }||
k7  r+t-        j.                  |j0                  |j2                        t5        j6                  t4        j8                  j:                  |j0                  |j2                         t=        j>                  |       |j?                  |	       	  ||        t         jD                  jG                          |	j'                  di       j'                  dt!        jD                  |             }tI        j>                  |       |r4t        jJ                  | |jM                               }tO        | ||||       tQ        j>                  tS        |              ||        tU        jV                          y# t,        j@                  $ r}|jC                          |d}~ww xY w)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              3   j   K   | ]+  }|j                  d       dk(  r|j                  d       |f - yw)typesupportN)get).0rP   s     r,   	<genexpr>z$attach_with_token.<locals>.<genexpr>   s5      55=I% 
vs   13resourceEntitlementsr_   affordances
onlySeriesN)releaseseries_codename	machineId)r    r/   r!   r"   r0   r&   ),uaclient.entitlementsrW   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   AttachFailureRestrictedReleaserf   rg   r   addNoticeLIMITED_TO_RELEASEr   r)   %EntitlementsAPTDirectivesAreNotUniquedeleteget_machine_idcache_clearr   get_enabled_by_default_servicesr	   rR   r   r   r   start)r    rS   rT   r0   rW   r%   machine_token_filer!   r"   new_machine_tokencurrent_seriesr\   support_resourceonly_seriesallowed_releaserP   
machine_idr/   s                     r,   attach_with_tokenr      s    E%%e,&==cB//4O##''8+<+<+@+@'AK'<<K =  ,,.55N$(();R@DDL  !!"8"=  	Y+	]B		\4	  
  00=.(;;'// / ? ?  	NN--#+++;;	

 	&++K8./3C8
 %%'"&&'92>BBV**3/J *%!)!I!I#002"
 	!#9+#	
 ~+FG	KKM1 ;; !!#s   'K	 	K3K..K3cloudc                 B    |j                  |       }t        | ||       y)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.
    )rS   rT   N)acquire_pro_tokenr   )r    r   rT   rS   s       r,   auto_attachr      s      ##C(Ec\Br.    )access_onlyr3   r0   
extra_argsr2   r   r3   r   c                   t        j                  | ||||      }|s=t        j                  t        j
                  j                  |j                               |j                  t        j                               \  }}|r?|s=t        j                  t        j                  j                  |j                               ||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    r2   r3   r   r   )title)r	   entitlement_factoryr:   infor   ENABLING_TMPLrD   r   enabler   ProgressWrapperENABLED_TMPL)	r    r2   r   r3   r0   r   entitlementrM   rN   s	            r,   r8   r8      s     22K 

8))00{7H7H0IJ!(()<)<)>?OGVv

8((//k6G6G/HIF?r.   )simulate_with_tokenshow_allr   r   c                ~    |rt        j                  | ||      \  }}||fS t        j                  | |      }d}||fS )z6
    Construct the current Pro status dictionary.
    )r    rS   r   r    r   r   )r*   simulate_statusr   )r    r   r   r   rJ   s        r,   r   r     sS     //%
 3; !!cH=3;r.   filenamec                    g d}d}d}	 t        j                  |      \  }}|rfg }|j                  d      D ]*  }t        j                  ||      s|j                  |       , t        j                  | dj                  |             yy# t        j                  $ rW}t        j                  dt        |             t        j                  dj                  |       t        |             Y d}~yd}~ww xY w)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_)N
z!Failed to collect kernel logs:
%s{}-error)r   subpsplitresearchr9   
write_filejoinr   ProcessExecutionErrorLOGwarningrE   rD   )r   cmdapparmor_rekernel_logs_apparmor_logskernel_linerP   s           r,   _write_apparmor_logs_to_filer   %  s     :CLKKBS)Q
 M*006 699[+6!((56 h		-(@A 	 ++ ?8#a&A*++H5s1v>>?s   B C5AC00C5return_codesc                 >   	 t        j                  | j                         |      \  }}t        j                  |dj	                  ||             y# t
        j                  $ r8}t        j                  dj	                  |      t        |             Y d}~yd}~ww xY w)zCHelper which runs a command and writes output or error to filename.)rcszstdout:
{}

stderr:
{}r   N)r   r   r   r   rD   r   r   rE   )r   r   r   outerrrP   s         r,   _write_command_output_to_filer   >  s~    
;;syy{=S 	299#sC	
 ++ ?*++H5s1v>>?s   (A B$.BBc                       j                   xs t         j                  t        j                  j
                  t        g fdt        j                  D        S )Nc              3      K   | ]:  }t        |t        j                  j                        r |      j                   < y wN)
issubclassr	   repoRepoEntitlement	repo_file)ra   entitlement_clsr    s     r,   rb   z#_get_state_files.<locals>.<genexpr>S  s:      

/<+<+<+L+LM C **

s   A A)	cfg_pathr   log_filer   ua_filepathr   r	   ENTITLEMENT_CLASSESr'   s   `r,   _get_state_filesr   L  sM     	++%%**	



#/#C#C


 
r.   
output_dirc                 
	   t        ddj                  |             t        dj                  t        j                        dj                  |             t        ddj                  |             t        ddj                  |             t        d	j                  d
j	                  t
        D cg c]  }d|v sdj                  |       c}            dj                  |             t
        D ]1  }t        dj                  |      dj                  ||      ddg       3 t        | d      \  }}t        j                  dj                  |      t        j                  |t        j                               t        j                         }t        j                  dj                  |      t        j                  |             t        |       }t        j                         rt!        j"                         dt$         nt!        j&                         g}t)        |      D ]q  \  }	}
	 t        j*                  t        j,                  |
            }t        j                  t.        j0                  j	                  |dj                  |	            |       s |t;        j:                  t<        dz         z   D ]  }t.        j0                  j?                  |      s#	 t        j,                  |      }t        j*                  |      }t        j                         rt        j                  ||       t        j                  t.        j0                  j	                  |t.        j0                  jA                  |            |        tC        dj                  |             tD        D ]9  }t.        j0                  j?                  |      s#	 tG        jH                  ||       ; yc c}w # t2        $ r+}t4        j7                  d|
t9        |             Y d}~d}~ww xY w# t2        $ r+}t4        j7                  d|t9        |             Y d}~d}~ww xY w# t2        $ r*}t4        j7                  d|t9        |             Y d}~d}~ww xY w)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 {} z.servicez-u {}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   rD   r   LIVEPATCH_CMDr   UA_SERVICESr   r   r   jsondumpsr   DatetimeAwareJSONEncoderget_pro_environmentr   we_are_currently_rootrF   get_all_user_log_filesUSER_LOG_COLLECTED_LIMITget_user_log_file	enumerateredact_sensitive_logs	load_fileosr   r?   r   r   rE   globr   isfilebasenamer   r   shutilcopy)r    r   sr4   
pro_statusr   env_varsstate_filesuser_log_fileslog_file_idxr   contentrP   fs                 r,   collect_logsr   [  s    "%,,Z8 "9223!((4 "%&&z2 "&
 	$**:6 "	,44HH,7Kq:?"K	

 	##J/  
%!((1z73Q	

 sU3MJ
##J/

:4#@#@A '')H
"))*5

8
 #3'K %%' 	&&()B*BC'')*  #,N"; 
h		001A1A(1KLGZ)<)<\)JK
 499%7#%=>> 77>>! **1- 009G))+!!!W-Z)9)9!)<=w( !!7!>!>z!JK  77>>!Az*C LH  	KK98SV 	   91c!fE.  91c!fEsU   -	O7O(A+O!PQ!	P* PP	Q! QQ	R Q==R)F)Tr   )Brn   r   r   loggingr   r   r   typingr   r   uaclientr   r   r   r   r	   r
   r   r   r   rF   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   UAConfigrm   r-   EnableByDefaultServiceboolrR   rE   r   AutoAttachInstancer   r8   r   intr   r   r    r.   r,   <module>r      s       	 	  !	 	 	 $ - ( ( (  2  	&%%'g:::8DE	  
,	
,..
, ""
,$ ?	? !@!@A? ..? ""	?
 ?L 	Q	QQ Q 	Q
 
Qn C	C$$C 
	C* &*	
 	
   c#J *.		 "# 	,B3 B4 B4 =A

&.tCy&9
	
&// bfoo b3 br.   