o 6aT@sdZddlZddlZddlZddlZddlZddlZddlmZddlm Z ddl m Z ddl m Z ddl mZeeZGdd d ZdS) zGReverter class saves configuration checkpoints and allows for recovery.N)errors)util) constants) filesystem)osc@seZdZdZddZddZd(ddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'S))ReverteraqReverter Class - save and revert configuration checkpoints. This class can be used by the plugins, especially Installers, to undo changes made to the user's system. Modifications to files and commands to do undo actions taken by the plugin should be registered with this class before the action is taken. Once a change has been registered with this class, there are three states the change can be in. First, the change can be a temporary change. This should be used for changes that will soon be reverted, such as config changes for the purpose of solving a challenge. Changes are added to this state through calls to :func:`~add_to_temp_checkpoint` and reverted when :func:`~revert_temporary_config` or :func:`~recovery_routine` is called. The second state a change can be in is in progress. These changes are not temporary, however, they also have not been finalized in a checkpoint. A change must become in progress before it can be finalized. Changes are added to this state through calls to :func:`~add_to_checkpoint` and reverted when :func:`~recovery_routine` is called. The last state a change can be in is finalized in a checkpoint. A change is put into this state by first becoming an in progress change and then calling :func:`~finalize_checkpoint`. Changes in this state can be reverted through calls to :func:`~rollback_checkpoints`. As a final note, creating new files and registering undo commands are handled specially and use the methods :func:`~register_file_creation` and :func:`~register_undo_command` respectively. Both of these methods can be used to create either temporary or in progress changes. .. note:: Consider moving everything over to CSV format. :param config: Configuration. :type config: :class:`certbot.configuration.NamespaceConfig` cCs ||_t|jtj|jjdS)N)configrmake_or_verify_dir backup_dirrCONFIG_DIRS_MODEstrict_permissions)selfrr2/usr/lib/python3/dist-packages/certbot/reverter.py__init__<szReverter.__init__cCsTtj|jjr(z ||jjWdStjy't d|jjtdwdS)aReload users original configuration files after a temporary save. This function should reinstall the users original configuration files for all saves with temporary=True :raises .ReverterError: when unable to revert config z$Incomplete or failed recovery for %sz!Unable to revert temporary configN) rpathisdirrtemp_checkpoint_dir_recover_checkpointr ReverterErrorloggercriticalr rrrrevert_temporary_configBs  z Reverter.revert_temporary_configcCs zt|}Wntytdtdw|dkr&tdtdt|jj }| |s9t dnt ||krHt d|t ||dkr|rtj |jj |}z||Wntjyrtdtdw|d8}|dkr|sNd Sd Sd Sd S) ayRevert 'rollback' number of configuration checkpoints. :param int rollback: Number of checkpoints to reverse. A str num will be cast to an integer. So "2" is also acceptable. :raises .ReverterError: if there is a problem with the input or if the function is unable to correctly revert the configuration checkpoints z,Rollback argument must be a positive integerz Invalid InputrzHCertbot hasn't modified your configuration, so rollback isn't available.z0Unable to rollback %d checkpoints, only %d existz)Failed to load checkpoint during rollbackz)Unable to load checkpoint during rollbackrN)int ValueErrorrerrorrrrlistdirrr sortwarninglenrjoinpoprr)r rollbackbackupscp_dirrrrrollback_checkpointsVs>         zReverter.rollback_checkpointscCs||jj||dS)zAdd files to temporary checkpoint. :param set save_files: set of filepaths to save :param str save_notes: notes about changes during the save N)_add_to_checkpoint_dirrrr save_files save_notesrrradd_to_temp_checkpoints zReverter.add_to_temp_checkpointcCs ||||jj||dS)zAdd files to a permanent checkpoint. :param set save_files: set of filepaths to save :param str save_notes: notes about changes during the save N)_check_tempfile_savesr(rin_progress_dirr)rrradd_to_checkpoints  zReverter.add_to_checkpointc Cst|tj|jj|tj |d\}}t |}|D]K}||vrgt d|zt |tj |tj|dt||d|Wntyb|t d||td||w|d7}q|ttj |dd }||Wd d S1swYd S) agAdd save files to checkpoint directory. :param str cp_dir: Checkpoint directory filepath :param set save_files: set of files to save :param str save_notes: notes about changes made during the save :raises IOError: if unable to open cp_dir + FILEPATHS file :raises .ReverterError: if unable to add checkpoint FILEPATHSzCreating backup of %s_{0} z&Unable to add file %s to checkpoint %sz(Unable to add file {0} to checkpoint {1}r CHANGES_SINCEaN)rr rr rr _read_and_appendrrr"r!rdebugshutilcopy2basenamestrwriteformatIOErrorcloserrropen) r r&r*r+op_fdexisting_filepathsidxfilenamenotes_fdrrrr(s@      "zReverter._add_to_checkpoint_dircCs@tj|rt|d}|}||fSg}t|d}||fS)zReads the file lines and returns a file obj. Read the file returning the lines, and a pointer to the end of the file. zr+w)rrisfiler?read splitlines)r filepathr@linesrrrr5s    zReverter._read_and_appendc Cs:tjtj|dr|tj|dtjtj|drvz?ttj|d,}|}t|D]\}}t tj|tj |dt ||q5Wdn1sYwYWnt tfyutd|td|w|tj|dzt |WdStytd|td|w)aRecover a specific checkpoint. Recover a specific checkpoint provided by cp_dir Note: this function does not reload augeas. :param str cp_dir: checkpoint directory file path :raises errors.ReverterError: If unable to recover checkpoint COMMANDSr0r1NzUnable to recover files from %s NEW_FILESzUnable to remove directory: %s)rrrFr"_run_undo_commandsr?rGrH enumerater7r8r9r:r=OSErrorrrrr_remove_contained_filesrmtree)r r&paths_fd filepathsrBrrrrrs>      zReverter._recover_checkpointc Csddi}t|dfi|1}t|}tt|D]}zt|Wqtjy5t dd |YqwWddS1sAwYdS)zRun all commands in a file.newlinerzUnable to run undo command: %s N) r?csvreaderreversedlistr run_scriptrSubprocessErrorrrr")r rIkwargscsvfile csvreadercommandrrrrMs  "zReverter._run_undo_commandscCsg}tj|jjd}tj|r/t|d}|| Wdn1s*wYtj|jjd}tj|r\t|d}|| Wdn1sWwY|D] }||vrkt d|q^dS)zVerify save isn't overwriting any temporary files. :param set save_files: Set of files about to be saved. :raises certbot.errors.ReverterError: when save is attempting to overwrite a temporary file. r0rVNrLz+Attempting to overwrite challenge file - %s) rrr"rrrFr?extendrGrHrr)r r*protected_files temp_path protected_fdnew_pathrCrrrr- s(     zReverter._check_tempfile_savesc Gs|std||}d}zDz|tj|d\}}|D]}||vr,|d|qWnt t fyEt d|td|wW|durQ| dSdS|dur\| ww)aARegister the creation of all files during certbot execution. Call this method before writing to the file to make sure that the file will be cleaned up if the program exits unexpectedly. (Before a save occurs) :param bool temporary: If the file creation registry is for a temp or permanent save. :param \*files: file paths (str) to be registered :raises certbot.errors.ReverterError: If call does not contain necessary parameters or if the file creation is unable to be registered. z,Forgot to provide files to registration callNrLr2z(Unable to register file creation(s) - %sz)Unable to register file creation(s) - {0})rr _get_cp_dirr5rrr"r;r<r=rOrrr>)r temporaryfilesr&new_fdex_filesrrrrregister_file_creation(s.     zReverter.register_file_creationc Cstj||d}ddi}z2tj|rdnd}t||fi|}t|}||WdWdS1s9wYWdSt t fySt dt dw) aRegister a command to be run to undo actions taken. .. warning:: This function does not enforce order of operations in terms of file modification vs. command registration. All undo commands are run first before all normal files are reverted to their previous state. If you need to maintain strict order, you may create checkpoints before and after the the command registration. This function may be improved in the future based on demand. :param bool temporary: Whether the command should be saved in the IN_PROGRESS or TEMPORARY checkpoints. :param command: Command to be run. :type command: list of str rKrTrUr4rENzUnable to register undo commandz Unable to register undo command.)rrr"rgrFr?rXwriterwriterowr=rOrrrr)r rhra commands_fpr^modef csvwriterrrrregister_undo_commandOs  & zReverter.register_undo_commandcCs.|r|jj}n|jj}t|tj|jj|S)z%Return the proper reverter directory.)rrr.rr rr r )r rhr&rrrrgms  zReverter._get_cp_dircCsd|tj|jjr0z ||jjWdStjy/t d|jjtd|jjwdS)aCRevert configuration to most recent finalized checkpoint. Remove all changes (temporary and permanent) that have not been finalized. This is useful to protect against crashes and other execution interruptions. :raises .errors.ReverterError: If unable to recover the configuration z=Incomplete or failed recovery for IN_PROGRESS checkpoint - %sN) rrrrrr.rrrrrrrrrrecovery_routineyszReverter.recovery_routinec Cstj|sdSz7t|d'}|}|D]}tj|r%t|qt d|qWdWdS1s8wYWdSt t fyVt d|t d|w)a Erase all files contained within file_list. :param str file_list: file containing list of file paths to be deleted :returns: Success :rtype: bool :raises certbot.errors.ReverterError: If all files within file_list cannot be removed FrVzVFile: %s - Could not be found to be deleted - Certbot probably shut down unexpectedlyNz.Unable to remove filepaths contained within %sz/Unable to remove filepaths contained within {0}T)rrrFr?rGrHlexistsremoverr r=rOrrrr<)r file_listlist_fdrSrrrrrPs4      z Reverter._remove_contained_filesc CsFtj|jjs dStj|jjd}tj|jjd}tj|sAtdt |d }| dWdn1ssz2Reverter._checkpoint_timestamp..rzyCurrent timestamp %s does not correspond to newest reverter checkpoint; your clock probably jumped. Time travelling to %sz6Race condition with timestamp %s, incrementing by 0.01g{Gz?)r:timeglobrrr"rr appendrfloatrr r!r6)r timestampothers timetravelrrr_checkpoint_timestamps"    zReverter._checkpoint_timestampc CsztdD]*}|}tj|jj|}z t|jj |WdSt y.t d|Yqwt d|jj |td)zTimestamp the checkpoint.Nz(Unexpected race condition, retrying (%s)z'Unable to finalize checkpoint, %s -> %sz&Unable to finalize checkpoint renaming)rangerrrr"rr rreplacer.rOrr rrr)r r1r final_dirrrrr~s  z Reverter._timestamp_progress_dirN)r)__name__ __module__ __qualname____doc__rrr'r,r/r(r5rrMr-rlrsrgrtrPrrr~rrrrrs() *  -'' &) r)rrXrloggingr7rr|certbotrrcertbot._internalrcertbot.compatrr getLoggerrrrrrrrs