config
frequenz.sdk.config ¤
Read and update config variables.
Classes¤
frequenz.sdk.config.ConfigManagingActor ¤
Bases: Actor
An actor that monitors a TOML configuration files for updates.
When the actor is started the configuration files will be read and sent to the output sender. Then the actor will start monitoring the files for updates. If any file is updated, all the configuration files will be re-read and sent to the output sender.
If no configuration file could be read, the actor will raise an exception.
The configuration files are read in the order of the paths, so the last path will override the configuration set by the previous paths. Dict keys will be merged recursively, but other objects (like lists) will be replaced by the value in the last path.
Example
If config1.toml
contains:
And config2.toml
contains:
Then the final configuration will be:
Source code in frequenz/sdk/config/_config_managing.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
|
Attributes¤
RESTART_DELAY
class-attribute
instance-attribute
¤
The delay to wait between restarts of this actor.
is_running
property
¤
is_running: bool
Return whether this background service is running.
A service is considered running when at least one task is running.
RETURNS | DESCRIPTION |
---|---|
bool
|
Whether this background service is running. |
name
property
¤
name: str
The name of this background service.
RETURNS | DESCRIPTION |
---|---|
str
|
The name of this background service. |
tasks
property
¤
Return the set of running tasks spawned by this background service.
Users typically should not modify the tasks in the returned set and only use them for informational purposes.
Danger
Changing the returned tasks may lead to unexpected behavior, don't do it unless the class explicitly documents it is safe to do so.
RETURNS | DESCRIPTION |
---|---|
Set[Task[Any]]
|
The set of running tasks spawned by this background service. |
Functions¤
__aenter__
async
¤
__aenter__() -> Self
Enter an async context.
Start this background service.
RETURNS | DESCRIPTION |
---|---|
Self
|
This background service. |
__aexit__
async
¤
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exit an async context.
Stop this background service.
PARAMETER | DESCRIPTION |
---|---|
exc_type
|
The type of the exception raised, if any.
TYPE:
|
exc_val
|
The exception raised, if any.
TYPE:
|
exc_tb
|
The traceback of the exception raised, if any.
TYPE:
|
Source code in frequenz/sdk/actor/_background_service.py
__await__ ¤
__await__() -> Generator[None, None, None]
Await this background service.
An awaited background service will wait for all its tasks to finish.
RETURNS | DESCRIPTION |
---|---|
None
|
An implementation-specific generator for the awaitable. |
Source code in frequenz/sdk/actor/_background_service.py
__del__ ¤
Destroy this instance.
Cancel all running tasks spawned by this background service.
__init__ ¤
__init__(
config_paths: Sequence[Path | str],
output: Sender[Mapping[str, Any]],
event_types: Set[EventType] = frozenset(EventType),
*,
name: str | None = None,
force_polling: bool = True,
polling_interval: timedelta = timedelta(seconds=1)
) -> None
Initialize this instance.
PARAMETER | DESCRIPTION |
---|---|
config_paths
|
The paths to the TOML files with the configuration. Order matters, as the configuration will be read and updated in the order of the paths, so the last path will override the configuration set by the previous paths. Dict keys will be merged recursively, but other objects (like lists) will be replaced by the value in the last path. |
output
|
The sender to send the configuration to. |
event_types
|
The set of event types to monitor. |
name
|
The name of the actor. If
TYPE:
|
force_polling
|
Whether to force file polling to check for changes.
TYPE:
|
polling_interval
|
The interval to poll for changes. Only relevant if polling is enabled. |
Source code in frequenz/sdk/config/_config_managing.py
__repr__ ¤
__repr__() -> str
Return a string representation of this instance.
RETURNS | DESCRIPTION |
---|---|
str
|
A string representation of this instance. |
__str__ ¤
__str__() -> str
Return a string representation of this instance.
RETURNS | DESCRIPTION |
---|---|
str
|
A string representation of this instance. |
cancel ¤
cancel(msg: str | None = None) -> None
Cancel all running tasks spawned by this background service.
PARAMETER | DESCRIPTION |
---|---|
msg
|
The message to be passed to the tasks being cancelled.
TYPE:
|
Source code in frequenz/sdk/actor/_background_service.py
send_config
async
¤
start ¤
Start this actor.
If this actor is already running, this method does nothing.
stop
async
¤
stop(msg: str | None = None) -> None
Stop this background service.
This method cancels all running tasks spawned by this service and waits for them to finish.
PARAMETER | DESCRIPTION |
---|---|
msg
|
The message to be passed to the tasks being cancelled.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
BaseExceptionGroup
|
If any of the tasks spawned by this service raised an exception. |
Source code in frequenz/sdk/actor/_background_service.py
wait
async
¤
Wait this background service to finish.
Wait until all background service tasks are finished.
RAISES | DESCRIPTION |
---|---|
BaseExceptionGroup
|
If any of the tasks spawned by this service raised an
exception ( |
Source code in frequenz/sdk/actor/_background_service.py
frequenz.sdk.config.LoggerConfig ¤
A configuration for a logger.
Source code in frequenz/sdk/config/_logging_config_updater.py
frequenz.sdk.config.LoggingConfig ¤
A configuration for the logging system.
Source code in frequenz/sdk/config/_logging_config_updater.py
Attributes¤
loggers
class-attribute
instance-attribute
¤
loggers: dict[str, LoggerConfig] = field(
default_factory=dict,
metadata={
"metadata": {
"description": "Configuration for a logger (the key is the logger name)."
},
"required": False,
},
)
The list of loggers configurations.
root_logger
class-attribute
instance-attribute
¤
root_logger: LoggerConfig = field(
default_factory=LoggerConfig,
metadata={
"metadata": {
"description": "Default default configuration for all loggers."
},
"required": False,
},
)
The default log level.
Functions¤
load
classmethod
¤
Load and validate configs from a dictionary.
PARAMETER | DESCRIPTION |
---|---|
configs
|
The configuration to validate. |
RETURNS | DESCRIPTION |
---|---|
Self
|
The configuration if they are valid. |
RAISES | DESCRIPTION |
---|---|
ValidationError
|
if the configuration are invalid. |
Source code in frequenz/sdk/config/_logging_config_updater.py
frequenz.sdk.config.LoggingConfigUpdater ¤
Bases: Actor
Actor that listens for logging configuration changes and sets them.
Example
config.toml
file:
[logging.root_logger]
level = "INFO"
[logging.loggers."frequenz.sdk.actor.power_distributing"]
level = "DEBUG"
[logging.loggers."frequenz.channels"]
level = "DEBUG"
import asyncio
from collections.abc import Mapping
from typing import Any
from frequenz.channels import Broadcast
from frequenz.sdk.config import LoggingConfigUpdater, ConfigManager
from frequenz.sdk.actor import run as run_actors
async def run() -> None:
config_channel = Broadcast[Mapping[str, Any]](name="config", resend_latest=True)
actors = [
ConfigManager(config_paths=["config.toml"], output=config_channel.new_sender()),
LoggingConfigUpdater(
config_recv=config_channel.new_receiver(limit=1)).map(
lambda app_config: app_config.get("logging", {}
)
),
]
await run_actors(*actors)
asyncio.run(run())
Now whenever the config.toml
file is updated, the logging configuration
will be updated as well.
Source code in frequenz/sdk/config/_logging_config_updater.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
|
Attributes¤
RESTART_DELAY
class-attribute
instance-attribute
¤
The delay to wait between restarts of this actor.
is_running
property
¤
is_running: bool
Return whether this background service is running.
A service is considered running when at least one task is running.
RETURNS | DESCRIPTION |
---|---|
bool
|
Whether this background service is running. |
name
property
¤
name: str
The name of this background service.
RETURNS | DESCRIPTION |
---|---|
str
|
The name of this background service. |
tasks
property
¤
Return the set of running tasks spawned by this background service.
Users typically should not modify the tasks in the returned set and only use them for informational purposes.
Danger
Changing the returned tasks may lead to unexpected behavior, don't do it unless the class explicitly documents it is safe to do so.
RETURNS | DESCRIPTION |
---|---|
Set[Task[Any]]
|
The set of running tasks spawned by this background service. |
Functions¤
__aenter__
async
¤
__aenter__() -> Self
Enter an async context.
Start this background service.
RETURNS | DESCRIPTION |
---|---|
Self
|
This background service. |
__aexit__
async
¤
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exit an async context.
Stop this background service.
PARAMETER | DESCRIPTION |
---|---|
exc_type
|
The type of the exception raised, if any.
TYPE:
|
exc_val
|
The exception raised, if any.
TYPE:
|
exc_tb
|
The traceback of the exception raised, if any.
TYPE:
|
Source code in frequenz/sdk/actor/_background_service.py
__await__ ¤
__await__() -> Generator[None, None, None]
Await this background service.
An awaited background service will wait for all its tasks to finish.
RETURNS | DESCRIPTION |
---|---|
None
|
An implementation-specific generator for the awaitable. |
Source code in frequenz/sdk/actor/_background_service.py
__del__ ¤
Destroy this instance.
Cancel all running tasks spawned by this background service.
__init__ ¤
__init__(
config_recv: Receiver[Mapping[str, Any]],
log_format: str = "%(asctime)s %(levelname)-8s %(name)s:%(lineno)s: %(message)s",
log_datefmt: str = "%Y-%m-%dT%H:%M:%S%z",
)
Initialize this instance.
PARAMETER | DESCRIPTION |
---|---|
config_recv
|
The receiver to listen for configuration changes. |
log_format
|
Use the specified format string in logs.
TYPE:
|
log_datefmt
|
Use the specified date/time format in logs.
TYPE:
|
Note
The log_format
and log_datefmt
parameters are used in a call to
logging.basicConfig()
. If logging has already been configured elsewhere
in the application (through a previous basicConfig()
call), then the format
settings specified here will be ignored.
Source code in frequenz/sdk/config/_logging_config_updater.py
__repr__ ¤
__repr__() -> str
Return a string representation of this instance.
RETURNS | DESCRIPTION |
---|---|
str
|
A string representation of this instance. |
__str__ ¤
__str__() -> str
Return a string representation of this instance.
RETURNS | DESCRIPTION |
---|---|
str
|
A string representation of this instance. |
cancel ¤
cancel(msg: str | None = None) -> None
Cancel all running tasks spawned by this background service.
PARAMETER | DESCRIPTION |
---|---|
msg
|
The message to be passed to the tasks being cancelled.
TYPE:
|
Source code in frequenz/sdk/actor/_background_service.py
start ¤
Start this actor.
If this actor is already running, this method does nothing.
stop
async
¤
stop(msg: str | None = None) -> None
Stop this background service.
This method cancels all running tasks spawned by this service and waits for them to finish.
PARAMETER | DESCRIPTION |
---|---|
msg
|
The message to be passed to the tasks being cancelled.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
BaseExceptionGroup
|
If any of the tasks spawned by this service raised an exception. |
Source code in frequenz/sdk/actor/_background_service.py
wait
async
¤
Wait this background service to finish.
Wait until all background service tasks are finished.
RAISES | DESCRIPTION |
---|---|
BaseExceptionGroup
|
If any of the tasks spawned by this service raised an
exception ( |
Source code in frequenz/sdk/actor/_background_service.py
Functions¤
frequenz.sdk.config.load_config ¤
load_config(
cls: type[DataclassT],
config: Mapping[str, Any],
/,
base_schema: type[Schema] | None = None,
**marshmallow_load_kwargs: Any,
) -> DataclassT
Load a configuration from a dictionary into an instance of a configuration class.
The configuration class is expected to be a dataclasses.dataclass
, which is
used to create a marshmallow.Schema
schema to validate the configuration
dictionary using marshmallow_dataclass.class_schema
(which in turn uses the
marshmallow.Schema.load
method to do the validation and deserialization).
To customize the schema derived from the configuration dataclass, you can use the
metadata
key in dataclasses.field
to pass extra options to
marshmallow_dataclass
to be used during validation and deserialization.
Additional arguments can be passed to marshmallow.Schema.load
using keyword
arguments marshmallow_load_kwargs
.
Note
This method will raise marshmallow.ValidationError
if the configuration
dictionary is invalid and you have to have in mind all of the gotchas of
marshmallow
and marshmallow_dataclass
applies when using this
function. It is recommended to carefully read the documentation of these
libraries.
PARAMETER | DESCRIPTION |
---|---|
cls
|
The configuration class.
TYPE:
|
config
|
The configuration dictionary. |
base_schema
|
An optional class to be used as a base schema for the configuration
class. This allow using custom fields for example. Will be passed to
|
**marshmallow_load_kwargs
|
Additional arguments to be passed to
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DataclassT
|
The loaded configuration as an instance of the configuration class. |