U
    Ldr'                     @   s  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mZ ddlmZ ddl	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mZ ddgZdZG d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ed-d.d/Zed-d0d1Z dHd2d3Z!d4d5 Z"d6d7 Z#d8d9 Z$d:d; Z%d<d= Z&d>d? Z'dIe(d@dAdBZ)dCdD Z*dEdF Z+e,dGkre-e+  dS )JzGDefine 'collect-logs' utility and handler to include in cloud-init cmd.    N)datetime)Path)
NamedTuple)read_cfg_paths)Paths)ProcessExecutionErrorsubp)tempdir)chdircopy
ensure_dir
write_filez/var/log/cloud-init.logz/var/log/cloud-init-output.logz/run/cloud-initc                   @   s   e Zd ZU eed< eed< dS )
ApportFilepathZlabelN)__name__
__module____qualname__str__annotations__ r   r   :/usr/lib/python3/dist-packages/cloudinit/cmd/devel/logs.pyr      s   
r   z(/var/log/installer/autoinstall-user-dataZAutoInstallUserDataz/autoinstall.yamlZAutoInstallYAMLz'/etc/cloud/cloud.cfg.d/99-installer.cfgZInstallerCloudCfgz//var/log/installer/ubuntu_desktop_installer.logZUdiLogz-/var/log/installer/subiquity-server-debug.logZSubiquityServerDebugz-/var/log/installer/subiquity-client-debug.logZSubiquityClientDebugz%/var/log/installer/curtin-install.logZ	CurtinLogz0/var/log/installer/subiquity-curtin-install.confZCurtinInstallConfigz8/var/log/installer/curtin-install/subiquity-initial.confZCurtinConfigInitialz:/var/log/installer/curtin-install/subiquity-curthooks.confZCurtinConfigCurtHooksz8/var/log/installer/curtin-install/subiquity-extract.confZCurtinConfigExtractz=/var/log/installer/curtin-install/subiquity-partitioning.confZCurtinConfigPartitioningz(/var/log/installer/curtin-error-logs.tarZCurtinErrorz$/var/log/installer/curtin-errors.tarz(/var/log/installer/block/probe-data.jsonZ	ProbeData)returnc                  C   s   t  } | dS )NZuserdata_raw)r   Zget_ipath_curpathsr   r   r   _get_user_data_fileN   s    r   c                  C   s   t  } | dS )Ndata)r   Z	get_cpathr   r   r   r   _get_cloud_data_pathS   s    r   c              	   C   s`   | st jddd} | jdddddd	d
 | jddddd t }| jdd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.
    collect-logsz)Collect and tar all cloud-init debug info)progZ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)r"   r$   z--include-userdataz-uF
store_trueuserdatazPOptionally include user-data from {0} which could contain sensitive information.)r"   r!   r#   r$   )argparseArgumentParseradd_argumentr   format)parseruser_data_filer   r   r   
get_parserX   s>    		r-   c                 C   s*   dg}t  dkr&|ti jd  |S )z>Return a list of files to ignore for /run/cloud-init directoryzhook-hotplug-cmdr   Zinstance_data_sensitive)osgetuidappendr   Zlookups)curdirfilesZignored_filesr   r   r   _copytree_rundir_ignore_files   s
    r3   c              
   C   s   t tj| zt| j}W n@ tk
r^ } z"t|t| t	d| d| W 5 d}~X Y n X t|| t	d| d| |S dS )CHelper which runs a command and writes output or error to filename.collecting %s failed.
   Ncollected %s
)
r   r.   r   dirnamer   stdoutr   r   r   _debug)cmdfilenamemsgr    outputer   r   r   _write_command_output_to_file   s    "
r@   c              
   C   s   t tj| z*t|d}tj| ||d W 5 Q R X W n@ tk
rz } z"t|t	| t
d| d| W 5 d}~X Y nX t
d| d| dS )r4   w)r9   stderrr5   r6   Nr7   )r   r.   r   r8   open
subprocesscallOSErrorr   r   r:   )r;   r<   r=   r    fr?   r   r   r   _stream_command_output_to_file   s    "rH   c                 C   s   ||krt j|  d S )N)sysrB   write)r=   levelr    r   r   r   r:      s    r:   c                 C   s<   t j| r(t| | td|  d| ntd|  d| d S )Nzcollected file: %s
r6   zfile %s did not exist
   )r.   r   isfiler   r:   )r   Zout_dirr    r   r   r   _collect_file   s    
rN   c                 C   s   t D ]:}t| |j j}| s,tt| t|jt|| q|rtD ]:}t| |j j}| sptt| t|jt|| qHdS )z'Obtain subiquity logs and config files.N)	INSTALLER_APPORT_FILESr   r   parentexistsr   r   rN    INSTALLER_APPORT_SENSITIVE_FILES)log_dirinclude_userdatar    Zsrc_fileZdestination_dirr   r   r   collect_installer_logs   s    rU   )rT   c                 C   s  |r t  dkr tjd dS t j| } t 	 
d}tdd}t j||}tddgt j|d	d
|d}tddddgt j|dd|d}|s|r|nd}td| td| d| tdgt j|dd|d tddddgt j|dd|d tD ]}t||| q|r2t }t||| t||| t j|d}	t|	 t jtrztjtt j|	dtd W nF tjk
r }
 z$tjd tjt|
d   W 5 d!}
~
X Y nX td"t d| ntd#t d| t jt jtd$r2tt }| r2tt|t|t|  t|" t d%d&| |!|d' d(g W 5 Q R X W 5 Q R X tjd)|   dS )*zCollect all cloud-init logs and tar them up into the provided tarfile.

    @param tarfile: The path of the tar-gzipped file to create.
    @param include_userdata: Boolean, true means include user-data.
    r   zMTo include userdata, root user is required. Try sudo cloud-init collect-logs
r6   zcloud-init-logs-%Y-%m-%dz/tmp)dirz
cloud-initz	--versionversionzcloud-init --version)r;   r<   r=   r    z
dpkg-queryz--showz-f=${Version}
zdpkg-versionzdpkg versionznot-availablez	version: z!collected cloud-init version: %s
Zdmesgz	dmesg.txtzdmesg outputZ
journalctlz--boot=0z-ozshort-precisezjournal.txtzsystemd journal of current bootrun)ignorez(Failed collecting file(s) due to error:

Nzcollected dir %s
zdirectory '%s' did not exist
ZdisabledZtarZczvf/ z	Wrote %s
)"r.   r/   rI   rB   rJ   r   abspathr   Zutcnowdatestrftimer	   joinr@   printr:   rH   CLOUDINIT_LOGSrN   r   rU   r   rQ   CLOUDINIT_RUN_DIRshutilZcopytreer3   Errorr   r   r   r
   r   replace)tarfilerT   r    rS   Ztmp_dirrW   Zdpkg_verlogr,   Zrun_dirr?   Zcloud_data_dirr   r   r   collect_logs   s    



&


0ri   c                 C   s   t |j|j|jS )z:Handle calls to 'cloud-init collect-logs' as a subcommand.)ri   rg   r&   r    )nameargsr   r   r   handle_collect_logs_args  s    rl   c                  C   s   t  } td|  S )z4Tool to collect and tar all cloud-init related logs.r   )r-   rl   
parse_args)r+   r   r   r   main"  s    rn   __main__)N)r   ).__doc__r'   r.   rd   rD   rI   r   pathlibr   typingr   Zcloudinit.cmd.develr   Zcloudinit.helpersr   Zcloudinit.subpr   r   Zcloudinit.temp_utilsr	   Zcloudinit.utilr
   r   r   r   rb   rc   r   rR   rO   r   r   r   r-   r3   r@   rH   r:   rN   rU   boolri   rl   rn   r   exitr   r   r   r   <module>   s    	  %
.U
