
    x[hN7                     J   d 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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 ddl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  eej@                   ejB                  e"            Z# G d
 de      Z$ e$dd       e$dd       e$dd      gZ% e$dd       e$dd       e$dd       e$dd       e$dd       e$dd       e$dd       e$d d!       e$d"d#       e$d$d%       e$d&d%       e$d'd(      gZ&	 dRd)eejN                     d*ejN                  fd+Z(d,ee)   d-ejT                  d.e)d*ee)   fd/Z+d,ee)   d-ejT                  d.e)d*dfd0Z,d1ejT                  d2ejT                  d3e-d*dfd4Z.d5ejT                  d3e-d*dfd6Z/d5ejT                  d*dfd7Z0d5ejT                  d3e-d*dfd8Z1d9ee)ef   d*eejT                     fd:Z2 ejT                  d;      fd<ejT                  d*eejT                     fd=Z3d>ejT                  d*eejT                     fd?Z4d@ejT                  d*eejT                     fdAZ5d5ejT                  d9ee)ef   d@ejT                  d>ejT                  d3e-d*dfdBZ6 ejT                  dC       ejT                  dD      dEfdFe)d9ee)ef   d@ejT                  d>ejT                  d3e-d*dfdGZ7dHe8d*dfdIZ9	 	 	 dSdFe)dHe8dJe-dKe-d*df
dLZ:dMe)dNejv                  d*e8fdOZ<e"dPk(  r- ejz                   e<dQ e(       j}                                      yy)TzGDefine 'collect-logs' utility and handler to include in cloud-init cmd.    N)datetimetimezone)AnyDictIteratorList
NamedTupleOptionalcast)loggers)Init)ProcessExecutionErrorsubp)tempdir)copyget_config_logfiles
write_filec                   "    e Zd ZU eed<   eed<   y)
ApportFilepathlabelN)__name__
__module____qualname__str__annotations__     :/usr/lib/python3/dist-packages/cloudinit/cmd/devel/logs.pyr   r      s    
IJr   r   z(/var/log/installer/autoinstall-user-dataAutoInstallUserDataz/autoinstall.yamlAutoInstallYAMLz'/etc/cloud/cloud.cfg.d/99-installer.cfgInstallerCloudCfgz//var/log/installer/ubuntu_desktop_installer.logUdiLogz-/var/log/installer/subiquity-server-debug.logSubiquityServerDebugz-/var/log/installer/subiquity-client-debug.logSubiquityClientDebugz%/var/log/installer/curtin-install.log	CurtinLogz0/var/log/installer/subiquity-curtin-install.confCurtinInstallConfigz8/var/log/installer/curtin-install/subiquity-initial.confCurtinConfigInitialz:/var/log/installer/curtin-install/subiquity-curthooks.confCurtinConfigCurtHooksz8/var/log/installer/curtin-install/subiquity-extract.confCurtinConfigExtractz=/var/log/installer/curtin-install/subiquity-partitioning.confCurtinConfigPartitioningz(/var/log/installer/curtin-error-logs.tarCurtinErrorz$/var/log/installer/curtin-errors.tarz(/var/log/installer/block/probe-data.json	ProbeDataparserreturnc                     | st        j                  dd      } | j                  dddddd	
       | j                  dddd       | j                  dddddd       | j                  ddddd       | S )a2  Build or extend and arg parser for collect-logs utility.

    @param parser: Optional existing ArgumentParser instance representing the
        collect-logs subcommand which will be extended to support the args of
        this utility.

    @returns: ArgumentParser with proper argument configuration.
    zcollect-logsz)Collect and tar all cloud-init debug info)progdescriptionz	--verbosez-vcountr   	verbosityzBe more verbose.)actiondefaultdesthelpz	--tarfilez-tzcloud-init.tar.gzzOThe tarfile to create containing all collected logs. Default: cloud-init.tar.gz)r6   r8   z--include-userdataz-uF
store_trueuserdataz?DEPRECATED: This is default behavior and this flag does nothing)r6   r5   r7   r8   z--redact-sensitivez-rzRedact potentially sensitive data from logs. Sensitive data may include passwords or keys in user data and root read-only files.)r6   r5   r8   )argparseArgumentParseradd_argument)r.   s    r   
get_parserr>   O   s     ((C
    #*   M  	 $  
 Mr   cmd	file_pathmsgc                 N   |j                   j                  dd       	 t        |       j                  }t	        ||       t
        j                  d||j                         |S # t        $ r8}t	        |t        |             t
        j                  d|       d}Y d}~|S d}~ww xY w)zCHelper which runs a command and writes output or error to filename.Tparentsexist_okcollected %s to file '%s'collecting %s failed.N)
parentmkdirr   stdoutr   LOGdebugstemr   r   )r?   r@   rA   outputes        r   _write_command_output_to_filerP      s     4$7Dc!! 	9f%		-sINNCM ! 9c!f%		)3/ Ms   A# #	B$,-BB$c                    |j                   j                  dd       	 |j                  d      5 }t        j                  | ||       ddd       t
        j                  d||j                         y# 1 sw Y   +xY w# t        $ r5}t        |t        |             t
        j                  d|       Y d}~yd}~ww xY w)zHelper which runs a command and writes output or error to filename.

    `subprocess.call` is invoked directly here to stream output to the file.
    Otherwise memory usage can be high for large outputs.
    TrC   w)rJ   stderrNrF   rG   )rH   rI   open
subprocesscallrK   rL   rM   OSErrorr   r   )r?   r@   rA   frO   s        r   _stream_command_output_to_filerY      s     4$7D^^C  	5AOOC!4	5 			-sINNC	5 	5 09c!f%		)3//0s.   A? A3	A? 3A<8A? ?	B=+B88B=r   out_dirinclude_sensitivec                 D   | j                         rz|s+| j                         j                  t        j                  z  r6|j	                  dd       t        | |       t        j                  d|        yt        j                  d|        yt        j                  d|        y)z-Collect a file into what will be the tarball.TrC   zcollected file: %sz#sensitive file %s was not collectedzfile %s did not existN)	is_filestatst_modeS_IROTHrI   r   rK   rL   trace)r   rZ   r[   s      r   _collect_filerb      sn     ||~		 3 3dll BMM$M6wII*D1II;TB		)40r   log_dirc                    t         D ]Z  }t        j                  | |j                  dd       j                  }t        t        j                  |j                        |d       \ |rdt        D ]Z  }t        j                  | |j                  dd       j                  }t        t        j                  |j                        |d       \ yy)z'Obtain subiquity logs and config files.   NT)r[   )INSTALLER_APPORT_FILESpathlibPathr   rH   rb    INSTALLER_APPORT_SENSITIVE_FILES)rc   r[   src_filedestination_dirs       r   _collect_installer_logsrl      s     + 
!,,wab0ABIILL'"	

 8 	H%ll7HMM!"4EFMMOX]]+"&	 r   c                 b    t        ddg| dz  d      }t        g d| dz  d      }|s|xs d	}y
y
)z8Include cloud-init version and dpkg version in the logs.
cloud-initz	--versionversionzcloud-init --versionr?   r@   rA   )z
dpkg-queryz--showz-f=${Version}
rn   zdpkg-versionzdpkg versionznot-availableN)rP   )rc   ro   dpkg_vers      r   _collect_version_inforr      sM    +;'I%"G
 -EN*H
 -o r   c                     |rt        dg| dz  d       t        g d| dz  d       t        g dt        j                  | d	      d
       y)z0Include dmesg and journalctl output in the logs.dmesgz	dmesg.txtzdmesg outputrp   )
journalctlz--boot=0-oshort-precisezjournal.txtzsystemd journal of current boot)ru   z	--boot=-1rv   rw   zjournal-previous.txtz systemd journal of previous bootN)rY   rg   rh   )rc   r[   s     r   _collect_system_logsrx      sV     &	+	

 #=M)-
 #>,,w(>?.r   log_cfgc              #   Z   K   t        |       D ]  }t        j                  |        yw)z7Get paths for cloud-init.log and cloud-init-output.log.N)r   rg   rh   )ry   r   s     r   _get_cloudinit_logsr{      s+      $G, !ll4  !s   )+z
/etc/cloudetc_cloud_dirc              #   l   K   | dz  | dz  dgfd| j                  d      D        E d{    y7 w)zGet paths for all files in /etc/cloud.

    Excludes:
      /etc/cloud/keys because it may contain non-useful sensitive data.
      /etc/cloud/templates because we already know its contents
    keys	templatesz99-installer.cfgc              3   Z   K   | ]"  }|j                   vr|j                  vr| $ y wN)namerH   ).0r   ignores     r   	<genexpr>z!_get_etc_cloud.<locals>.<genexpr>  s0      99F"t{{&'@ 	s   (+z**/*Nglob)r|   r   s    @r   _get_etc_cloudr      sE      	#	F!&&v.  s   )424	cloud_dirc           	          t        j                  | j                  d      | j                  d      | j                  d      d | j                  d      D        | j                  d            S )zkGet paths for files in /var/lib/cloud.

    Skip user-provided scripts, semaphores, and old instances.
    zdata/*z
handlers/*zseed/*c              3   B   K   | ]  }|j                         s|  y wr   )r]   )r   ps     r   r   z%_get_var_lib_cloud.<locals>.<genexpr>  s     @qAIIK@s   z
instance/*zinstance/handlers)	itertoolschainr   r   s    r   _get_var_lib_cloudr     sW    
 ??x |$x @INN<0@*+ r   run_dirc                 $    | j                  d      S )zGet all paths under /run/cloud-init except for hook-hotplug-cmd.

    Note that this only globs the top-level directory as there are currently
    no relevant files within subdirectories.
    *r   r   s    r   _get_run_dirr   $  s     <<r   c                    t        |        t        | |       t        | |       t        |      D ]>  }t	        || t        j                  |      j                  j                  d      z  d       @ t        j                  t               t        |      t        |            D ]>  }t	        || t        j                  |      j                  j                  d      z  |       @ y)z8Collect all cloud-init logs into the provided directory./Tr   r   N)rr   rx   rl   r{   rb   rg   rh   rH   relative_tor   r   r   r   r   )rc   ry   r   r   r[   logfiles         r   _collect_logs_into_tmp_dirr   -  s     '""34G%67&w/ 
 	gll7+22>>sCC	
	
 ??Y/W% 	

 	gll7+22>>sCC	
	
r   z/run/cloud-initz/var/lib/cloudTtarfilec                    t         j                  j                  |       } t        j                  t
        j                        j                         j                  d      }t        |      5 }t        j                  ||      }t        |||||       t        dd| d|t        |      j                  | dd      g       d	d	d	       t         j#                  d
|        y	# 1 sw Y    xY w)a  Collect all cloud-init logs and tar them up into the provided tarfile.

    :param tarfile: The path of the tar-gzipped file to create.
    :param log_cfg: The cloud-init base configuration containing logging cfg.
    :param run_dir: The path to the cloud-init run directory.
    :param cloud_dir: The path to the cloud-init cloud directory.
    :param include_sensitive: Boolean, true means include sensitive data.
    zcloud-init-logs-%Y-%m-%d)dir)rc   ry   r   r   r[   tarczfz-Cr    NzWrote %s)osr   abspathr   nowr   utcdatestrftimer   rg   rh   r   r   r   replacerK   info)r   ry   r   r   r[   dir_nametmp_dirrc   s           r   collect_logsr   N  s     ggoog&GX\\"'')223MN  
W	 
,,w1"/	
 	G$$y]B7		

& HHZ!'
 
s   ,ACC(r4   c                 h   t        j                          | dk(  rt        j                  }n&| dk(  rt        j                  }nt         j
                  }t        j                  |       t        j                         }|j                  t        j                  d             t        j                  |       y)zSet up the logger for CLI use.

    The verbosity controls which level gets printed to stderr. By default,
    DEBUG and TRACE are hidden.
    r   re   z%(message)sN)r   reset_loggingloggingINFODEBUGTRACErK   setLevelStreamHandlersetFormatter	Formatter
addHandler)r4   levelhandlers      r   _setup_loggerr   w  sx     A~	aLL##%G**=9:NN7r   redact_sensitiveinclude_userdatac                    t        |       t        j                         dk7  rt        d      |rt        j                  d       t        g       }|j                          t        | |j                  t        j                  |j                  j                        t        j                  |j                  j                        |        |st        j                  d       yy)z:Handle calls to 'cloud-init collect-logs' as a subcommand.r   z!This command must be run as root.z;The --include-userdata flag is deprecated and does nothing.)ds_deps)r   ry   r   r   r[   zWARNING:
Sensitive data may have been included in the collected logs.
Please review the contents of the tarball before sharing or
rerun with --redact-sensitive to redact sensitive data.N)r   r   getuidRuntimeErrorrK   warningr   read_cfgr   cfgrg   rh   pathsr   r   )r   r4   r   r   inits        r   collect_logs_clir     s     )	yy{a>??I	
 DMMOTZZ//0,,tzz334.. F	
 r   _nameargsc                    t               j                         }	 t        |j                  |j                  |j
                  |j                         y# t        $ r%}t        |t        j                         Y d}~yd}~ww xY w)z}Handle the CLI interface to the module.

    Parse CLI args, redirect all exceptions to stderr, and return an exit code.
    )r4   r   r   r   r   )fileNre   )r>   
parse_argsr   r4   r   r   r:   	ExceptionprintsysrS   )r   r   rO   s      r   handle_collect_logs_argsr     se    
 <""$D
nnLL!22!]]		
  acjj!s   7A 	B A;;B __main__r   r   )r   TF)?__doc__r;   r   r   r   rg   r^   rU   r   r   r   typingr   r   r   r   r	   r
   r   cloudinit.logr   cloudinit.stagesr   cloudinit.subpr   r   cloudinit.temp_utilsr   cloudinit.utilr   r   r   CustomLoggerType	getLoggerr   rK   r   ri   rf   r<   r>   r   rh   rP   rY   boolrb   rl   rr   rx   r{   r   r   r   r   r   intr   r   	Namespacer   exitr   r   r   r   <module>r      sh   N    	    
 ' H H H ! ! 6 ( @ @
7##%6W%6%6x%@A  24I "$568:MN$   @(K79O 79O 6D: B D B G"
 9=I5}E9;GC" L 156X,,-66r	c|| 
 c]	&D	cD&||D25D	D&1
,,1!(1BF1	1\\.2	*.7<< .D . \\.2	,!#s(^!gll! #/',,|"<<<gll,',, 8GLL3I ',, 8GLL+A 
\\
#s(^
 \\
 ||	

 
 

H )GLL):;*gll+;<"&"&"#s(^&" \\&" ||	&"
 &" 
&"RS T * !"	


 
 	

 

BC x/A/A c & zCHH%b*,*A*A*CDE r   