Skip to content

Config module

FileLogHandler pydantic-model

Configuration for a file log handler

enabled: bool pydantic-field

If the log handler should be enabled or not

format: LogFormat pydantic-field

The log format to use when logging to the console

path: Path pydantic-field

The file path to log to, must be set if the handler is enabled.

validate_log_path(path) classmethod

Validate that the given path is a file if it exists

Source code in simulation/config.py
@validator("path")
def validate_log_path(cls, path: Path) -> Path:
    """Validate that the given path is a file if it exists"""
    if path.exists() and not path.is_file():
        raise ValueError(f"Log file path {path.absolute()} is not a file!")
    return path

LogFormat

Enum for log formatter styles

COLORED

The same as PLAIN, but colorized

JSON

The log events in JSON format

PLAIN

Human readable structured text format

LoggingConfig pydantic-model

Configuration options for the logging system.

console: LogHandler pydantic-field

Configuration for the console logger

file: FileLogHandler pydantic-field

Configuration for the file logger

level: LogLevel pydantic-field

The log level to use for logging

timestamp: LogTimestamp pydantic-field

Configuration options for modifying the log timestamps

LogHandler pydantic-model

Configuration for a log handler

enabled: bool pydantic-field

If the log handler should be enabled or not

format: LogFormat pydantic-field

The log format to use when logging to the console

LogTimestamp pydantic-model

Configuration for the log timestamp format and key

format: str pydantic-field

The strftime string format to use for formating timestamps (e.g., %Y-%m-%d %H:%M:%S). If this is None a UNIX timestamp is used.

key: str pydantic-field

The key to use for the timestamp.

utc: bool pydantic-field

If the timestamp should be in UTC or the local timezone.

PluginConfig pydantic-model

Configuration options for the state machine factory plugin system.

exclude_names: Pattern pydantic-field

A list of regular expressions used to define which plugins to explicitly exclude.

include_names: Pattern pydantic-field

A list of regular expressions used to define which plugins to include.

Settings pydantic-model

Cyber Range Kyoushi Simulation settings

log: LoggingConfig pydantic-field

The logging configuration

plugin: PluginConfig pydantic-field

The plugin system configuration

seed: int pydantic-field

The seed to use for random generators

configure_seed(seed=None)

Configure a seed for PRNG, if no seed is passed then one is generated.

Parameters:

Name Type Description Default
seed Optional[int]

The seed to use for PRNG

None
Source code in simulation/config.py
def configure_seed(seed: Optional[int] = None):
    """Configure a seed for PRNG, if no seed is passed then one is generated.

    Args:
        seed: The seed to use for PRNG
    """
    if seed is None:
        # legacy global numpy requires seeds to be in
        # [0, 2**32-1]
        seed = random.randint(0, 2 ** 32 - 1)
    global _SEED
    _SEED = seed
    random.seed(seed)
    np.random.seed(seed)

get_seed()

Get the global random seed value for the simulation library

Returns:

Type Description
int

The seed value

Source code in simulation/config.py
def get_seed() -> int:
    """Get the global random seed value for the simulation library

    Returns:
        The seed value
    """
    # configure seed if not already done
    global _SEED
    if _SEED is None:
        configure_seed()

    # return seed value
    return _SEED

load_config_file(config_path)

Loads a given a config from the given path and returns a raw dictionary.

Supported file formats are: - YAML

Parameters:

Name Type Description Default
config_path Path

The file path to read the config from

required

Returns:

Type Description
Dict[Any, Any]

The contents of the configuration file converted to a dictionary or {} if the file is empty or does not exist.

Source code in simulation/config.py
def load_config_file(config_path: Path) -> Dict[Any, Any]:
    """Loads a given a config from the given path and returns a raw dictionary.

    Supported file formats are:
        - YAML

    Args:
        config_path: The file path to read the config from

    Returns:
        The contents of the configuration file converted to a dictionary or `{}`
        if the file is empty or does not exist.
    """
    yaml = YAML(typ="safe")
    if config_path.exists():
        return yaml.load(config_path)
    return {}

load_settings(settings_path, log_level=None, seed=None)

Loads the Cyber Range Kyoushi Simulation CLI settings

Parameters:

Name Type Description Default
settings_path Path

The path to load the settings file from

required
log_level Optional[cr_kyoushi.simulation.model.LogLevel]

The CLI log_level override. This supercedes the config and environment variable values..

None

Exceptions:

Type Description
ConfigValidationError

If the config validation fails

Returns:

Type Description
Settings

The validated settings object

Source code in simulation/config.py
def load_settings(
    settings_path: Path,
    log_level: Optional[LogLevel] = None,
    seed: Optional[int] = None,
) -> Settings:
    """Loads the Cyber Range Kyoushi Simulation CLI settings

    Args:
        settings_path: The path to load the settings file from
        log_level: The CLI log_level override. This supercedes the config
                   and environment variable values..

    Raises:
        ConfigValidationError: If the config validation fails

    Returns:
        The validated settings object
    """
    try:
        settings_raw = load_config_file(settings_path)

        if log_level is not None:
            settings_raw.setdefault("log", {})["level"] = log_level

        if seed is not None:
            settings_raw["seed"] = seed

        settings = Settings(
            _env_file=str(object),
            _env_file_encoding=None,
            _secrets_dir=None,
            **settings_raw,
        )

        return settings
    except ValidationError as val_err:
        raise ConfigValidationError(val_err)

load_sm_config(config_path, sm_config_type)

Loads and validates the state machine configuration

Parameters:

Name Type Description Default
config_path Path

The path to load the configuration from

required
sm_config_type Type[~StatemachineConfig]

The state machine config class to convert to

required

Exceptions:

Type Description
ConfigValidationError

If the config validation fails

Returns:

Type Description
~StatemachineConfig

The state machine configuration validated and converted to the given config class.

Source code in simulation/config.py
def load_sm_config(
    config_path: Path,
    sm_config_type: Type[StatemachineConfig],
) -> StatemachineConfig:
    """Loads and validates the state machine configuration

    Args:
        config_path: The path to load the configuration from
        sm_config_type: The state machine config class to convert to

    Raises:
        ConfigValidationError: If the config validation fails

    Returns:
        The state machine configuration validated and converted
        to the given config class.
    """
    try:
        config_raw = load_config_file(config_path)
        if issubclass(sm_config_type, BaseModel):
            return sm_config_type.parse_obj(config_raw)
        else:
            return config_raw

    except ValidationError as val_err:
        raise ConfigValidationError(val_err)