コード例 #1
0
ファイル: utilities.py プロジェクト: tutugreen/dynamite-nsm
def backup_configuration_file(source_file, configuration_backup_directory,
                              destination_file_prefix):
    """
    Backup a configuration file

    :param source_file: The configuration file you wish to backup
    :param configuration_backup_directory: The destination configuration directory
    :param destination_file_prefix: The prefix of the file; timestamp is automatically appended in filename
    """
    timestamp = int(time.time())
    destination_backup_config_file = os.path.join(
        configuration_backup_directory, '{}.{}'.format(destination_file_prefix,
                                                       timestamp))
    try:
        makedirs(configuration_backup_directory, exist_ok=True)
    except Exception as e:
        raise exceptions.WriteConfigError(
            "General error while attempting to create backup directory at {}; {}"
            .format(configuration_backup_directory, e))
    try:
        shutil.copy(source_file, destination_backup_config_file)
    except Exception as e:
        raise exceptions.WriteConfigError(
            "General error while attempting to copy {} to {}".format(
                source_file, destination_backup_config_file, e))
コード例 #2
0
ファイル: config.py プロジェクト: DynamiteAI/dynamite-nsm
    def commit(self,
               out_file_path: Optional[str] = None,
               backup_directory: Optional[str] = None) -> None:
        """Write out an updated configuration file, and optionally backup the old one.
        Args:
            out_file_path: The path to the output file; if none given overwrites existing
            backup_directory: The path to the backup directory
        Returns:
            None
        """

        # Backup old configuration first
        out_file_name = os.path.basename(out_file_path)
        backup_file_name = out_file_name + '.backup'
        if backup_directory:
            utilities.backup_configuration_file(
                out_file_path,
                backup_directory,
                destination_file_prefix=backup_file_name)
        try:
            with open(out_file_path, 'w') as config_raw_f:
                config_raw_f.write(self.formatted_data)
        except IOError:
            raise general_exceptions.WriteConfigError(
                'An error occurred while writing the configuration file to disk.'
            )
        utilities.set_permissions_of_file(out_file_path, 644)
        self.logger.warning(
            'Configuration updated. Restart this service to apply.')
コード例 #3
0
ファイル: config.py プロジェクト: DynamiteAI/dynamite-nsm
    def commit(self,
               out_file_path: Optional[str] = None,
               backup_directory: Optional[str] = None) -> None:
        """Write out an updated configuration file, and optionally backup the old one.
        Args:
            out_file_path: The path to the output file; if none given overwrites existing
            backup_directory: The path to the backup directory
        Returns:
            None
        """

        # Backup old configuration first
        out_file_name = os.path.basename(out_file_path)
        backup_file_name = out_file_name + '.backup'
        self.formatted_data = f'-Xms{self.initial_memory}\n-Xmx{self.maximum_memory}\n' + \
                              '\n'.join(self._raw_extra_params)
        if backup_directory:
            utilities.backup_configuration_file(
                out_file_path,
                backup_directory,
                destination_file_prefix=backup_file_name)
        try:
            with open(out_file_path, 'w') as config_raw_f:
                config_raw_f.write(self.formatted_data)
        except IOError:
            raise general_exceptions.WriteConfigError(
                'An error occurred while writing the configuration file to disk.'
            )
        utilities.set_permissions_of_file(out_file_path, 644)
コード例 #4
0
ファイル: config.py プロジェクト: DynamiteAI/dynamite-nsm
    def commit(self,
               out_file_path: Optional[str] = None,
               backup_directory: Optional[str] = None,
               top_text: Optional[str] = None) -> None:
        """Write out an updated configuration file, and optionally backup the old one.
        Args:
            out_file_path: The path to the output file; if none given overwrites existing
            backup_directory: The path to the backup directory
            top_text: The text to be appended at the top of the config file (typically used for YAML version header)
        Returns:
            None
        """
        out_file_name = os.path.basename(out_file_path)
        backup_file_name = out_file_name + '.backup'

        def update_dict_from_path(path, value) -> None:
            """Update the internal YAML dictionary object with the new values from our config
            Args:
                path: A tuple representing each level of a nested path in the yaml document ('vars', 'address-groups', 'HOME_NET') = /vars/address-groups/HOME_NET
                value: The new value
            Returns:
                 None
            """
            partial_config_data = self.config_data
            if len(path) > 1:
                for i in range(0, len(path) - 1):
                    k = path[i]
                    if isinstance(partial_config_data, dict):
                        partial_config_data = partial_config_data[k]
                    elif isinstance(partial_config_data, list):
                        for list_entry in partial_config_data:
                            if isinstance(list_entry, dict):
                                if k in list_entry.keys():
                                    partial_config_data = list_entry[k]
                    else:
                        break
            if value is None:
                return
            partial_config_data.update({path[-1]: value})

        # Backup old configuration first
        if backup_directory:
            utilities.backup_configuration_file(
                out_file_path,
                backup_directory,
                destination_file_prefix=backup_file_name)

        for k, v in vars(self).items():
            if k not in self.extract_tokens:
                continue
            token_path = self.extract_tokens[k]
            update_dict_from_path(token_path, v)
        try:
            with open(out_file_path, 'w') as config_yaml_f:
                if top_text:
                    config_yaml_f.write(f'{top_text}\n')
                try:
                    dump(self.config_data,
                         config_yaml_f,
                         default_flow_style=False,
                         Dumper=NoAliasDumper)
                except RecursionError:
                    dump(self.config_data,
                         config_yaml_f,
                         default_flow_style=False)
        except IOError:
            raise general_exceptions.WriteConfigError(
                'An error occurred while writing the configuration file to disk.'
            )
        utilities.set_permissions_of_file(out_file_path, 644)
        self.logger.warning(
            'Configuration updated. Restart this service to apply.')