Ejemplo n.º 1
0
    def load(self, filename):
        """Load configuration file.

        :param filename: 

        """
        # Protect against directory traversals.
        filename = os_path.basename(filename)

        # Absolute path to configuration file.
        filepath = os_path.join(self.CONFIG_PATH, filename)

        # FIXME: Use ``os_path.exists``.
        try:
            os.stat(filepath)
        except OSError:
            return

        log.info('Reading configuration file {}'.format(filepath))
        try:
            with open(filepath, "r") as instream:
                payload = instream.read()
                data = json.loads(payload)
                return data

        except Exception as ex:
            log.exc(ex, 'Reading configuration from "{}" failed'.format(filepath))
def backup_file(filename, backup_path, backup_count):
    """
    Backup file using a rotation mechanism.

    :param filename:
    :param backup_path:
    :param backup_count:
    :return:
    """

    # Sanity checks.
    if not file_exists(filename):
        log.info('File {} does not exist, skipping backup'.format(filename))
        return

    #log.info('Preparing backup')
    # Running this here will crash the machine.
    #ensure_directory(backup_path)

    filepath = os_path.join(backup_path, os_path.basename(filename))
    outfile = RotatingFile(filepath, backup_count)

    log.info('Creating backup of {}'.format(filename))
    with open(filename, "r") as f:
        outfile.write(f)
Ejemplo n.º 3
0
    def save(self, filename, instream):
        """
        Save configuration file, with rotating backup.
        """
        import uos

        # Protect against directory traversals.
        filename = os_path.basename(filename)

        # Only allow specific filenames.
        if 'settings' not in filename:
            raise ValueError(
                'Writing arbitrary files to the system is prohibited')

        # Absolute path to configuration file.
        filepath = os_path.join(self.CONFIG_PATH, filename)

        # Number of backup files to keep around.
        backup_count = self.get('main.backup.file_count', 7)

        # Backup configuration file.
        log.info(
            'Backing up file {} to {}, keeping a history worth of {} files'.
            format(filepath, self.BACKUP_PATH, backup_count))
        backup_file(filepath, self.BACKUP_PATH, backup_count)

        # Overwrite configuration file.
        log.info('Saving configuration file {}'.format(filepath))
        with open(filepath, "w") as outstream:
            if isinstance(instream, str):
                outstream.write(instream)
            else:
                copyfileobj(instream, outstream)

        uos.sync()