
    f(                        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 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mZ d d
lm Z m!Z!m"Z"  ejF                   ejH                  e%            Z&dZ'dZ(dejR                  de*de+ddfdZ,	 d)dejR                  de
j0                  ddfdZ-dddddddejR                  de*de+de+de+de*deee*      fdZ.ddddejR                  dee*   d e+fd!Zd"e*ddfd#Z/	 d*d"e*d$eee0      ddfd%Z1dejR                  fd&Z2dejR                  d'e*fd(Z3y)+    N)ListOptional)cloudsconfigcontractentitlements
exceptions	livepatch)log)status)systemtimerutil)AutoAttachCloudInstance)identity)APPARMOR_PROFILESCLOUD_BUILD_INFODEFAULT_CONFIG_FILEDEFAULT_LOG_PREFIX)AttachmentDataattachment_data_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tokenallow_enablereturnc                    ddl m} t        j                  |       }t        j                  j                  t        j                  j                        }|j                  ||      }| j                  j                  |       t        j                  j                          |j                  di       j                  dt        j                  |             }| j                  d|       	 t        j                   | i | j                  j"                  |       t5        j6                         }	|	r| j                  d|	       t+        j                  t-        |              ||        t9        j:                          y
# t$        j&                  t$        j(                  f$ rT}t+        j                  t-        |             t/        j0                  | 	        ||        |j3                          |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   )update_motd_messages)tz)contract_tokenattachment_dtmachineTokenInfo	machineIdz
machine-id)attached_atr   Nzinstance-id)uaclient.timer.update_messagingr   r   UAContractClientdatetimenowtimezoneutcadd_contract_machinemachine_token_filewriter   get_machine_idcache_cleargetwrite_cacheprocess_entitlements_deltar   r	   ConnectivityErrorUbuntuProErrorr   r   	ua_statusr   update_activity_tokenr   get_instance_idr   start)
r   r   r   r   contract_clientr%   new_machine_token
machine_idexccurrent_iids
             2/usr/lib/python3/dist-packages/uaclient/actions.pyattach_with_tokenrA   3   s    E//4O##''8+<+<+@+@'AK'<<K =    !23
%%'"&&'92>BBV**3/J OOL*-++ ""//	
" **,K{3~+FG	KKM ((**C*CD "">k#JKS!S!--/	s   (,E8 8#G/AG**G/cloudc                 x    t        j                  |       }|j                  |      }|d   }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.
    )instancecontractToken)r   r   N)r   r(   %get_contract_token_for_cloud_instancerA   )r   rB   r   r;   tokenResponser   s         r@   auto_attachrH   h   sE     //4O#II J M /*Ec\B    F )
assume_yes
allow_betaaccess_onlyvariant
extra_argsnamerK   rL   rM   rN   rO   c                n    t        j                  | ||      } || |||||      }|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   rP   rN   )rK   rL   called_namerM   rO   )r   entitlement_factoryenable)	r   rP   rK   rL   rM   rN   rO   ent_clsentitlements	            r@   enable_entitlement_by_namerW      sJ      ..dGG K rI   )simulate_with_tokenshow_allrX   rY   c                ~    |rt        j                  | ||      \  }}||fS t        j                  | |      }d}||fS )z6
    Construct the current Pro status dictionary.
    )r   r   rY   )r   rY   r   )r7   simulate_statusr   )r   rX   rY   r   rets        r@   r   r      sS     //%
 3; !!cH=3;rI   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searchappend
write_filejoinr	   ProcessExecutionErrorLOGwarningstrformat)r]   cmdapparmor_rekernel_logs_apparmor_logskernel_linees           r@   _write_apparmor_logs_to_fileru      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                  ||       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.)rcsra   N)r   rb   rc   rg   r	   ri   rm   rl   )rn   r]   rv   outrq   rt   s         r@   _write_command_output_to_filerz      sm    )SYY[l;Q 	(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).0rV   r   s     r@   	<genexpr>z#_get_state_files.<locals>.<genexpr>   s:      

+|'8'8'H'HI &&

s   A A)	cfg_pathr   log_filer   ua_filepathr   r   ENTITLEMENT_CLASSESr&   s   `r@   _get_state_filesr      sM     	++%%**	



+??


 
rI   
output_dirc                    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	                  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        |       }t        j                         rt        j                         dt         nt        j                         g}t        |      D ]q  \  }}	 t        j                  t        j                   |            }t        j"                  t$        j&                  j	                  |dj                  |            |       s |t1        j0                  t2        dz         z   D ]  }
t$        j&                  j5                  |
      s#	 t        j                   |
      }t        j                  |      }t        j                         rt        j"                  |
|       t        j"                  t$        j&                  j	                  |t$        j&                  j7                  |
            |        t9        dj                  |             t:        D ]9  }
t$        j&                  j5                  |
      s#	 t=        j>                  |
|       ; yc c}w # t(        $ r+}	t*        j-                  d|t/        |	             Y d}	~	d}	~	ww xY w# t(        $ r+}	t*        j-                  d|
t/        |	             Y d}	~	d}	~	ww xY w# t(        $ r*}	t*        j-                  d|
t/        |	             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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 {} z.servicez-u {}z{}/pro-journal.txtzsystemctl status {}z	{}/{}.txtr      )rv   Nz
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) rz   rm   r
   LIVEPATCH_CMDrh   UA_SERVICESr   r   we_are_currently_rootpro_logget_all_user_log_filesUSER_LOG_COLLECTED_LIMITget_user_log_file	enumerateredact_sensitive_logsr   	load_filerg   osr   	Exceptionrj   rk   rl   globr   isfilebasenameru   r   shutilcopy)r   r   sservicestate_filesuser_log_fileslog_file_idxr   contentrt   fs              r@   collect_logsr      sW    "%,,Z8 ""$7$>$>z$J "9223!((4 "%&&z2 "&
 	$**:6 "	,44HH,7Kq:?"K	

 	##J/  
%!((1z73Q	

 #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*o L4  	KK98SV 	   91c!fE.  91c!fEsU   	MMA+MN:O	N! NN	O N>>O	O9 O44O9)Tr}   )4r)   r   loggingr   rd   r   typingr   r   uaclientr   r   r   r   r	   r
   r   r   r   r7   r   r   r   uaclient.cloudsr   r   uaclient.defaultsr   r   r   r   uaclient.files.state_filesr   r   r   	getLoggerreplace_top_level_logger_name__name__rj   r   r   UAConfigrl   boolrA   rH   rW   ru   intrz   r   r    rI   r@   <module>r      s      	 	  !  $ ( ( ( 3 $   g:::8DE	  2	2!$2482	2p C	C))C 
	C6 &* 	 
  	 
       c# B *.		 "# 	,B3 B4 B2 =A	)	)&.tCy&9	)		)&// [foo [3 [rI   