U
    Ad$                     @   s  d 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dFd2d3Z d4d5 Z!d6d7 Z"d8d9 Z#d:d; Z$d<d= Z%dGe&d>d?d@Z'dAdB Z(dCdD Z)e*dEkre+e)  dS )HzGDefine '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_fileM   s    r   c                  C   s   t  } | dS )Ndata)r   Z	get_cpathr   r   r   r   _get_cloud_data_pathR   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_parserW   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   st   zt | \}}W n@ tk
rP } z"t|t| td| d| W 5 d}~X Y n X t|| td| d| |S dS )zCHelper which runs a command and writes output or error to filename.zcollecting %s failed.
   Nzcollected %s
)r   r   r   r   _debug)cmdfilenamemsgr    out_er   r   r   _write_command_output_to_file   s    "
r<   c                 C   s   ||krt j|  d S )N)sysstderrwrite)r8   levelr    r   r   r   r5      s    r5   c                 C   s<   t j| r(t| | td|  d| ntd|  d| d S )Nzcollected file: %s
r4   zfile %s did not exist
   )r.   r   isfiler   r5   )r   Zout_dirr    r   r   r   _collect_file   s    
rC   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   rC    INSTALLER_APPORT_SENSITIVE_FILES)log_dirinclude_userdatar    Zsrc_fileZdestination_dirr   r   r   collect_installer_logs   s    rJ   )rI   c                 C   sl  |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
|}tddddgt j|dd|}|s|r|nd}td| d| tdgt j|dd| tddddgt j|dd| tD ]}t||| q|rt }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"rtt }| rt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
r4   zcloud-init-logs-%Y-%m-%dz/tmp)dirz
cloud-initz	--versionversionzcloud-init --versionz
dpkg-queryz--showz-f=${Version}
zdpkg-versionzdpkg versionznot-availablez!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/   r=   r>   r?   r   abspathr   Zutcnowdatestrftimer	   joinr<   r5   CLOUDINIT_LOGSrC   r   rJ   r   rF   CLOUDINIT_RUN_DIRshutilZcopytreer3   Errorr   r   r   r
   r   replace)tarfilerI   r    rH   Ztmp_dirrL   Zdpkg_verlogr,   Zrun_dirr;   Zcloud_data_dirr   r   r   collect_logs   s    


&


0r]   c                 C   s   t |j|j|jS )z:Handle calls to 'cloud-init collect-logs' as a subcommand.)r]   r[   r&   r    )nameargsr   r   r   handle_collect_logs_args  s    r`   c                  C   s   t  } td|  S )z4Tool to collect and tar all cloud-init related logs.r   )r-   r`   
parse_args)r+   r   r   r   main  s    rb   __main__)N)r   ),__doc__r'   r.   rX   r=   r   pathlibr   typingr   Zcloudinit.cmd.develr   Zcloudinit.helpersr   Zcloudinit.subpr   r   Zcloudinit.temp_utilsr	   Zcloudinit.utilr
   r   r   r   rV   rW   r   rG   rD   r   r   r   r-   r3   r<   r5   rC   rJ   boolr]   r`   rb   r   exitr   r   r   r   <module>   s    	  %
.T
