3 \me @ s d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl m Z ddlmZm Z mZ ddlmZmZmZmZmZmZ dZd d ddd dgZdgZdddZdddZdd Zdd Zedkre dS )zEDefine 'clean' utility and handler as part of cloud-init commandline. N)settings)uses_systemd)Init)ProcessExecutionErrorrunpartssubp)del_dirdel_fileerrorget_config_logfilesis_link write_filez/etc/machine-idz/etc/netplan/50-cloud-init.yamlz-/etc/NetworkManager/conf.d/99-cloud-init.confz?/etc/NetworkManager/conf.d/30-cloud-init-ip6-addr-gen-mode.confz@/etc/NetworkManager/system-connections/cloud-init-*.nmconnectionz,/etc/systemd/network/10-cloud-init-*.networkz+/etc/network/interfaces.d/50-cloud-init.cfgz)/etc/ssh/sshd_config.d/50-cloud-init.confc C s | st jddd} | jdddddd d | jddddd | jdddddd | jddddddd | jdddddgg dddd | S )a# Build or extend an arg parser for clean utility. @param parser: Optional existing ArgumentParser instance representing the clean subcommand which will be extended to support the args of this utility. @returns: ArgumentParser with proper argument configuration. cleanzJRemove logs, configs and artifacts so cloud-init re-runs on a clean system)progdescriptionz-lz--logs store_trueFremove_logszRemove cloud-init logs.)actiondefaultdesthelpz--machine-idzSet /etc/machine-id to 'uninitialized ' for golden imagecreation. On next boot, systemd generates a new machine-id. Remove /etc/machine-id on non-systemd environments.)r r r z-rz--rebootz;Reboot system after logs are cleaned so cloud-init re-runs.z-sz--seedremove_seedz5Remove cloud-init seed directory /var/lib/cloud/seed.z-cz --configsall ssh_confignetwork+ remove_configzbRemove cloud-init generated config files of a certain type. Config types: all, ssh_config, network)choicesr nargsr r )argparseArgumentParseradd_argument)parser r# /usr/lib/python3.6/clean.py get_parser) sP r% Fc C s t g d}|j | r2xt|jD ]}t| q"W |rrt|jddgrrx(tD ] }xtj|D ]}t| q^W qNW |rt|jddgrxt D ]}t| qW t jj|j jsdS t jj|j jd}xtjd|j j D ]|}||kr| rqy0t jj|rt| rt| nt| W q tk rR } ztdj|t| d S d }~X qX qW yttj W n8 tk r } ztdtj d| d S d }~X nX dS ) a Helper which removes artifacts dir and optionally log files. @param: remove_logs: Boolean. Set True to delete the cloud_dir path. False preserves them. @param: remove_seed: Boolean. Set True to also delete seed subdir in paths.cloud_dir. @param: remove_config: List of strings. Can be any of: all, network, ssh_config. @returns: 0 on success, 1 otherwise. )Zds_depsr r r r Zseedz%s/*zCould not remove {0}: {1} NzFailure during run-parts of z: )r Zread_cfgr Zcfgr setintersectionGEN_NET_CONFIG_FILESglobGEN_SSH_CONFIG_FILESospathisdirpathsZ cloud_dirjoinr r OSErrorr formatstrr r ZCLEAN_RUNPARTS_DIR Exception) r r r ZinitZlog_filer- ZconfZ seed_pather# r# r$ remove_artifactsl sB r6 c C s t |j|j|j}|jr6t r.ttddd ntt |dkr|j rdddg}yt |dd W n: tk r } ztd j |t| d}W Y dd}~X nX |S ) z3Handle calls to 'cloud-init clean' as a subcommand.zuninitialized i$ )moder Zshutdownz-rZnowF)Zcapturez-Could not reboot this system using "{0}": {1}r&