Skip to content

config

Configuration module for the moduli generator project. Centralizes all default configuration values.

__version__ module-attribute

__version__ = get_version()

version module-attribute

version = __version__

__all__ module-attribute

__all__ = [
    "ModuliConfig",
    "default_config",
    "iso_utc_timestamp",
    "iso_utc_time_notzinfo",
    "strip_punction_from_datetime_str",
    "DEFAULT_MARIADB_DB_NAME",
    "DEFAULT_MARIADB_CNF",
    "DEFAULT_KEY_LENGTHS",
    "TEST_MARIADB_DB_NAME",
    "__version__",
]

CONST_PROJECT_NAME module-attribute

CONST_PROJECT_NAME = 'moduli_generator'

TEST_MARIADB_DB_NAME module-attribute

TEST_MARIADB_DB_NAME = 'test_moduli_db'

DEFAULT_MODULI_GENERATOR_HOME module-attribute

DEFAULT_MODULI_GENERATOR_HOME = home() / ".moduli_generator"

DEFAULT_KEY_LENGTHS module-attribute

DEFAULT_KEY_LENGTHS = (3072, 4096, 6144, 7680, 8192)

DEFAULT_NICE_VALUE module-attribute

DEFAULT_NICE_VALUE = 15

DEFAULT_MARIADB_CNF module-attribute

DEFAULT_MARIADB_CNF = 'moduli_generator.cnf'

DEFAULT_MARIADB_DB_NAME module-attribute

DEFAULT_MARIADB_DB_NAME = 'moduli_db'

DEFAULT_MARIADB_TABLE module-attribute

DEFAULT_MARIADB_TABLE = 'moduli'

DEFAULT_MARIADB_VIEW module-attribute

DEFAULT_MARIADB_VIEW = 'moduli_view'

DEFAULT_PRESERVE_MODULI_AFTER_DBSTORE module-attribute

DEFAULT_PRESERVE_MODULI_AFTER_DBSTORE = False

DEFAULT_MODULI_RECORDS_PER_KEYLENGTH module-attribute

DEFAULT_MODULI_RECORDS_PER_KEYLENGTH = 20

DEFAULT_DELETE_RECORDS_ON_MODULI_WRITE module-attribute

DEFAULT_DELETE_RECORDS_ON_MODULI_WRITE = False

CONST_CANDIDATES_DIR module-attribute

CONST_CANDIDATES_DIR = '.candidates'

CONST_MODULI_DIR module-attribute

CONST_MODULI_DIR = '.moduli'

CONST_LOG_DIR module-attribute

CONST_LOG_DIR = '.logs'

CONST_LOG_FILE_NAME module-attribute

CONST_LOG_FILE_NAME = 'moduli_generator.log'

CONST_SSH_MODULI_FILE_PREFIX module-attribute

CONST_SSH_MODULI_FILE_PREFIX = f'ssh-moduli_'

CONST_GENERATOR_TYPE module-attribute

CONST_GENERATOR_TYPE = 2

CONST_CONFIG_ID module-attribute

CONST_CONFIG_ID = 1

CONST_MODULI_FILENAME_PATTERN module-attribute

CONST_MODULI_FILENAME_PATTERN = 'moduli_????_*'

CONST_CANDIDATE_IDX_FILENAME_PATTERN module-attribute

CONST_CANDIDATE_IDX_FILENAME_PATTERN = (
    ".candidates_????_????????????????????"
)

CONST_PRIVILEGED_TMP_CNF module-attribute

CONST_PRIVILEGED_TMP_CNF = 'privileged.cnf'

CONST_MARIADB_PASSWORD_LENGTH module-attribute

CONST_MARIADB_PASSWORD_LENGTH = 32

DEFAULT_MODULI_FILE module-attribute

DEFAULT_MODULI_FILE = (
    f"ssh-moduli_{iso_utc_timestamp(compress=True)}"
)

config module-attribute

config = ModuliConfig

ModuliConfig

Class representing the configuration for Moduli generation and management.

This class is used to define directories, file patterns, database configurations, logging, and other essential components required for handling Moduli operations.

Attributes:

Name Type Description
moduli_home PosixPath

Base directory for Moduli files, derived from a user-provided path, environment variable, or a default directory.

candidates_dir PosixPath

Directory for storing candidate files.

moduli_dir PosixPath

Directory for storing Moduli files.

log_dir PosixPath

Directory for storing log files.

log_file PosixPath

Full path to the default log file.

key_lengths list

List of default key lengths for Moduli generation.

generator_type str

Default generator type used during Moduli generation.

nice_value int

Default "nice" value for adjusting process priority.

db_name str

Name of the MariaDB database used for storing Moduli data.

table_name str

Name of the MariaDB table used for Moduli storage.

view_name str

Name of the MariaDB view for querying Moduli data.

records_per_keylength int

Number of records generated or stored per key length.

config_id int

Unique ID used to link constants in the Moduli file to the database table.

mariadb_cnf PosixPath

Path to the MariaDB configuration file.

moduli_file_pattern str

Default filename pattern for Moduli files.

candidate_idx_pattern str

Default filename pattern for candidate index files.

moduli_file_pfx str

Prefix for naming Moduli output files.

moduli_file PosixPath

Path to the default Moduli file.

preserve_moduli_after_dbstore bool

Flag indicating whether to preserve Moduli files after being stored in the database.

delete_records_on_moduli_write bool

Flag indicating whether to delete database records after writing to Moduli files successfully.

version str

The version of the Moduli project.

Source code in config/__init__.py
class ModuliConfig:
    """Class representing the configuration for Moduli generation and management.

    This class is used to define directories, file patterns, database configurations, logging, and
    other essential components required for handling Moduli operations.

    Attributes:
        moduli_home (Path): Base directory for Moduli files, derived from a user-provided path,
            environment variable, or a default directory.
        candidates_dir (Path): Directory for storing candidate files.
        moduli_dir (Path): Directory for storing Moduli files.
        log_dir (Path): Directory for storing log files.
        log_file (Path): Full path to the default log file.
        key_lengths (list): List of default key lengths for Moduli generation.
        generator_type (str): Default generator type used during Moduli generation.
        nice_value (int): Default "nice" value for adjusting process priority.
        db_name (str): Name of the MariaDB database used for storing Moduli data.
        table_name (str): Name of the MariaDB table used for Moduli storage.
        view_name (str): Name of the MariaDB view for querying Moduli data.
        records_per_keylength (int): Number of records generated or stored per key length.
        config_id (int): Unique ID used to link constants in the Moduli file to the database table.
        mariadb_cnf (Path): Path to the MariaDB configuration file.
        moduli_file_pattern (str): Default filename pattern for Moduli files.
        candidate_idx_pattern (str): Default filename pattern for candidate index files.
        moduli_file_pfx (str): Prefix for naming Moduli output files.
        moduli_file (Path): Path to the default Moduli file.
        preserve_moduli_after_dbstore (bool): Flag indicating whether to preserve Moduli files
            after being stored in the database.
        delete_records_on_moduli_write (bool): Flag indicating whether to delete database records
            after writing to Moduli files successfully.
        version (str): The version of the Moduli project.
    """

    def __init__(self, base_dir: str | None = None) -> "ModuliConfig":
        """
        Class representing the configuration for Moduli generation and management. This class is used
        to define directories, file patterns, database configurations, logging, and other essential
        components required for handling Moduli operations.

        Args:
            base_dir (str | None): User-provided base directory for Moduli files. Defaults to an environment
                variable or a pre-defined directory if not specified.
        """
        # Use user-provided base dir, or env var, or default to ~/.moduli_assembly
        self.moduli_home = Path(
            base_dir or osenv.get("MODULI_HOME", DEFAULT_MODULI_GENERATOR_HOME)
        )
        self.project_name = CONST_PROJECT_NAME

        # Define subdirectories as properties
        self.candidates_dir = self.moduli_home / CONST_CANDIDATES_DIR
        self.moduli_dir = self.moduli_home / CONST_MODULI_DIR
        self.log_dir = self.moduli_home / CONST_LOG_DIR
        self.log_file = self.log_dir / CONST_LOG_FILE_NAME
        # `config_id` links `moduli_db.moduli` to `moduli_file_constants.moduli` to yield the view
        self.config_id = CONST_CONFIG_ID
        # SSH-Key Screening Generator Type (ssh-keygen)
        self.generator_type = CONST_GENERATOR_TYPE
        #
        self.moduli_file_pattern = CONST_MODULI_FILENAME_PATTERN
        self.candidate_idx_pattern = CONST_CANDIDATE_IDX_FILENAME_PATTERN
        self.moduli_file_pfx = CONST_SSH_MODULI_FILE_PREFIX

        # Other defaults (For Generation and Screening, And Linking to Moduli File Constants Table (config_id)
        self.key_lengths = DEFAULT_KEY_LENGTHS
        self.nice_value = DEFAULT_NICE_VALUE

        # Configure MariaDB
        self.db_name = DEFAULT_MARIADB_DB_NAME
        self.table_name = DEFAULT_MARIADB_TABLE
        self.view_name = DEFAULT_MARIADB_VIEW
        self.records_per_keylength = DEFAULT_MODULI_RECORDS_PER_KEYLENGTH

        # Default Mariadb Configuration
        self.mariadb_cnf = self.moduli_home / DEFAULT_MARIADB_CNF

        # Default moduli output files
        self.moduli_file = self.moduli_home / DEFAULT_MODULI_FILE

        # Delete on successful Write Flag
        self.preserve_moduli_after_dbstore = DEFAULT_PRESERVE_MODULI_AFTER_DBSTORE
        self.delete_records_on_moduli_write = DEFAULT_DELETE_RECORDS_ON_MODULI_WRITE

        # Set Project Version Number
        self.version = version

        # Set the name of Privleged Temporary MariaDB Config File
        self.privileged_tmp_cnf = CONST_PRIVILEGED_TMP_CNF
        self.password_length = CONST_MARIADB_PASSWORD_LENGTH

    def ensure_directories(self) -> "ModuliConfig":
        """
        Ensures that a set of directories (base, candidates, moduli, and log directories) exist.
                If they do not exist, they will be created. This method ensures all necessary directories
                are ready for further operations.

        Returns:
            Self: The current instance after ensuring directories exist.
        """
        for dir_path in [
            self.moduli_home,
            self.candidates_dir,
            self.moduli_dir,
            self.log_dir,
        ]:
            dir_path.mkdir(parents=True, exist_ok=True)

        return self

    def get_logger(self) -> "logging.Logger":
        """
        Initializes and returns a logger instance configured for file-based logging.

                This function ensures that the required directories and configuration files exist
                before setting up the logging system. It verifies the existence of the base logging
                directory, the default log directory, and the MariaDB configuration file. If they do not
                exist, they are created as needed. Once these prerequisites are met, the logger is
                configured with a specific logging level, format, and file output.

        Returns:
            Logging.Logger: Configured logger instance.

        Raises:
            OSError: If there is an issue, create required directories or files.
            IOError: If there is an issue, read the default MariaDB configuration file.
        """

        if not self.moduli_home.exists():
            Path(self.moduli_home).mkdir(parents=True, exist_ok=True)
        if not (self.moduli_home / CONST_LOG_DIR).exists():
            Path(self.moduli_home / CONST_LOG_DIR).mkdir(parents=True, exist_ok=True)

        # Set logging to use UTC time globally
        import logging

        logging.Formatter.converter = lambda *args: datetime.now(UTC).timetuple()

        basicConfig(
            level=DEBUG,
            format="%(asctime)s - %(levelname)s: %(message)s",
            filename=Path(self.log_file),
            filemode="a",
        )
        return getLogger()

    def get_log_file(self, name) -> Path:
        """
        Retrieve the log file path, either by name or default log file path.

                This method determines whether a specific log file name is provided. If a
                name is given, the method constructs and returns the full path to the named
                log file within the logging directory. If no name is provided, it returns the
                path to the default log file.

        Args:
            name (Optional[str]): Name of the log file to retrieve. If None, the default log file
                         path is returned.

        Returns:
            Path: The full path to the specified log file if a name is provided, or
                         the default log file path otherwise.
        """
        if name:
            return self.log_dir / name
        else:
            return self.log_file

    @staticmethod
    def with_base_dir(base_dir) -> 'ModuliConfig':
        """
        Creates a new instance of ModuliConfig with the given base directory.

                This static method provides a convenience to instantiate the ModuliConfig
                class with a specified base directory. It ensures that the provided base
                directory is explicitly set during the object creation.

        Args:
            base_dir (str): The base directory to be used for initialization.

        Returns:
            ModuliConfig: A new instance of the ModuliConfig class initialized with the given
                         base directory.
        """
        return ModuliConfig(base_dir)

    @property
    def __version__(self) -> str:
        return self.version

ensure_directories

ensure_directories()

Ensures that a set of directories (base, candidates, moduli, and log directories) exist. If they do not exist, they will be created. This method ensures all necessary directories are ready for further operations.

Returns:

Name Type Description
Self ModuliConfig

The current instance after ensuring directories exist.

Source code in config/__init__.py
def ensure_directories(self) -> "ModuliConfig":
    """
    Ensures that a set of directories (base, candidates, moduli, and log directories) exist.
            If they do not exist, they will be created. This method ensures all necessary directories
            are ready for further operations.

    Returns:
        Self: The current instance after ensuring directories exist.
    """
    for dir_path in [
        self.moduli_home,
        self.candidates_dir,
        self.moduli_dir,
        self.log_dir,
    ]:
        dir_path.mkdir(parents=True, exist_ok=True)

    return self

get_logger

get_logger()

Initializes and returns a logger instance configured for file-based logging.

    This function ensures that the required directories and configuration files exist
    before setting up the logging system. It verifies the existence of the base logging
    directory, the default log directory, and the MariaDB configuration file. If they do not
    exist, they are created as needed. Once these prerequisites are met, the logger is
    configured with a specific logging level, format, and file output.

Returns:

Type Description
Logger

Logging.Logger: Configured logger instance.

Raises:

Type Description
OSError

If there is an issue, create required directories or files.

IOError

If there is an issue, read the default MariaDB configuration file.

Source code in config/__init__.py
def get_logger(self) -> "logging.Logger":
    """
    Initializes and returns a logger instance configured for file-based logging.

            This function ensures that the required directories and configuration files exist
            before setting up the logging system. It verifies the existence of the base logging
            directory, the default log directory, and the MariaDB configuration file. If they do not
            exist, they are created as needed. Once these prerequisites are met, the logger is
            configured with a specific logging level, format, and file output.

    Returns:
        Logging.Logger: Configured logger instance.

    Raises:
        OSError: If there is an issue, create required directories or files.
        IOError: If there is an issue, read the default MariaDB configuration file.
    """

    if not self.moduli_home.exists():
        Path(self.moduli_home).mkdir(parents=True, exist_ok=True)
    if not (self.moduli_home / CONST_LOG_DIR).exists():
        Path(self.moduli_home / CONST_LOG_DIR).mkdir(parents=True, exist_ok=True)

    # Set logging to use UTC time globally
    import logging

    logging.Formatter.converter = lambda *args: datetime.now(UTC).timetuple()

    basicConfig(
        level=DEBUG,
        format="%(asctime)s - %(levelname)s: %(message)s",
        filename=Path(self.log_file),
        filemode="a",
    )
    return getLogger()

get_log_file

get_log_file(name)

Retrieve the log file path, either by name or default log file path.

    This method determines whether a specific log file name is provided. If a
    name is given, the method constructs and returns the full path to the named
    log file within the logging directory. If no name is provided, it returns the
    path to the default log file.

Parameters:

Name Type Description Default
name Optional[str]

Name of the log file to retrieve. If None, the default log file path is returned.

required

Returns:

Name Type Description
Path PosixPath

The full path to the specified log file if a name is provided, or the default log file path otherwise.

Source code in config/__init__.py
def get_log_file(self, name) -> Path:
    """
    Retrieve the log file path, either by name or default log file path.

            This method determines whether a specific log file name is provided. If a
            name is given, the method constructs and returns the full path to the named
            log file within the logging directory. If no name is provided, it returns the
            path to the default log file.

    Args:
        name (Optional[str]): Name of the log file to retrieve. If None, the default log file
                     path is returned.

    Returns:
        Path: The full path to the specified log file if a name is provided, or
                     the default log file path otherwise.
    """
    if name:
        return self.log_dir / name
    else:
        return self.log_file

with_base_dir staticmethod

with_base_dir(base_dir)

Creates a new instance of ModuliConfig with the given base directory.

    This static method provides a convenience to instantiate the ModuliConfig
    class with a specified base directory. It ensures that the provided base
    directory is explicitly set during the object creation.

Parameters:

Name Type Description Default
base_dir str

The base directory to be used for initialization.

required

Returns:

Name Type Description
ModuliConfig ModuliConfig

A new instance of the ModuliConfig class initialized with the given base directory.

Source code in config/__init__.py
@staticmethod
def with_base_dir(base_dir) -> 'ModuliConfig':
    """
    Creates a new instance of ModuliConfig with the given base directory.

            This static method provides a convenience to instantiate the ModuliConfig
            class with a specified base directory. It ensures that the provided base
            directory is explicitly set during the object creation.

    Args:
        base_dir (str): The base directory to be used for initialization.

    Returns:
        ModuliConfig: A new instance of the ModuliConfig class initialized with the given
                     base directory.
    """
    return ModuliConfig(base_dir)

iso_utc_timestamp

iso_utc_timestamp(compress=False)

Generates a UTC timestamp in ISO 8601 format. Optionally, the output can be compressed to remove non-numeric characters.

Parameters:

Name Type Description Default
compress bool

Specifies whether the timestamp should be compressed by removing non-numeric characters.

False

Returns:

Name Type Description
str str

The generated UTC timestamp as a string. If compress is True, the timestamp will only contain numeric characters.

Source code in config/__init__.py
def iso_utc_timestamp(compress: bool = False) -> str:
    """
    Generates a UTC timestamp in ISO 8601 format. Optionally, the output can be compressed
        to remove non-numeric characters.

    Args:
        compress (bool): Specifies whether the timestamp should be compressed by removing
                 non-numeric characters.

    Returns:
        str: The generated UTC timestamp as a string. If `compress` is True, the
                 timestamp will only contain numeric characters.
    """

    timestamp = iso_utc_time_notzinfo().isoformat()
    if compress:
        return re.sub(r"[^0-9]", "", timestamp)
    else:
        return timestamp

iso_utc_time_notzinfo

iso_utc_time_notzinfo()

Generates and returns the current time in UTC format, stripped of timezone information. This function uses the UTC timezone to fetch the current time but removes the timezone information from the resulting datetime object.

Returns:

Name Type Description
datetime datetime

The current UTC time as a timezone-naive datetime object.

Source code in config/__init__.py
def iso_utc_time_notzinfo() -> datetime:
    """
    Generates and returns the current time in UTC format, stripped of timezone
        information. This function uses the UTC timezone to fetch the current time
        but removes the timezone information from the resulting datetime object.

    Returns:
        datetime: The current UTC time as a timezone-naive datetime object.
    """
    return datetime.now(UTC).replace(tzinfo=None)

strip_punction_from_datetime_str

strip_punction_from_datetime_str(timestamp)

Compresses a datetime object into a compact string format by removing non-numeric characters from its ISO 8601 format string.

Parameters:

Name Type Description Default
timestamp Datetime

A datetime object to compress into a string.

required

Returns:

Name Type Description
str str

A string representation of the given datetime with all non-numeric characters removed.

Source code in config/__init__.py
def strip_punction_from_datetime_str(timestamp: datetime) -> str:
    """
    Compresses a datetime object into a compact string format by removing non-numeric
        characters from its ISO 8601 format string.

    Args:
        timestamp (Datetime): A datetime object to compress into a string.

    Returns:
        str: A string representation of the given datetime with all non-numeric characters removed.
    """
    return re.sub(r"[^0-9]", "", timestamp.isoformat())

default_config

default_config()

Generates and ensures the default configuration directories and structure.

Returns:

Name Type Description
ModuliConfig ModuliConfig

An instance of ModuliConfig with directories ensured.

Source code in config/__init__.py
def default_config() -> 'ModuliConfig':
    """
    Generates and ensures the default configuration directories and structure.

    Returns:
        ModuliConfig: An instance of ModuliConfig with directories ensured.
    """
    return ModuliConfig().ensure_directories()

options: members: true