Coverage for certbot/reverter.py : 97%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
"""Reverter class saves configuration checkpoints and allows for recovery."""
"""Reverter 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.interfaces.IConfig`
"""
config.backup_dir, constants.CONFIG_DIRS_MODE, compat.os_geteuid(), self.config.strict_permissions)
"""Reload 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
""" # We have a partial or incomplete recovery "Incomplete or failed recovery for %s", self.config.temp_checkpoint_dir, )
"""Revert '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
""" # Sanity check input
"Certbot hasn't modified your configuration, so rollback " "isn't available.") rollback, len(backups))
"Unable to load checkpoint during rollback")
"""Displays all saved checkpoints.
All checkpoints are printed by :meth:`certbot.interfaces.IDisplay.notification`.
.. todo:: Decide on a policy for error handling, OSError IOError...
:raises .errors.ReverterError: If invalid directory structure.
""" backups = backups[:num]
# Make sure there isn't anything unexpected in the backup folder # There should only be timestamped (float) directories "Invalid directories in {0}".format(self.config.backup_dir))
os.linesep.join(output), force_interactive=True, pause=False)
"""Add files to temporary checkpoint.
:param set save_files: set of filepaths to save :param str save_notes: notes about changes during the save
""" self.config.temp_checkpoint_dir, save_files, save_notes)
"""Add files to a permanent checkpoint.
:param set save_files: set of filepaths to save :param str save_notes: notes about changes during the save
""" # Check to make sure we are not overwriting a temp file self.config.in_progress_dir, save_files, save_notes)
"""Add 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
""" cp_dir, constants.CONFIG_DIRS_MODE, compat.os_geteuid(), self.config.strict_permissions)
os.path.join(cp_dir, "FILEPATHS"))
# No need to copy/index already existing files # The oldest copy already exists in the directory... # Tag files with index so multiple files can # have the same filename cp_dir, os.path.basename(filename) + "_" + str(idx))) # http://stackoverflow.com/questions/4726260/effective-use-of-python-shutil-copy2 "Unable to add file %s to checkpoint %s", filename, cp_dir) "Unable to add file {0} to checkpoint " "{1}".format(filename, cp_dir))
"""Reads the file lines and returns a file obj.
Read the file returning the lines, and a pointer to the end of the file.
""" # Open up filepath differently depending on if it already exists else:
"""Recover 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
""" # Undo all commands # Revert all changed files cp_dir, os.path.basename(path) + "_" + str(idx)), path) # This file is required in all checkpoints. "Unable to recover files from %s" % cp_dir)
# Remove any newly added files if they exist
"Unable to remove directory: %s" % cp_dir)
"""Run all commands in a file.""" # NOTE: csv module uses native strings. That is, bytes on Python 2 and # unicode on Python 3 "Unable to run undo command: %s", " ".join(command))
"""Verify 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.
"""
# Get temp modified files
# Get temp new files
# Verify no save_file is in protected_files "Attempting to overwrite challenge " "file - %s" % filename)
r"""Register 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.
""" # Make sure some files are provided... as this is an error # Made this mistake in my initial implementation of apache.dvsni.py
# Append all new files (that aren't already registered)
"Unable to register file creation(s) - {0}".format(files)) finally:
"""Register 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
""" else:
"Unable to register undo command.") finally:
"""Return the proper reverter directory.""" else:
cp_dir, constants.CONFIG_DIRS_MODE, compat.os_geteuid(), self.config.strict_permissions)
"""Revert 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
""" # First, any changes found in IConfig.temp_checkpoint_dir are removed, # then IN_PROGRESS changes are removed The order is important. # IN_PROGRESS is unable to add files that are already added by a TEMP # change. Thus TEMP must be rolled back first because that will be the # 'latest' occurrence of the file. # We have a partial or incomplete recovery "checkpoint - %s", self.config.in_progress_dir) "Incomplete or failed recovery for IN_PROGRESS checkpoint " "- %s" % self.config.in_progress_dir)
"""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
""" # Check to see that file exists to differentiate can't find file_list # and can't remove filepaths within file_list errors. # Files are registered before they are added... so # check to see if file exists first else: "File: %s - Could not be found to be deleted %s - " "Certbot probably shut down unexpectedly", os.linesep, path) "Unable to remove filepaths contained within %s", file_list) "Unable to remove filepaths contained within " "{0}".format(file_list))
"""Finalize the checkpoint.
Timestamps and permanently saves all changes made through the use of :func:`~add_to_checkpoint` and :func:`~register_file_creation`
:param str title: Title describing checkpoint
:raises certbot.errors.ReverterError: when the checkpoint is not able to be finalized.
""" # Check to make sure an "in progress" directory exists
# Add title to self.config.in_progress_dir CHANGES_SINCE
# Move self.config.in_progress_dir to Backups directory
# rename the directory as a timestamp
"Determine the timestamp of the checkpoint, enforcing monotonicity." timetravel = str(float(others[-1]) + 1) logger.warning("Current timestamp %s does not correspond to newest reverter " "checkpoint; your clock probably jumped. Time travelling to %s", timestamp, timetravel) timestamp = timetravel # It is possible if the checkpoints are made extremely quickly # that will result in a name collision. logger.debug("Race condition with timestamp %s, incrementing by 0.01", timestamp) timetravel = str(float(others[-1]) + 0.01) timestamp = timetravel
"""Timestamp the checkpoint.""" # It is possible save checkpoints faster than 1 per second resulting in # collisions in the naming convention.
# After 10 attempts... something is probably wrong here... "Unable to finalize checkpoint, %s -> %s", self.config.in_progress_dir, final_dir) "Unable to finalize checkpoint renaming") |