watchpost
Modules:
-
app–Watchpost application and Starlette integration.
-
cache–Caching utilities and pluggable storage backends.
-
check–Check definitions, execution helpers, and caching.
-
cli– -
datasource–Datasource primitives and factory helpers.
-
discover_checks–Utilities for discovering checks defined in modules and packages.
-
environment–Execution environments and registry.
-
executor–Threaded check executor for Watchpost.
-
globals–Global state for Watchpost and a proxy to the active application instance.
-
hostname–Hostname resolution utilities and strategies.
-
http–Starlette HTTP routes for Watchpost.
-
result–Result types and builders for Watchpost checks.
-
scheduling_strategy–Scheduling strategies and validation.
-
utils–Utility helpers for Watchpost.
-
vendored–
Classes:
-
Cache–High-level caching API using a pluggable storage backend.
-
ChainedStorage–A storage implementation that chains multiple storage backends together.
-
CheckResult–Represents the result of a check performed on a system or component.
-
Datasource–Base class for datasources that provide input to checks.
-
DatasourceFactory–Protocol for factories that construct datasources for checks.
-
DatasourceUnavailable–Raised when a datasource cannot be created, accessed, or used.
-
DiskStorage–A disk-backed storage backend using Pickle-serialized
CacheEntryobjects. -
Environment–Represents a logical environment in which checks run.
-
EnvironmentRegistry–Simple in-memory registry of
Environmentobjects. -
FromFactory–Marker used with
typing.Annotatedto request a datasource from a factory. -
InMemoryStorage–A simple in-memory storage backend.
-
Metric–Represents a measurable metric with an optional threshold configuration.
-
MustRunAgainstGivenTargetEnvironmentStrategy–Restrict which target environments the check may run against.
-
MustRunInGivenExecutionEnvironmentStrategy–Require that the check executes from one of the given execution
-
MustRunInTargetEnvironmentStrategy–Require that the current execution environment equals the target
-
RedisStorage–A Redis-backed storage backend.
-
Thresholds–Represents threshold values with warning and critical levels.
-
Watchpost–Main Watchpost application and ASGI app.
Functions:
-
build_result–Start building up a new check result that allows adding multiple
-
crit–Generates a CheckResult object indicating a CRIT check state.
-
ok–Generates a CheckResult object indicating an OK check state.
-
unknown–Generates a CheckResult object indicating an UNKNOWN check state.
-
warn–Generates a CheckResult object indicating a WARN check state.
Cache
Cache(storage: Storage)
High-level caching API using a pluggable storage backend.
Use get and store to interact with the cache directly, or the memoize
decorator to cache function results.
Methods:
-
get–Retrieve a value from the cache.
-
memoize–Memoize a function by caching its return value.
-
store–Store a value in the cache.
get
get(
key: Hashable,
default: T | None = None,
*,
package: str | None = None,
return_expired: bool = False,
) -> CacheEntry[T] | None
Retrieve a value from the cache.
Parameters:
-
(keyHashable) –The key to look up. Must be hashable and unique within the given package.
-
(defaultT | None, default:None) –An optional default value to return when the key is not found.
-
(packagestr | None, default:None) –The package namespace. If not provided, the package of the caller is used.
-
(return_expiredbool, default:False) –Whether to return an expired entry once before it is removed. (This behavior does depend on the storage backend supporting this.)
Returns:
-
CacheEntry[T] | None–The cache entry if found. If not found, returns
Nonewhen no -
CacheEntry[T] | None–default is given, otherwise a cache entry wrapping the default
-
CacheEntry[T] | None–value.
memoize
memoize(
*,
key: Hashable | None = None,
key_generator: Callable[P, Hashable] | None = None,
package: str | None = None,
return_expired: bool = False,
ttl: timedelta | None = None,
) -> Callable[[Callable[P, R]], Callable[P, R]]
Memoize a function by caching its return value.
Use either a fixed key or a key_generator to compute the cache key
from call arguments. If key contains format placeholders like "{arg}",
they will be formatted from the function's bound arguments.
Parameters:
-
(keyHashable | None, default:None) –A static key or a format string used to build the key. Mutually exclusive with
key_generator. -
(key_generatorCallable[P, Hashable] | None, default:None) –A callable that receives the function's arguments and returns a hashable key. Mutually exclusive with
key. -
(packagestr | None, default:None) –The package namespace. If not provided, the package of the caller is used.
-
(return_expiredbool, default:False) –Whether to return an expired entry once before it is recomputed and overwritten.
-
(ttltimedelta | None, default:None) –Optional time-to-live for stored values.
Returns:
-
Callable[[Callable[P, R]], Callable[P, R]]–A decorator that wraps the function and provides cached results.
Notes
- Only one of
keyorkey_generatormust be provided. - If
return_expiredis True, an expired value may be returned once; it is then replaced with a fresh value.
store
store(
key: Hashable,
value: T,
*,
package: str | None = None,
ttl: timedelta | None = None,
) -> CacheEntry[T]
Store a value in the cache.
Parameters:
-
(keyHashable) –The key under which to store the value. Must be hashable and unique within the given package.
-
(valueT) –The value to store.
-
(packagestr | None, default:None) –The package namespace. If not provided, the package of the caller is used.
-
(ttltimedelta | None, default:None) –Optional time-to-live for the entry. When omitted, the entry does not expire.
Returns:
-
CacheEntry[T]–The cache entry that was stored.
ChainedStorage
Bases: Storage
A storage implementation that chains multiple storage backends together.
On retrieval, it tries each storage in order until it finds a hit. On storage, it stores the value in all storage backends.
Parameters:
-
(storageslist[Storage]) –Storage backends to chain. The order defines lookup priority; the first backend with a hit will be used.
CheckResult
dataclass
CheckResult(
check_state: CheckState,
summary: str,
details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
hostname: HostnameInput | None = None,
)
Represents the result of a check performed on a system or component.
This class encapsulates the result of a check operation, providing details such as the state of the check, a summary, optional details, a name suffix, metrics, and hostname information. It is designed to store and convey the outcome of a check operation in a structured format.
Attributes:
-
check_state(CheckState) –The state of the check, indicating whether it was successful, warning,
-
details(str | None) –A detailed output of the check result, providing additional information
-
hostname(HostnameInput | None) –An optional hostname that overrides the hostname that would have been used
-
metrics(list[Metric] | None) –An optional list of metrics to associate with the check.
-
name_suffix(str | None) –A suffix to add to the check name as defined in the
@checkdecorator. -
summary(str) –A summary of the check result, indicating the outcome of the check.
check_state
instance-attribute
check_state: CheckState = check_state
The state of the check, indicating whether it was successful, warning, critical, or unknown.
details
class-attribute
instance-attribute
details: str | None = normalize_details(details)
A detailed output of the check result, providing additional information beyond the summary.
Checkmk will show this detailed output when you are viewing a specific service.
hostname
class-attribute
instance-attribute
An optional hostname that overrides the hostname that would have been used otherwise.
metrics
class-attribute
instance-attribute
metrics: list[Metric] | None = metrics
An optional list of metrics to associate with the check.
name_suffix
class-attribute
instance-attribute
A suffix to add to the check name as defined in the @check decorator.
This enables a single check function to return multiple results that create multiple services on the Checkmk side.
Datasource
Bases: ABC
Base class for datasources that provide input to checks.
Subclass this to integrate systems your checks read from (APIs, files, services, etc.). Datasources can influence where and when checks are run by exposing scheduling strategies.
Attributes:
-
scheduling_strategies(tuple[SchedulingStrategy, ...] | EllipsisType | None) –Optional scheduling strategies that constrain where a check may run.
scheduling_strategies
class-attribute
instance-attribute
scheduling_strategies: (
tuple[SchedulingStrategy, ...] | EllipsisType | None
) = ...
Optional scheduling strategies that constrain where a check may run.
- Ellipsis (...) means "unspecified". If a datasource created by a factory
leaves this as Ellipsis, Watchpost will fall back to the factory's
own
scheduling_strategiesif any. - A tuple provides explicit strategies for this datasource and takes precedence over any factory strategies.
- None or an empty tuple means "no constraints".
DatasourceFactory
Bases: Protocol
Protocol for factories that construct datasources for checks.
A factory centralizes configuration and creation logic for a datasource.
Watchpost can use factory-level scheduling_strategies when the created
datasource does not define its own.
Attributes:
-
new(Callable[..., Datasource]) –Function that creates and returns a datasource instance.
-
scheduling_strategies(tuple[SchedulingStrategy, ...] | EllipsisType | None) –Optional scheduling strategies applied to datasources created by this
new
class-attribute
new: Callable[..., Datasource]
Function that creates and returns a datasource instance.
Watchpost forwards the positional and keyword arguments declared
via FromFactory(..., *args, **kwargs) to this callable.
scheduling_strategies
class-attribute
instance-attribute
scheduling_strategies: (
tuple[SchedulingStrategy, ...] | EllipsisType | None
) = ...
Optional scheduling strategies applied to datasources created by this factory.
A tuple sets explicit constraints; None or an empty tuple means "no constraints".
DatasourceUnavailable
Bases: Exception
Raised when a datasource cannot be created, accessed, or used.
Watchpost raises this error when a check requests data, but the underlying system is not reachable, misconfigured, or otherwise unavailable.
DiskStorage
DiskStorage(directory: str)
Bases: Storage
A disk-backed storage backend using Pickle-serialized CacheEntry objects.
Entries are stored under a versioned directory and sharded by a hash prefix.
Parameters:
-
(directorystr) –Directory root where cache files are written.
Environment
Represents a logical environment in which checks run.
An environment typically maps to how or where checks are executed (for example: dev, stage, prod, monitoring). It can carry a hostname resolution strategy and arbitrary metadata that checks and data sources may use to alter behavior.
Parameters:
-
(namestr) –The name of the environment (e.g., "dev", "stage", "prod", "monitoring").
-
(hostnameHostnameInput | None, default:None) –Input used to determine the hostname when running checks in this environment. Accepts the same forms as
HostnameInputsuch as a template string, a callable, or a strategy instance. If omitted, the application may fall back to its default hostname generation. -
(metadataHashable, default:{}) –Arbitrary, hashable metadata attached to the environment. Checks and data sources may consult these values to change behavior.
Notes
Hostname handling integrates with the hostname resolution system in
watchpost.hostname. The chosen strategy ultimately influences the
Checkmk host a service is associated with.
EnvironmentRegistry
Simple in-memory registry of Environment objects.
The registry provides dictionary-like access and helpers to create and manage environments used by a Watchpost application.
Methods:
-
add–Add or replace an environment by its name.
-
get–Return the environment for the given name, or a default if missing.
-
new–Create a new environment, add it to the registry, and return it.
add
add(environment: Environment) -> None
Add or replace an environment by its name.
Parameters:
-
(environmentEnvironment) –The environment to register. If another environment with the same name exists, it will be overwritten.
get
get(
name: str, default: Environment | None = None
) -> Environment | None
Return the environment for the given name, or a default if missing.
Parameters:
-
(namestr) –The environment name to look up.
-
(defaultEnvironment | None, default:None) –Value to return when the name is not present.
Returns:
-
Environment | None–The matching
Environment, or the provided default.
new
new(
name: str,
*,
hostname: HostnameInput | None = None,
**metadata: Hashable,
) -> Environment
Create a new environment, add it to the registry, and return it.
Parameters:
-
(namestr) –The name of the environment to create.
-
(hostnameHostnameInput | None, default:None) –Input used to determine the hostname for this environment. See
Environment.__init__for supported forms. -
(metadataHashable, default:{}) –Arbitrary, hashable metadata to attach to the environment.
Returns:
-
Environment–The created and registered
Environmentinstance.
FromFactory
FromFactory(
factory: type[DatasourceFactory],
*args: Any,
**kwargs: Any,
)
FromFactory(
factory: type[DatasourceFactory] | Any = None,
*args: Any,
**kwargs: Any,
)
Marker used with typing.Annotated to request a datasource from a factory.
Use in a check parameter annotation as:
Annotated[MyDatasource, FromFactory(MyFactory, "service")]
You may omit the factory type when the parameter type implements the factory protocol:
Annotated[MyDatasourceWithFactory, FromFactory("service")]
Parameters are forwarded to the factory's new callable. Watchpost caches
the constructed datasource per factory type and argument set.
Parameters:
-
(factorytype[DatasourceFactory] | Any, default:None) –Optional factory type used to create the datasource. If omitted, Watchpost infers the factory from the annotated parameter's type. If the first positional argument is not a type, it is treated as a factory argument and the factory is inferred.
-
(argsAny, default:()) –Positional arguments forwarded to the factory
newcallable. -
(kwargsAny, default:{}) –Keyword arguments forwarded to the factory
newcallable.
Methods:
-
cache_key–Generate a stable cache key for this factory invocation.
cache_key
cache_key(
type_key: type[DatasourceFactory] | None,
) -> tuple[type[DatasourceFactory] | None, int, int]
Generate a stable cache key for this factory invocation.
Parameters:
-
(type_keytype[DatasourceFactory] | None) –Fallback factory type to use when this instance did not specify a factory explicitly (i.e., it will be inferred from the annotated parameter type).
Returns:
-
type[DatasourceFactory] | None–A tuple that identifies the factory type and the provided arguments,
-
int–suitable for use as a cache key.
InMemoryStorage
Bases: Storage
A simple in-memory storage backend.
Useful for tests or ephemeral caching within a single process. Entries are lost when the process exits.
Metric
dataclass
Metric(
name: str,
value: int | float,
levels: Thresholds | None = None,
boundaries: Thresholds | None = None,
)
Represents a measurable metric with an optional threshold configuration.
This maps to the Checkmk concept of metrics exactly.
MustRunAgainstGivenTargetEnvironmentStrategy
MustRunAgainstGivenTargetEnvironmentStrategy(
*environments: Environment,
)
Bases: SchedulingStrategy
Restrict which target environments the check may run against.
Use this to allow only specific targets (for example, only "stage"). If the requested target is not in the allowed set, the decision is DONT_SCHEDULE.
This strategy does not affect from where the check executes, i.e. the execution environment.
One or more target environments that the check may run against.
MustRunInGivenExecutionEnvironmentStrategy
MustRunInGivenExecutionEnvironmentStrategy(
*environments: Environment,
)
Bases: SchedulingStrategy
Require that the check executes from one of the given execution environments.
Use this when a datasource or check can only run from specific locations (for example, from a monitoring environment). If the current execution environment is not in the allowed set, the decision is DONT_SCHEDULE.
One or more execution environments from which the check may run.
MustRunInTargetEnvironmentStrategy
Bases: SchedulingStrategy
Require that the current execution environment equals the target environment.
This models "run in-environment" behavior where the check must execute inside the environment it is checking. If current != target, the decision is DONT_SCHEDULE.
RedisStorage
RedisStorage(
redis_client: Redis,
*,
use_redis_ttl: bool = True,
redis_key_infix: str | None = None,
)
Bases: Storage
A Redis-backed storage backend.
When use_redis_ttl is True, Redis key expiration is used so expired
entries are never returned by get.
Parameters:
-
(redis_clientRedis) –The Redis client instance.
-
(use_redis_ttlbool, default:True) –Whether to use Redis TTL for automatic expiry. When
True, expired entries are not returned. -
(redis_key_infixstr | None, default:None) –Optional infix to namespace keys to avoid collisions between multiple caches or watchposts.
Methods:
get
get(
cache_key: CacheKey, return_expired: bool = False
) -> CacheEntry[T] | None
Retrieve a cache entry from Redis.
Parameters:
-
(cache_keyCacheKey) –The key to retrieve the value for.
-
(return_expiredbool, default:False) –Whether to return an expired entry once before it is removed. (If Redis's TTL is used, an expired entry is never returned and this has no effect.)
Returns:
-
CacheEntry[T] | None–The cache entry if found, otherwise
None.
store
store(entry: CacheEntry) -> None
Thresholds
dataclass
Represents threshold values with warning and critical levels.
This maps to the Checkmk concept of thresholds exactly and thus directly
relates to metrics, see the Metric class.
Watchpost
Watchpost(
*,
checks: list[Check | ModuleType],
execution_environment: Environment,
version: str = "unknown",
max_workers: int | None = None,
executor: CheckExecutor[list[ExecutionResult]]
| None = None,
check_cache_storage: Storage | None = None,
default_scheduling_strategies: list[SchedulingStrategy]
| None = None,
hostname: HostnameInput | None = None,
hostname_fallback_to_default_hostname_generation: bool = True,
hostname_coerce_into_valid_hostname: bool = True,
)
Main Watchpost application and ASGI app.
Watchpost discovers and runs checks across environments, coordinates
datasources, applies scheduling strategies, and generates Checkmk-compatible
output. A Watchpost instance is also an ASGI application backed by
Starlette and exposes operational endpoints.
Notes
The instance manages a per-check result cache and a key-aware executor to run checks without blocking. It also verifies check configuration and hostname generation at application startup.
Parameters:
-
(checkslist[Check | ModuleType]) –A list of
Checkobjects or Python modules to scan for checks. Modules are discovered recursively. -
(execution_environmentEnvironment) –The environment in which this Watchpost instance runs checks.
-
(versionstr, default:'unknown') –Version string included in the Checkmk agent header output.
-
(max_workersint | None, default:None) –Maximum number of worker threads for the internal executor. Used when no custom
executoris provided. -
(executorCheckExecutor[list[ExecutionResult]] | None, default:None) –Optional custom
CheckExecutorto use instead of the default. -
(check_cache_storageStorage | None, default:None) –Optional storage backend for the per-check result cache. Defaults to in-memory storage.
-
(default_scheduling_strategieslist[SchedulingStrategy] | None, default:None) –Default strategies applied to all checks in addition to those specified by checks and datasources. If not provided, the
DetectImpossibleCombinationStrategywill be applied by default. -
(hostnameHostnameInput | None, default:None) –Optional Watchpost-level hostname strategy or value used to resolve the piggyback host for results.
-
(hostname_fallback_to_default_hostname_generationbool, default:True) –Whether to fall back to the default hostname generation "{service_name}-{environment.name}" when no strategy resolves a hostname.
-
(hostname_coerce_into_valid_hostnamebool, default:True) –Whether to coerce a non-compliant hostname into RFC1123 format during hostname resolution. If
False, a non-compliant hostname will result in an error.
Methods:
-
app_context–Provide a context where the current Watchpost instance is active.
-
register_datasource–Register a datasource type and its constructor arguments.
-
register_datasource_factory–Register a
DatasourceFactorythat can produce datasources. -
run_check–Run a single check across all its target environments.
-
run_checks–Run all checks and produce a Checkmk-compatible output stream.
-
run_checks_once–Run all the checks once and write the output stream to stdout.
-
verify_check_scheduling–Validate that checks can be scheduled and invoked correctly.
-
verify_hostname_generation–Validate that hostnames can be resolved for all checks and environments.
app_context
app_context() -> Generator[Watchpost]
Provide a context where the current Watchpost instance is active.
This sets the global context variable so helper utilities can access the current application instance during check execution.
Returns:
-
Generator[Watchpost]–The current
Watchpostinstance via a context manager.
register_datasource
register_datasource(
datasource_type: type[_D], **kwargs: dict[str, Any]
) -> None
Register a datasource type and its constructor arguments.
Parameters:
-
(datasource_typetype[_D]) –The
Datasourcesubclass to register. -
(kwargsdict[str, Any], default:{}) –Keyword arguments to use when instantiating the datasource.
register_datasource_factory
register_datasource_factory(
factory_type: type[_DF],
) -> None
Register a DatasourceFactory that can produce datasources.
Parameters:
-
(factory_typetype[_DF]) –The factory type to register.
run_check
run_check(
check: Check,
*,
custom_executor: CheckExecutor[list[ExecutionResult]]
| None = None,
use_cache: bool = True,
) -> Generator[ExecutionResult]
Run a single check across all its target environments.
Parameters:
-
(checkCheck) –The
Checkto run. -
(custom_executorCheckExecutor[list[ExecutionResult]] | None, default:None) –Optional executor used only for this call.
-
(use_cachebool, default:True) –Whether to use and update the per-check cache.
Yields:
-
Generator[ExecutionResult]–ExecutionResultobjects produced by the check for each environment.
run_checks
run_checks(act_as_agent: bool = True) -> Generator[bytes]
Run all checks and produce a Checkmk-compatible output stream.
This yields the agent header, the serialized results of all checks, and synthetic sections.
Parameters:
-
(act_as_agentbool, default:True) –If Watchpost should act as a full Checkmk agent, including the
<<<checkmk>>>preamble. This should be true if Watchpost is queried by the Checkmk site directly (via HTTP), but can be set to false if you have the Checkmk agent invoke Watchpost for you, for example.
Yields:
-
Generator[bytes]–Bytes in Checkmk agent format.
run_checks_once
run_checks_once(act_as_agent: bool = True) -> None
Run all the checks once and write the output stream to stdout.
This is a convenience method primarily intended for CLI usage.
Parameters:
-
(act_as_agentbool, default:True) –If Watchpost should act as a full Checkmk agent, including the
<<<checkmk>>>preamble. This should be true if Watchpost is queried by the Checkmk site directly (via HTTP), but can be set to false if you have the Checkmk agent invoke Watchpost for you, for example.
verify_check_scheduling
verify_check_scheduling(force: bool = False) -> None
Validate that checks can be scheduled and invoked correctly.
This verifies argument provisioning for each check and evaluates each strategy's configuration checks. It aggregates errors across all checks.
Parameters:
-
(forcebool, default:False) –Run verification even if it has already completed successfully.
Raises:
-
ExceptionGroup–If one or more checks are misconfigured.
verify_hostname_generation
verify_hostname_generation(force: bool = False) -> None
Validate that hostnames can be resolved for all checks and environments.
Parameters:
-
(forcebool, default:False) –Run verification even if it has already completed successfully.
Raises:
-
ExceptionGroup–If hostname resolution fails for any check/environment.
build_result
build_result(
ok_summary: str,
fail_summary: str,
base_details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
alternative_hostname: HostnameInput | None = None,
) -> OngoingCheckResult
Start building up a new check result that allows adding multiple OK/WARN/UNKNOWN/CRIT results, called "partials", eventually resulting in a regular check result that holds the worst check state provided by the individual results.
Use of this builder greatly simplifies scenarios where your check function validates multiple aspects of a single system or component but only returns a single check result: by allowing you to provide the status of each aspect as you check it through simple function calls on the builder instead of having to manually combine the results into a single check result, you can reduce the complexity of your check function and improve its readability.
Parameters:
-
(ok_summarystr) –Overall check summary that will be shown if the final result is OK.
-
(fail_summarystr) –Overall check summary that will be shown if the final result is WARN, UNKNOWN, or CRIT.
-
(base_detailsDetails | None, default:None) –Optional base details for the check result. They will always be included and then enriched by the details provided by partial results.
-
(name_suffixstr | None, default:None) –Optional suffix for the check result name.
-
(metricslist[Metric] | None, default:None) –Optional list of metrics associated with the check.
-
(alternative_hostnameHostnameInput | None, default:None) –Optional alternative hostname input for the check.
Returns:
-
OngoingCheckResult–An instance of OngoingCheckResult initialized with the provided
-
OngoingCheckResult–parameters and ready to receive partial results.
crit
crit(
summary: str,
details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
alternative_hostname: HostnameInput | None = None,
) -> CheckResult
Generates a CheckResult object indicating a CRIT check state.
This function creates and returns a CheckResult indicating the system or component is in a CRIT state. It allows for passing additional information such as a summary, details, name suffix, metrics, or an alternative hostname.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
-
(name_suffixstr | None, default:None) –A suffix to add to the check name as defined in the
@checkdecorator. This enables a single check function to return multiple results that create multiple services on the Checkmk side. -
(metricslist[Metric] | None, default:None) –An optional list of metrics to associate with the check.
-
(alternative_hostnameHostnameInput | None, default:None) –An optional hostname that overrides the hostname that would have been used otherwise.
Returns:
-
CheckResult–A
CheckResultobject representing the CRIT check result.
ok
ok(
summary: str,
details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
alternative_hostname: HostnameInput | None = None,
) -> CheckResult
Generates a CheckResult object indicating an OK check state.
This function creates and returns a CheckResult indicating the system or component is in an OK state. It allows for passing additional information such as a summary, details, name suffix, metrics, or an alternative hostname.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
-
(name_suffixstr | None, default:None) –A suffix to add to the check name as defined in the
@checkdecorator. This enables a single check function to return multiple results that create multiple services on the Checkmk side. -
(metricslist[Metric] | None, default:None) –An optional list of metrics to associate with the check.
-
(alternative_hostnameHostnameInput | None, default:None) –An optional hostname that overrides the hostname that would have been used otherwise.
Returns:
-
CheckResult–A
CheckResultobject representing the OK check result.
unknown
unknown(
summary: str,
details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
alternative_hostname: HostnameInput | None = None,
) -> CheckResult
Generates a CheckResult object indicating an UNKNOWN check state.
This function creates and returns a CheckResult indicating the system or component is in an UNKNOWN state. It allows for passing additional information such as a summary, details, name suffix, metrics, or an alternative hostname.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
-
(name_suffixstr | None, default:None) –A suffix to add to the check name as defined in the
@checkdecorator. This enables a single check function to return multiple results that create multiple services on the Checkmk side. -
(metricslist[Metric] | None, default:None) –An optional list of metrics to associate with the check.
-
(alternative_hostnameHostnameInput | None, default:None) –An optional hostname that overrides the hostname that would have been used otherwise.
Returns:
-
CheckResult–A
CheckResultobject representing the UNKNOWN check result.
warn
warn(
summary: str,
details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
alternative_hostname: HostnameInput | None = None,
) -> CheckResult
Generates a CheckResult object indicating a WARN check state.
This function creates and returns a CheckResult indicating the system or component is in a WARN state. It allows for passing additional information such as a summary, details, name suffix, metrics, or an alternative hostname.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
-
(name_suffixstr | None, default:None) –A suffix to add to the check name as defined in the
@checkdecorator. This enables a single check function to return multiple results that create multiple services on the Checkmk side. -
(metricslist[Metric] | None, default:None) –An optional list of metrics to associate with the check.
-
(alternative_hostnameHostnameInput | None, default:None) –An optional hostname that overrides the hostname that would have been used otherwise.
Returns:
-
CheckResult–A
CheckResultobject representing the WARN check result.
app
Watchpost application and Starlette integration.
This module provides the Watchpost ASGI application that discovers and runs
checks, manages datasources, applies scheduling strategies, resolves hostnames,
coordinates execution via an internal executor, and exposes HTTP endpoints.
Notes
- The app streams Checkmk-compatible output from
/. - Operational endpoints expose executor statistics and errors.
- Global app context is available via
current_appinglobals.py.
Classes:
-
Watchpost–Main Watchpost application and ASGI app.
Watchpost
Watchpost(
*,
checks: list[Check | ModuleType],
execution_environment: Environment,
version: str = "unknown",
max_workers: int | None = None,
executor: CheckExecutor[list[ExecutionResult]]
| None = None,
check_cache_storage: Storage | None = None,
default_scheduling_strategies: list[SchedulingStrategy]
| None = None,
hostname: HostnameInput | None = None,
hostname_fallback_to_default_hostname_generation: bool = True,
hostname_coerce_into_valid_hostname: bool = True,
)
Main Watchpost application and ASGI app.
Watchpost discovers and runs checks across environments, coordinates
datasources, applies scheduling strategies, and generates Checkmk-compatible
output. A Watchpost instance is also an ASGI application backed by
Starlette and exposes operational endpoints.
Notes
The instance manages a per-check result cache and a key-aware executor to run checks without blocking. It also verifies check configuration and hostname generation at application startup.
Parameters:
-
(checkslist[Check | ModuleType]) –A list of
Checkobjects or Python modules to scan for checks. Modules are discovered recursively. -
(execution_environmentEnvironment) –The environment in which this Watchpost instance runs checks.
-
(versionstr, default:'unknown') –Version string included in the Checkmk agent header output.
-
(max_workersint | None, default:None) –Maximum number of worker threads for the internal executor. Used when no custom
executoris provided. -
(executorCheckExecutor[list[ExecutionResult]] | None, default:None) –Optional custom
CheckExecutorto use instead of the default. -
(check_cache_storageStorage | None, default:None) –Optional storage backend for the per-check result cache. Defaults to in-memory storage.
-
(default_scheduling_strategieslist[SchedulingStrategy] | None, default:None) –Default strategies applied to all checks in addition to those specified by checks and datasources. If not provided, the
DetectImpossibleCombinationStrategywill be applied by default. -
(hostnameHostnameInput | None, default:None) –Optional Watchpost-level hostname strategy or value used to resolve the piggyback host for results.
-
(hostname_fallback_to_default_hostname_generationbool, default:True) –Whether to fall back to the default hostname generation "{service_name}-{environment.name}" when no strategy resolves a hostname.
-
(hostname_coerce_into_valid_hostnamebool, default:True) –Whether to coerce a non-compliant hostname into RFC1123 format during hostname resolution. If
False, a non-compliant hostname will result in an error.
Methods:
-
app_context–Provide a context where the current Watchpost instance is active.
-
register_datasource–Register a datasource type and its constructor arguments.
-
register_datasource_factory–Register a
DatasourceFactorythat can produce datasources. -
run_check–Run a single check across all its target environments.
-
run_checks–Run all checks and produce a Checkmk-compatible output stream.
-
run_checks_once–Run all the checks once and write the output stream to stdout.
-
verify_check_scheduling–Validate that checks can be scheduled and invoked correctly.
-
verify_hostname_generation–Validate that hostnames can be resolved for all checks and environments.
app_context
app_context() -> Generator[Watchpost]
Provide a context where the current Watchpost instance is active.
This sets the global context variable so helper utilities can access the current application instance during check execution.
Returns:
-
Generator[Watchpost]–The current
Watchpostinstance via a context manager.
register_datasource
register_datasource(
datasource_type: type[_D], **kwargs: dict[str, Any]
) -> None
Register a datasource type and its constructor arguments.
Parameters:
-
(datasource_typetype[_D]) –The
Datasourcesubclass to register. -
(kwargsdict[str, Any], default:{}) –Keyword arguments to use when instantiating the datasource.
register_datasource_factory
register_datasource_factory(
factory_type: type[_DF],
) -> None
Register a DatasourceFactory that can produce datasources.
Parameters:
-
(factory_typetype[_DF]) –The factory type to register.
run_check
run_check(
check: Check,
*,
custom_executor: CheckExecutor[list[ExecutionResult]]
| None = None,
use_cache: bool = True,
) -> Generator[ExecutionResult]
Run a single check across all its target environments.
Parameters:
-
(checkCheck) –The
Checkto run. -
(custom_executorCheckExecutor[list[ExecutionResult]] | None, default:None) –Optional executor used only for this call.
-
(use_cachebool, default:True) –Whether to use and update the per-check cache.
Yields:
-
Generator[ExecutionResult]–ExecutionResultobjects produced by the check for each environment.
run_checks
run_checks(act_as_agent: bool = True) -> Generator[bytes]
Run all checks and produce a Checkmk-compatible output stream.
This yields the agent header, the serialized results of all checks, and synthetic sections.
Parameters:
-
(act_as_agentbool, default:True) –If Watchpost should act as a full Checkmk agent, including the
<<<checkmk>>>preamble. This should be true if Watchpost is queried by the Checkmk site directly (via HTTP), but can be set to false if you have the Checkmk agent invoke Watchpost for you, for example.
Yields:
-
Generator[bytes]–Bytes in Checkmk agent format.
run_checks_once
run_checks_once(act_as_agent: bool = True) -> None
Run all the checks once and write the output stream to stdout.
This is a convenience method primarily intended for CLI usage.
Parameters:
-
(act_as_agentbool, default:True) –If Watchpost should act as a full Checkmk agent, including the
<<<checkmk>>>preamble. This should be true if Watchpost is queried by the Checkmk site directly (via HTTP), but can be set to false if you have the Checkmk agent invoke Watchpost for you, for example.
verify_check_scheduling
verify_check_scheduling(force: bool = False) -> None
Validate that checks can be scheduled and invoked correctly.
This verifies argument provisioning for each check and evaluates each strategy's configuration checks. It aggregates errors across all checks.
Parameters:
-
(forcebool, default:False) –Run verification even if it has already completed successfully.
Raises:
-
ExceptionGroup–If one or more checks are misconfigured.
verify_hostname_generation
verify_hostname_generation(force: bool = False) -> None
Validate that hostnames can be resolved for all checks and environments.
Parameters:
-
(forcebool, default:False) –Run verification even if it has already completed successfully.
Raises:
-
ExceptionGroup–If hostname resolution fails for any check/environment.
cache
Caching utilities and pluggable storage backends.
This module provides a small, consistent caching API (Cache) and a set of
storage backends (Storage) for in-memory, disk, and Redis persistence. It also
includes a memoization decorator for function-level caching.
Classes:
-
Cache–High-level caching API using a pluggable storage backend.
-
CacheEntry–Represents a cached value together with metadata.
-
CacheKey–A compound key that uniquely identifies a cache entry within a package.
-
ChainedStorage–A storage implementation that chains multiple storage backends together.
-
DiskStorage–A disk-backed storage backend using Pickle-serialized
CacheEntryobjects. -
InMemoryStorage–A simple in-memory storage backend.
-
RedisStorage–A Redis-backed storage backend.
-
Storage–Base interface for cache storage backends.
Functions:
-
get_caller_package–Return the caller's package name.
Cache
Cache(storage: Storage)
High-level caching API using a pluggable storage backend.
Use get and store to interact with the cache directly, or the memoize
decorator to cache function results.
Methods:
-
get–Retrieve a value from the cache.
-
memoize–Memoize a function by caching its return value.
-
store–Store a value in the cache.
get
get(
key: Hashable,
default: T | None = None,
*,
package: str | None = None,
return_expired: bool = False,
) -> CacheEntry[T] | None
Retrieve a value from the cache.
Parameters:
-
(keyHashable) –The key to look up. Must be hashable and unique within the given package.
-
(defaultT | None, default:None) –An optional default value to return when the key is not found.
-
(packagestr | None, default:None) –The package namespace. If not provided, the package of the caller is used.
-
(return_expiredbool, default:False) –Whether to return an expired entry once before it is removed. (This behavior does depend on the storage backend supporting this.)
Returns:
-
CacheEntry[T] | None–The cache entry if found. If not found, returns
Nonewhen no -
CacheEntry[T] | None–default is given, otherwise a cache entry wrapping the default
-
CacheEntry[T] | None–value.
memoize
memoize(
*,
key: Hashable | None = None,
key_generator: Callable[P, Hashable] | None = None,
package: str | None = None,
return_expired: bool = False,
ttl: timedelta | None = None,
) -> Callable[[Callable[P, R]], Callable[P, R]]
Memoize a function by caching its return value.
Use either a fixed key or a key_generator to compute the cache key
from call arguments. If key contains format placeholders like "{arg}",
they will be formatted from the function's bound arguments.
Parameters:
-
(keyHashable | None, default:None) –A static key or a format string used to build the key. Mutually exclusive with
key_generator. -
(key_generatorCallable[P, Hashable] | None, default:None) –A callable that receives the function's arguments and returns a hashable key. Mutually exclusive with
key. -
(packagestr | None, default:None) –The package namespace. If not provided, the package of the caller is used.
-
(return_expiredbool, default:False) –Whether to return an expired entry once before it is recomputed and overwritten.
-
(ttltimedelta | None, default:None) –Optional time-to-live for stored values.
Returns:
-
Callable[[Callable[P, R]], Callable[P, R]]–A decorator that wraps the function and provides cached results.
Notes
- Only one of
keyorkey_generatormust be provided. - If
return_expiredis True, an expired value may be returned once; it is then replaced with a fresh value.
store
store(
key: Hashable,
value: T,
*,
package: str | None = None,
ttl: timedelta | None = None,
) -> CacheEntry[T]
Store a value in the cache.
Parameters:
-
(keyHashable) –The key under which to store the value. Must be hashable and unique within the given package.
-
(valueT) –The value to store.
-
(packagestr | None, default:None) –The package namespace. If not provided, the package of the caller is used.
-
(ttltimedelta | None, default:None) –Optional time-to-live for the entry. When omitted, the entry does not expire.
Returns:
-
CacheEntry[T]–The cache entry that was stored.
CacheEntry
dataclass
CacheEntry(
cache_key: CacheKey,
value: T,
added_at: datetime | None,
ttl: timedelta | None,
)
Represents a cached value together with metadata.
This object stores the value and all information needed by backends to determine freshness and validity.
Methods:
-
is_expired–Determine whether the cache entry has expired.
Attributes:
-
added_at(datetime | None) –The timestamp when this entry was stored.
Nonemeans the value is a -
cache_key(CacheKey) –The globally unique cache key for this entry.
-
ttl(timedelta | None) –The time-to-live for this entry.
Nonemeans the value does not expire. -
value(T) –The cached value.
added_at
instance-attribute
The timestamp when this entry was stored. None means the value is a
default and not persisted yet.
ttl
instance-attribute
The time-to-live for this entry. None means the value does not expire.
CacheKey
dataclass
A compound key that uniquely identifies a cache entry within a package.
The combination of key and package forms the globally unique key used by
storage backends.
Attributes:
ChainedStorage
Bases: Storage
A storage implementation that chains multiple storage backends together.
On retrieval, it tries each storage in order until it finds a hit. On storage, it stores the value in all storage backends.
Parameters:
-
(storageslist[Storage]) –Storage backends to chain. The order defines lookup priority; the first backend with a hit will be used.
DiskStorage
DiskStorage(directory: str)
Bases: Storage
A disk-backed storage backend using Pickle-serialized CacheEntry objects.
Entries are stored under a versioned directory and sharded by a hash prefix.
Parameters:
-
(directorystr) –Directory root where cache files are written.
InMemoryStorage
Bases: Storage
A simple in-memory storage backend.
Useful for tests or ephemeral caching within a single process. Entries are lost when the process exits.
RedisStorage
RedisStorage(
redis_client: Redis,
*,
use_redis_ttl: bool = True,
redis_key_infix: str | None = None,
)
Bases: Storage
A Redis-backed storage backend.
When use_redis_ttl is True, Redis key expiration is used so expired
entries are never returned by get.
Parameters:
-
(redis_clientRedis) –The Redis client instance.
-
(use_redis_ttlbool, default:True) –Whether to use Redis TTL for automatic expiry. When
True, expired entries are not returned. -
(redis_key_infixstr | None, default:None) –Optional infix to namespace keys to avoid collisions between multiple caches or watchposts.
Methods:
get
get(
cache_key: CacheKey, return_expired: bool = False
) -> CacheEntry[T] | None
Retrieve a cache entry from Redis.
Parameters:
-
(cache_keyCacheKey) –The key to retrieve the value for.
-
(return_expiredbool, default:False) –Whether to return an expired entry once before it is removed. (If Redis's TTL is used, an expired entry is never returned and this has no effect.)
Returns:
-
CacheEntry[T] | None–The cache entry if found, otherwise
None.
store
store(entry: CacheEntry) -> None
Storage
Bases: ABC
Base interface for cache storage backends.
Implementations persist and retrieve CacheEntry objects.
Methods:
get
abstractmethod
get(
cache_key: CacheKey, return_expired: bool = False
) -> CacheEntry[T] | None
Retrieve a cache entry by key.
Parameters:
-
(cache_keyCacheKey) –The cache key to look up.
-
(return_expiredbool, default:False) –Whether to return an expired entry once before it is removed.
Returns:
-
CacheEntry[T] | None–The cache entry if found, otherwise
None.
store
abstractmethod
store(entry: CacheEntry) -> None
check
Check definitions, execution helpers, and caching.
This module provides the core pieces for defining and running monitoring checks:
Check: a lightweight wrapper around a user-defined check function plus metadata such as the service name, labels, environments, and hostname strategy.check: a decorator to declare checks in a Pythonic way.CheckCache: a small helper that stores and retrieves executed check results.
Notes:
- A
Checkmaps to one or more Checkmk services. The application turns results produced by a check into Checkmk-compatible output later. Service labels map to Checkmk service labels. - Both synchronous and asynchronous check functions are supported.
- Hostname resolution (the Checkmk piggyback host) is delegated to the
hostname strategy; see
watchpost.hostnamefor details.
Classes:
-
Check–Represents a monitoring check definition.
-
CheckCache–Caches executed check results per check and environment.
-
ErrorHandler–A strategy for transforming error results to match a check's service
Functions:
-
check–Decorator to define a Watchpost check function.
Check
dataclass
Check(
check_function: CheckFunction,
service_name: str,
service_labels: dict[str, Any],
environments: list[Environment],
cache_for: timedelta | None,
invocation_information: InvocationInformation
| None = None,
scheduling_strategies: list[SchedulingStrategy]
| None = None,
hostname_strategy: HostnameStrategy | None = None,
error_handlers: list[ErrorHandler] | None = None,
)
Represents a monitoring check definition.
A Check wraps a user-defined check function together with metadata such as
the service name, labels, environments, caching, scheduling, and hostname
strategy. A Check maps to one or more Checkmk services; each execution
produces one or more results that are later rendered as Checkmk-compatible
output.
Methods:
-
get_function_kwargs–Build the keyword arguments to call the check function.
-
run_async–Execute the check function asynchronously and return
ExecutionResults. -
run_sync–Execute the check function synchronously and return
ExecutionResults.
Attributes:
-
cache_for(timedelta | None) –Optional time-to-live for caching check results. If set, results are cached
-
check_function(CheckFunction) –The user-provided function that implements the check. It may be synchronous
-
environments(list[Environment]) –The environments against which this check is executed.
-
error_handlers(list[ErrorHandler] | None) –Optional error handlers that are called to adapt the results when the check
-
hostname_strategy(HostnameStrategy | None) –Strategy to resolve the piggyback host (hostname) for results of this
-
invocation_information(InvocationInformation | None) –Source location information for the check definition (file and line).
-
is_async(bool) –Indicates whether the check function is asynchronous.
-
name(str) –Returns the fully qualified name of the check function.
-
scheduling_strategies(list[SchedulingStrategy] | None) –Optional scheduling strategies that influence when, where and how the check
-
service_labels(dict[str, Any]) –Labels attached to the service. This maps to Checkmk service labels exactly.
-
service_name(str) –The base service name used for the Checkmk service created by this check.
-
signature(Signature) –Returns the cached
inspect.Signatureof the check function. -
type_hints(dict[str, Any]) –Returns the resolved type hints for the check function's parameters.
cache_for
instance-attribute
Optional time-to-live for caching check results. If set, results are cached for this duration, otherwise they are always re-executed after Checkmk picks up results.
check_function
instance-attribute
The user-provided function that implements the check. It may be synchronous
or asynchronous and may accept one or more Datasource instances and
optionally an environment: Environment parameter.
environments
instance-attribute
environments: list[Environment]
The environments against which this check is executed.
error_handlers
class-attribute
instance-attribute
error_handlers: list[ErrorHandler] | None = None
Optional error handlers that are called to adapt the results when the check function raises an exception.
hostname_strategy
class-attribute
instance-attribute
hostname_strategy: HostnameStrategy | None = None
Strategy to resolve the piggyback host (hostname) for results of this check. If not set here, environment- or app-level strategies may apply.
invocation_information
class-attribute
instance-attribute
invocation_information: InvocationInformation | None = None
Source location information for the check definition (file and line). Used for diagnostics and included in output.
is_async
property
Indicates whether the check function is asynchronous.
Returns True if the function is a coroutine or a coroutine function,
otherwise False.
name
property
Returns the fully qualified name of the check function.
This is used as a stable identifier in places like caching keys and diagnostics.
scheduling_strategies
class-attribute
instance-attribute
scheduling_strategies: list[SchedulingStrategy] | None = (
None
)
Optional scheduling strategies that influence when, where and how the check is run.
service_labels
instance-attribute
Labels attached to the service. This maps to Checkmk service labels exactly.
service_name
instance-attribute
The base service name used for the Checkmk service created by this check.
A result may append a name_suffix to this name to create multiple
services.
type_hints
property
Returns the resolved type hints for the check function's parameters.
The mapping excludes the return annotation. If resolving forward
references raises NameError, it falls back to a mapping derived from
the function signature.
get_function_kwargs
get_function_kwargs(
*,
environment: Environment,
datasources: dict[str, Datasource],
) -> dict[str, Environment | Datasource]
Build the keyword arguments to call the check function.
Parameters:
-
(environmentEnvironment) –The environment in which the check runs. Only included in the result if the check function declares an
environmentparameter. -
(datasourcesdict[str, Datasource]) –A mapping of datasource names to instantiated
Datasourceobjects.
Returns:
-
dict[str, Environment | Datasource]–A dictionary of keyword arguments to pass to the check function.
run_async
async
run_async(
*,
watchpost: Watchpost,
environment: Environment,
datasources: dict[str, Datasource],
) -> list[ExecutionResult]
Execute the check function asynchronously and return ExecutionResults.
Captures stdout/stderr during execution, then normalizes and
materializes results. Raises TypeError if the check function is
synchronous.
Parameters:
-
(watchpostWatchpost) –The Watchpost application providing execution context.
-
(environmentEnvironment) –The environment in which the check should run.
-
(datasourcesdict[str, Datasource]) –Instantiated
Datasourceobjects passed as keyword arguments.
Returns:
-
list[ExecutionResult]–A list of
ExecutionResultinstances created from the check output.
Raises:
-
TypeError–If the check is synchronous. Use
run_syncinstead.
run_sync
run_sync(
*,
watchpost: Watchpost,
environment: Environment,
datasources: dict[str, Datasource],
) -> list[ExecutionResult]
Execute the check function synchronously and return ExecutionResults.
Captures stdout/stderr during execution, then normalizes and
materializes results. Raises TypeError if the check function is
asynchronous (use run_async instead).
Parameters:
-
(watchpostWatchpost) –The Watchpost application providing execution context.
-
(environmentEnvironment) –The environment in which the check should run.
-
(datasourcesdict[str, Datasource]) –Instantiated
Datasourceobjects passed as keyword arguments.
Returns:
-
list[ExecutionResult]–A list of
ExecutionResultinstances created from the check output.
Raises:
-
TypeError–If the check is asynchronous. Use
run_asyncinstead.
CheckCache
Caches executed check results per check and environment.
This class is a thin wrapper around Cache that uses a composite key based
on the check definition and environment. Values are lists of
ExecutionResult objects, stored with a TTL derived from the Check.
Parameters:
-
(storageStorage) –The storage backend used to persist cache entries.
Methods:
-
get_check_results_cache_entry–Retrieve cached results for a given check and environment.
-
store_check_results–Store the results of a check execution.
get_check_results_cache_entry
get_check_results_cache_entry(
check: Check,
environment: Environment,
return_expired: bool = False,
) -> CacheEntry[list[ExecutionResult]] | None
Retrieve cached results for a given check and environment.
Parameters:
-
(checkCheck) –The check whose results should be retrieved.
-
(environmentEnvironment) –The environment associated with the cached results.
-
(return_expiredbool, default:False) –Whether to return an entry even if it has expired. An expired entry is returned at most once.
Returns:
-
CacheEntry[list[ExecutionResult]] | None–A
CacheEntrycontaining a list ofExecutionResult, orNoneif -
CacheEntry[list[ExecutionResult]] | None–no entry exists.
store_check_results
store_check_results(
check: Check,
environment: Environment,
results: list[ExecutionResult],
override_cache_for: timedelta | None = None,
) -> None
Store the results of a check execution.
Parameters:
-
(checkCheck) –The check that produced the results.
-
(environmentEnvironment) –The environment in which the check ran.
-
(resultslist[ExecutionResult]) –The list of
ExecutionResultinstances to cache. -
(override_cache_fortimedelta | None, default:None) –Override the time to cache the result for.
Notes
This is a no-op if check.cache_for is None (caching disabled).
ErrorHandler
Bases: Protocol
A strategy for transforming error results to match a check's service pattern.
When a check function fails to execute successfully (e.g., raises an
exception, datasource is unavailable, or scheduling prevents execution),
Watchpost needs to create synthetic monitoring results. An ErrorHandler
transforms the initial error result(s) to match the services that the check
would normally create.
For example, if a check normally produces results for multiple hostnames or with different name suffixes, an ErrorHandler can expand a single error result into multiple results with the appropriate hostname and service name variations.
Multiple ErrorHandlers can be attached to a single check. They are applied sequentially, with each handler receiving the output of the previous one. This allows composition of different expansion strategies (e.g., first expand by hostname, then by name suffix).
See expand_by_hostname() and expand_by_name_suffix() for built-in
implementations that handle common expansion patterns.
check
check(
*,
name: str,
service_labels: dict[str, Any],
environments: list[Environment],
cache_for: timedelta | str | None,
hostname: HostnameInput | None = None,
scheduling_strategies: list[SchedulingStrategy]
| None = None,
error_handlers: list[ErrorHandler] | None = None,
) -> Callable[[CheckFunction], Check]
Decorator to define a Watchpost check function.
Use this decorator to declare a check and attach metadata such as the service name, labels, environments, caching, and an optional hostname strategy. The decorated function may return a single result or result-builder, a list of results or result-builders, or yield results or result-builders as a generator.
This decorator supports both sync and async functions.
Parameters:
-
(namestr) –The Checkmk service name for this check.
-
(service_labelsdict[str, Any]) –Labels to attach to the service. This maps to Checkmk service labels exactly.
-
(environmentslist[Environment]) –The environments in which this check will be executed.
-
(cache_fortimedelta | str | None) –Optional cache duration. Accepts a
timedeltaor a string supported bynormalize_to_timedelta. If provided, results are cached for this duration. -
(hostnameHostnameInput | None, default:None) –An optional hostname input or strategy that controls piggyback host resolution for results of this check.
-
(scheduling_strategieslist[SchedulingStrategy] | None, default:None) –Optional list of scheduling strategies to apply to this check.
-
(error_handlerslist[ErrorHandler] | None, default:None) –Optional list of error handlers that are called to adapt the results when the check function raises an exception.
Returns:
-
Callable[[CheckFunction], Check]–A
Checkinstance wrapping the decorated function and provided -
Callable[[CheckFunction], Check]–metadata.
Notes
- A
CheckResultmay set aname_suffixto create multiple services from a single check function. - See
watchpost.hostnamefor the available hostname strategy inputs.
cli
Modules:
-
loader–
loader
Classes:
-
AppNotFound–Custom exception for when the app cannot be found.
Functions:
-
find_app–Finds and loads the Watchpost app instance.
AppNotFound
Bases: Exception
Custom exception for when the app cannot be found.
find_app
find_app(app_str: str | None) -> Watchpost
Finds and loads the Watchpost app instance.
The search order is:
1. The app_str argument if provided (e.g., 'my_module:app').
2. Convention: look for a Watchpost instance named app in watchpost.py,
then app.py, then main.py in the current directory.
datasource
Datasource primitives and factory helpers.
This module defines the Datasource base class, the DatasourceFactory
protocol for constructing datasources, a FromFactory marker to declare
factory-created dependencies in check parameters, and a DatasourceUnavailable
exception to signal that a datasource is not available or otherwise unusable.
Notes
Datasources and factories can declare scheduling_strategies that Watchpost
uses to decide where a check may run.
Classes:
-
Datasource–Base class for datasources that provide input to checks.
-
DatasourceFactory–Protocol for factories that construct datasources for checks.
-
DatasourceUnavailable–Raised when a datasource cannot be created, accessed, or used.
-
FromFactory–Marker used with
typing.Annotatedto request a datasource from a factory.
Datasource
Bases: ABC
Base class for datasources that provide input to checks.
Subclass this to integrate systems your checks read from (APIs, files, services, etc.). Datasources can influence where and when checks are run by exposing scheduling strategies.
Attributes:
-
scheduling_strategies(tuple[SchedulingStrategy, ...] | EllipsisType | None) –Optional scheduling strategies that constrain where a check may run.
scheduling_strategies
class-attribute
instance-attribute
scheduling_strategies: (
tuple[SchedulingStrategy, ...] | EllipsisType | None
) = ...
Optional scheduling strategies that constrain where a check may run.
- Ellipsis (...) means "unspecified". If a datasource created by a factory
leaves this as Ellipsis, Watchpost will fall back to the factory's
own
scheduling_strategiesif any. - A tuple provides explicit strategies for this datasource and takes precedence over any factory strategies.
- None or an empty tuple means "no constraints".
DatasourceFactory
Bases: Protocol
Protocol for factories that construct datasources for checks.
A factory centralizes configuration and creation logic for a datasource.
Watchpost can use factory-level scheduling_strategies when the created
datasource does not define its own.
Attributes:
-
new(Callable[..., Datasource]) –Function that creates and returns a datasource instance.
-
scheduling_strategies(tuple[SchedulingStrategy, ...] | EllipsisType | None) –Optional scheduling strategies applied to datasources created by this
new
class-attribute
new: Callable[..., Datasource]
Function that creates and returns a datasource instance.
Watchpost forwards the positional and keyword arguments declared
via FromFactory(..., *args, **kwargs) to this callable.
scheduling_strategies
class-attribute
instance-attribute
scheduling_strategies: (
tuple[SchedulingStrategy, ...] | EllipsisType | None
) = ...
Optional scheduling strategies applied to datasources created by this factory.
A tuple sets explicit constraints; None or an empty tuple means "no constraints".
DatasourceUnavailable
Bases: Exception
Raised when a datasource cannot be created, accessed, or used.
Watchpost raises this error when a check requests data, but the underlying system is not reachable, misconfigured, or otherwise unavailable.
FromFactory
FromFactory(
factory: type[DatasourceFactory],
*args: Any,
**kwargs: Any,
)
FromFactory(
factory: type[DatasourceFactory] | Any = None,
*args: Any,
**kwargs: Any,
)
Marker used with typing.Annotated to request a datasource from a factory.
Use in a check parameter annotation as:
Annotated[MyDatasource, FromFactory(MyFactory, "service")]
You may omit the factory type when the parameter type implements the factory protocol:
Annotated[MyDatasourceWithFactory, FromFactory("service")]
Parameters are forwarded to the factory's new callable. Watchpost caches
the constructed datasource per factory type and argument set.
Parameters:
-
(factorytype[DatasourceFactory] | Any, default:None) –Optional factory type used to create the datasource. If omitted, Watchpost infers the factory from the annotated parameter's type. If the first positional argument is not a type, it is treated as a factory argument and the factory is inferred.
-
(argsAny, default:()) –Positional arguments forwarded to the factory
newcallable. -
(kwargsAny, default:{}) –Keyword arguments forwarded to the factory
newcallable.
Methods:
-
cache_key–Generate a stable cache key for this factory invocation.
cache_key
cache_key(
type_key: type[DatasourceFactory] | None,
) -> tuple[type[DatasourceFactory] | None, int, int]
Generate a stable cache key for this factory invocation.
Parameters:
-
(type_keytype[DatasourceFactory] | None) –Fallback factory type to use when this instance did not specify a factory explicitly (i.e., it will be inferred from the annotated parameter type).
Returns:
-
type[DatasourceFactory] | None–A tuple that identifies the factory type and the provided arguments,
-
int–suitable for use as a cache key.
discover_checks
Utilities for discovering checks defined in modules and packages.
This module scans Python modules for global Check instances and, when
requested, traverses packages to find checks across submodules. It offers
predicates to include or exclude modules, an optional per-check filter, and
configurable error handling for import failures.
Classes:
-
DiscoveryError–Raised when a submodule import fails during discovery and strict error
Functions:
-
discover_checks–Discover
Checkinstances defined as global names in a module or package.
DiscoveryError
Bases: Exception
Raised when a submodule import fails during discovery and strict error handling is enabled.
This exception is raised only when raise_on_import_error=True is passed to
discover_checks() and a submodule cannot be imported while traversing a
package.
discover_checks
discover_checks(
module: ModuleType | str,
*,
recursive: bool = True,
include_module: ModulePredicate | None = None,
exclude_module: ModulePredicate | None = None,
check_filter: CheckPredicate | None = None,
raise_on_import_error: bool = False,
) -> list[Check]
Discover Check instances defined as global names in a module or package.
This function scans the given module for global Check objects and, when
recursive is enabled, traverses subpackages to discover checks across the
package tree. It supports module-level include/exclude predicates, a
per-check filter, and optional strict error handling for imports.
Parameters:
-
(moduleModuleType | str) –The root module object or dotted module name to scan for checks.
-
(recursivebool, default:True) –Indicates whether to traverse subpackages when the module is a package.
-
(include_moduleModulePredicate | None, default:None) –Predicate receiving the imported module. Return True to include the module in scanning; return False to skip it. Use this to constrain traversal (for example, skip test modules or expensive imports).
-
(exclude_moduleModulePredicate | None, default:None) –Predicate receiving the imported module. If it returns True, the module is skipped. This is applied after
include_module. -
(check_filterCheckPredicate | None, default:None) –Predicate receiving
(check, module, name)that decides whether a discoveredCheckshould be included. Return True to keep it. -
(raise_on_import_errorbool, default:False) –If True, raise a
DiscoveryErrorwhen a submodule import fails while traversing packages. If False (default), such modules are skipped.
Returns:
-
list[Check]–A list of discovered
Checkinstances. If the sameCheckobject is -
list[Check]–re-exported from multiple modules, it appears only once.
Raises:
-
DiscoveryError–If a submodule import fails and
raise_on_import_erroris True.
Notes
Checks are discovered by scanning module globals and selecting objects
that are instances of Check. Identity de-duplicates duplicate objects
to avoid listing the same Check multiple times when re-exported.
environment
Execution environments and registry.
This module defines Environment, representing where a check runs or targets,
and EnvironmentRegistry, a simple container to manage named environments.
Notes
Environments can carry hostname configuration used during result output.
Classes:
-
Environment–Represents a logical environment in which checks run.
-
EnvironmentRegistry–Simple in-memory registry of
Environmentobjects.
Environment
Represents a logical environment in which checks run.
An environment typically maps to how or where checks are executed (for example: dev, stage, prod, monitoring). It can carry a hostname resolution strategy and arbitrary metadata that checks and data sources may use to alter behavior.
Parameters:
-
(namestr) –The name of the environment (e.g., "dev", "stage", "prod", "monitoring").
-
(hostnameHostnameInput | None, default:None) –Input used to determine the hostname when running checks in this environment. Accepts the same forms as
HostnameInputsuch as a template string, a callable, or a strategy instance. If omitted, the application may fall back to its default hostname generation. -
(metadataHashable, default:{}) –Arbitrary, hashable metadata attached to the environment. Checks and data sources may consult these values to change behavior.
Notes
Hostname handling integrates with the hostname resolution system in
watchpost.hostname. The chosen strategy ultimately influences the
Checkmk host a service is associated with.
EnvironmentRegistry
Simple in-memory registry of Environment objects.
The registry provides dictionary-like access and helpers to create and manage environments used by a Watchpost application.
Methods:
-
add–Add or replace an environment by its name.
-
get–Return the environment for the given name, or a default if missing.
-
new–Create a new environment, add it to the registry, and return it.
add
add(environment: Environment) -> None
Add or replace an environment by its name.
Parameters:
-
(environmentEnvironment) –The environment to register. If another environment with the same name exists, it will be overwritten.
get
get(
name: str, default: Environment | None = None
) -> Environment | None
Return the environment for the given name, or a default if missing.
Parameters:
-
(namestr) –The environment name to look up.
-
(defaultEnvironment | None, default:None) –Value to return when the name is not present.
Returns:
-
Environment | None–The matching
Environment, or the provided default.
new
new(
name: str,
*,
hostname: HostnameInput | None = None,
**metadata: Hashable,
) -> Environment
Create a new environment, add it to the registry, and return it.
Parameters:
-
(namestr) –The name of the environment to create.
-
(hostnameHostnameInput | None, default:None) –Input used to determine the hostname for this environment. See
Environment.__init__for supported forms. -
(metadataHashable, default:{}) –Arbitrary, hashable metadata to attach to the environment.
Returns:
-
Environment–The created and registered
Environmentinstance.
executor
Threaded check executor for Watchpost.
Provides a non-blocking, key-aware execution engine that de-duplicates work per key and can run both synchronous and asynchronous check functions. It exposes lightweight statistics used by the HTTP endpoints and tests.
Classes:
-
AsyncioLoopThread–Run an asyncio event loop in a dedicated background thread.
-
BlockingCheckExecutor–Execute checks while blocking until results are available.
-
CheckExecutor–Execute checks concurrently while avoiding duplicate work per key.
AsyncioLoopThread
Bases: Thread
Run an asyncio event loop in a dedicated background thread.
The thread creates its own event loop and runs it forever until stopped.
CheckExecutor uses this to execute coroutine functions without blocking
the worker threads in the thread pool.
BlockingCheckExecutor
Bases: CheckExecutor[T]
Execute checks while blocking until results are available.
This variant waits for all futures of a key to complete when result() is
called. It is useful for tests and simple CLI usage where non-blocking
behavior is not required.
Notes
Prefer the default CheckExecutor for production use. This class is
provided for special cases (such as the CLI or in unit-tests) where
synchronous behavior is desired.
Classes:
-
Statistics–Summary statistics of the executor state.
Methods:
-
errored–Return a mapping of keys to stringified exceptions for errored jobs.
-
result–Wait for all active futures of the key and then return the next result.
-
shutdown–Shut down the executor and stop the background event loop.
-
statistics–Compute executor statistics.
-
submit–Submit a function to run for a key, deduplicating concurrent work.
Attributes:
-
asyncio_loop(AbstractEventLoop) –Return the background asyncio event loop, starting it on first access.
asyncio_loop
property
Return the background asyncio event loop, starting it on first access.
Returns:
-
AbstractEventLoop–The event loop used to run coroutine functions submitted to this
-
AbstractEventLoop–executor.
Statistics
dataclass
Summary statistics of the executor state.
These values feed monitoring endpoints and tests to provide visibility into how many jobs are running, finished, or awaiting pickup.
Attributes:
-
awaiting_pickup(int) –Total number of finished futures (completed + errored) that have not
-
completed(int) –Number of successfully completed futures awaiting pickup.
-
errored(int) –Number of futures that completed with an exception and await pickup.
-
running(int) –Number of futures currently executing (not yet completed).
-
total(int) –Number of active futures across all keys (running + awaiting pickup).
awaiting_pickup
instance-attribute
Total number of finished futures (completed + errored) that have not
yet been retrieved via result().
completed
instance-attribute
Number of successfully completed futures awaiting pickup.
errored
instance-attribute
Number of futures that completed with an exception and await pickup.
errored
Return a mapping of keys to stringified exceptions for errored jobs.
Returns:
-
dict[str, str]–A dict mapping the string form of each key to the corresponding
-
dict[str, str]–exception message of futures that completed with an error and have
-
dict[str, str]–not yet been picked up via
result().
result
result(key: Hashable) -> T | None
Wait for all active futures of the key and then return the next result.
Parameters:
-
(keyHashable) –The key used when submitting the job(s).
Returns:
-
T | None–The completed result value, or None if no finished results are
-
T | None–queued after waiting.
shutdown
shutdown(wait: bool = False) -> None
Shut down the executor and stop the background event loop.
Parameters:
-
(waitbool, default:False) –If true, waits for all running futures to finish before returning. This is passed through to the underlying
ThreadPoolExecutor.shutdown().
statistics
statistics() -> Statistics
Compute executor statistics.
Returns:
-
Statistics–A
CheckExecutor.Statisticsinstance summarizing total, completed, -
Statistics–errored, running, and awaiting pickup futures.
submit
submit(
key: Hashable,
func: Callable[P, T | Awaitable[T]],
*args: P.args,
resubmit: bool = False,
**kwargs: P.kwargs,
) -> Future
Submit a function to run for a key, deduplicating concurrent work.
If another job with the same key is already running and resubmit is
false, this returns the existing future instead of starting a new one.
Coroutine functions are scheduled on the background asyncio loop.
Parameters:
-
(keyHashable) –The deduplication key. Only one active job per key is started unless
resubmit=Trueis given. -
(funcCallable[P, T | Awaitable[T]]) –The callable to execute. May be synchronous or a coroutine function.
-
(*argsP.args, default:()) –Positional arguments passed to the callable.
-
(resubmitbool, default:False) –When true, always schedules a new job even if one with the same key is already running.
-
(**kwargsP.kwargs, default:{}) –Keyword arguments passed to the callable.
Returns:
-
Future–A Future representing the running or already existing job.
CheckExecutor
Execute checks concurrently while avoiding duplicate work per key.
This executor wraps a ThreadPoolExecutor and adds key-aware submission:
if a job for a key is already running, later submissions with the same key
return the existing future unless resubmit=True is passed. The executor
can also run coroutine functions by scheduling them on a single background
asyncio event loop.
Classes:
-
Statistics–Summary statistics of the executor state.
Methods:
-
errored–Return a mapping of keys to stringified exceptions for errored jobs.
-
result–Retrieve the next finished result for a key.
-
shutdown–Shut down the executor and stop the background event loop.
-
statistics–Compute executor statistics.
-
submit–Submit a function to run for a key, deduplicating concurrent work.
Attributes:
-
asyncio_loop(AbstractEventLoop) –Return the background asyncio event loop, starting it on first access.
asyncio_loop
property
Return the background asyncio event loop, starting it on first access.
Returns:
-
AbstractEventLoop–The event loop used to run coroutine functions submitted to this
-
AbstractEventLoop–executor.
Statistics
dataclass
Summary statistics of the executor state.
These values feed monitoring endpoints and tests to provide visibility into how many jobs are running, finished, or awaiting pickup.
Attributes:
-
awaiting_pickup(int) –Total number of finished futures (completed + errored) that have not
-
completed(int) –Number of successfully completed futures awaiting pickup.
-
errored(int) –Number of futures that completed with an exception and await pickup.
-
running(int) –Number of futures currently executing (not yet completed).
-
total(int) –Number of active futures across all keys (running + awaiting pickup).
awaiting_pickup
instance-attribute
Total number of finished futures (completed + errored) that have not
yet been retrieved via result().
completed
instance-attribute
Number of successfully completed futures awaiting pickup.
errored
instance-attribute
Number of futures that completed with an exception and await pickup.
errored
Return a mapping of keys to stringified exceptions for errored jobs.
Returns:
-
dict[str, str]–A dict mapping the string form of each key to the corresponding
-
dict[str, str]–exception message of futures that completed with an error and have
-
dict[str, str]–not yet been picked up via
result().
result
result(key: Hashable) -> T | None
Retrieve the next finished result for a key.
If no job for the key exists, raises a KeyError. If jobs exist but none has completed yet, returns None. When the last active future for a key is consumed, the internal state for the key is cleaned up.
Parameters:
-
(keyHashable) –The key used when submitting the job(s).
Returns:
-
T | None–The completed result value or None if the job is still running.
Raises:
-
KeyError–If no job for the given key has been submitted.
shutdown
shutdown(wait: bool = False) -> None
Shut down the executor and stop the background event loop.
Parameters:
-
(waitbool, default:False) –If true, waits for all running futures to finish before returning. This is passed through to the underlying
ThreadPoolExecutor.shutdown().
statistics
statistics() -> Statistics
Compute executor statistics.
Returns:
-
Statistics–A
CheckExecutor.Statisticsinstance summarizing total, completed, -
Statistics–errored, running, and awaiting pickup futures.
submit
submit(
key: Hashable,
func: Callable[P, T | Awaitable[T]],
*args: P.args,
resubmit: bool = False,
**kwargs: P.kwargs,
) -> Future
Submit a function to run for a key, deduplicating concurrent work.
If another job with the same key is already running and resubmit is
false, this returns the existing future instead of starting a new one.
Coroutine functions are scheduled on the background asyncio loop.
Parameters:
-
(keyHashable) –The deduplication key. Only one active job per key is started unless
resubmit=Trueis given. -
(funcCallable[P, T | Awaitable[T]]) –The callable to execute. May be synchronous or a coroutine function.
-
(*argsP.args, default:()) –Positional arguments passed to the callable.
-
(resubmitbool, default:False) –When true, always schedules a new job even if one with the same key is already running.
-
(**kwargsP.kwargs, default:{}) –Keyword arguments passed to the callable.
Returns:
-
Future–A Future representing the running or already existing job.
globals
Global state for Watchpost and a proxy to the active application instance.
This module exposes current_app, a lightweight LocalProxy that resolves to
the running Watchpost instance. It uses a ContextVar, so access is bound to
the current async/task context rather than a process-wide global. This makes it
safe to use from request handlers, check execution, and any code that runs under
Watchpost.app_context().
Notes:
Watchpost.app_context()sets and resets the context variable around operations that need access to the active application. The ASGI integration also enters this context automatically for incoming requests.- Accessing
current_appoutside an active context raises aRuntimeErrorwith a helpful message. Ensure your code runs insideWatchpost.app_context()or via the ASGI app when usingcurrent_app.
hostname
Hostname resolution utilities and strategies.
Provides a small strategy protocol to compute the target hostname for a check
result, helpers to validate or coerce hostnames to RFC1123, and the
orchestration function resolve_hostname that applies precedence across result,
check, environment, and the Watchpost application.
Notes
Hostnames must follow RFC1123: ASCII letters, digits, and hyphens in dot-separated labels, each label 1-63 characters, total length up to 253 characters. Labels must start and end with an alphanumeric character.
Classes:
-
CoercingStrategy–Wraps another strategy and coerces its result to RFC1123 if present.
-
CompositeStrategy–Tries multiple strategies in order and returns the first non-empty result.
-
FunctionStrategy–Calls a function with the
HostnameContextto compute a hostname. -
HostnameContext–Carries context available when resolving a hostname for a check execution.
-
HostnameResolutionError–Raised when a hostname cannot be resolved or validated.
-
HostnameStrategy–Strategy protocol for resolving a hostname from a
HostnameContext. -
NoPiggybackHostStrategy–Explicitly disables the setting of a piggyback hostname. Whatever results a
-
StaticHostnameStrategy–Always returns the given hostname literal.
-
TemplateStrategy–Formats a string template using fields from the
HostnameContext.
Functions:
-
coerce_to_rfc1123–Normalize and coerce an arbitrary string into an RFC1123-compatible
-
is_rfc1123_hostname–Determine whether the given value is a valid RFC1123 hostname.
-
resolve_hostname–Resolve the final hostname for a check execution.
-
to_strategy–Convert user-facing hostname input into a
HostnameStrategy.
CoercingStrategy
CoercingStrategy(inner: HostnameStrategy)
Bases: HostnameStrategy
Wraps another strategy and coerces its result to RFC1123 if present.
If the inner strategy returns None, no coercion happens and None is
returned. If a non-empty hostname is returned, it is passed through
coerce_to_rfc1123.
Parameters:
-
(innerHostnameStrategy) –The inner strategy whose output should be coerced.
CompositeStrategy
CompositeStrategy(*strategies: HostnameStrategy)
Bases: HostnameStrategy
Tries multiple strategies in order and returns the first non-empty result.
Parameters:
-
(strategiesHostnameStrategy, default:()) –One or more strategies to evaluate in order.
FunctionStrategy
FunctionStrategy(
fn: Callable[
[HostnameContext], str | NoPiggybackHost | None
],
)
Bases: HostnameStrategy
Calls a function with the HostnameContext to compute a hostname.
Returning None indicates no decision and allows fallthrough to later
strategies.
Parameters:
-
(fnCallable[[HostnameContext], str | NoPiggybackHost | None]) –A callable that receives a
HostnameContextand returns a hostname orNone.
HostnameContext
dataclass
HostnameContext(
check: Check,
environment: Environment,
service_name: str,
service_labels: dict[str, Any],
result: CheckResult | None = None,
)
Carries context available when resolving a hostname for a check execution.
This object is passed to hostname strategies so they can decide on a hostname based on the check, environment, service information, and an optional result.
Methods:
-
new–Create a HostnameContext with sensible defaults from the given inputs.
Attributes:
-
check(Check) –The current check being executed.
-
environment(Environment) –The current environment of the execution.
-
result(CheckResult | None) –The optional result that the check returned. If present, it may include a
-
service_labels(dict[str, Any]) –Labels attached to the service. Useful for templating or custom strategies.
-
service_name(str) –The service name as defined by the check (
@check). Checkmk will use this
result
class-attribute
instance-attribute
result: CheckResult | None = None
The optional result that the check returned. If present, it may include a hostname override on the result which takes precedence during resolution.
service_labels
instance-attribute
Labels attached to the service. Useful for templating or custom strategies.
service_name
instance-attribute
The service name as defined by the check (@check). Checkmk will use this
name to identify the service.
new
classmethod
new(
*,
check: Check,
environment: Environment,
result: CheckResult | None = None,
service_name: str | None = None,
service_labels: dict[str, Any] | None = None,
) -> HostnameContext
Create a HostnameContext with sensible defaults from the given inputs.
Parameters:
-
(checkCheck) –The check for which a hostname is being resolved.
-
(environmentEnvironment) –The environment in which the check runs.
-
(resultCheckResult | None, default:None) –Optional result produced by the check. When given, used to support per-result hostname overrides.
-
(service_namestr | None, default:None) –Optional service name. Defaults to the check's service name.
-
(service_labelsdict[str, Any] | None, default:None) –Optional service labels. Defaults to the check's service labels.
Returns:
-
HostnameContext–A new HostnameContext initialized with the provided values and
-
HostnameContext–defaults.
HostnameResolutionError
Bases: Exception
Raised when a hostname cannot be resolved or validated.
This error wraps exceptions thrown by strategies and signals failure to produce a usable hostname for a check/environment combination.
HostnameStrategy
Bases: Protocol
Strategy protocol for resolving a hostname from a HostnameContext.
Implementations return a hostname string or None if they cannot decide.
Returning None allows composition where later strategies may provide a
hostname.
NoPiggybackHostStrategy
Bases: HostnameStrategy
Explicitly disables the setting of a piggyback hostname. Whatever results a check has created will be associated with the host the Watchpost application ran on.
Compared to simply providing an empty string, using this strategy will never
result in either a fallback hostname being generated or a
HostnameResolutionError to be raised.
StaticHostnameStrategy
StaticHostnameStrategy(hostname: str)
Bases: HostnameStrategy
Always returns the given hostname literal.
Parameters:
-
(hostnamestr) –The hostname to return for any context.
TemplateStrategy
TemplateStrategy(template: str)
Bases: HostnameStrategy
Formats a string template using fields from the HostnameContext.
The template is processed with str.format(**asdict(ctx)). You can access
context fields, including nested attributes on objects such as
{environment.name} or {check.service_name}.
Parameters:
-
(templatestr) –A format string for
str.formatusing keys from the context.
coerce_to_rfc1123
coerce_to_rfc1123(value: str | NoPiggybackHost) -> str
Normalize and coerce an arbitrary string into an RFC1123-compatible hostname.
The process lowercases the input, removes unsupported characters, replaces
invalid characters with hyphens, normalizes repeated separators, trims
leading/trailing hyphens from labels, and truncates labels and the overall
hostname to RFC1123 limits. If the value cannot be coerced into a valid
hostname, a ValueError is raised.
Parameters:
-
(valuestr | NoPiggybackHost) –The input string to coerce into a hostname.
Returns:
-
str–A string that complies with RFC1123 hostname rules.
Raises:
-
ValueError–If the input is empty or cannot be transformed into a valid hostname.
is_rfc1123_hostname
is_rfc1123_hostname(value: str) -> bool
Determine whether the given value is a valid RFC1123 hostname.
Parameters:
-
(valuestr) –The hostname candidate to validate.
Returns:
-
bool–True if the value conforms to RFC1123; otherwise, False.
Notes
Enforces ASCII letters, digits, and hyphens in dot-separated labels; each label is 1-63 characters and must start and end with an alphanumeric character. The full hostname must not exceed 253 characters.
resolve_hostname
resolve_hostname(
*,
watchpost: Watchpost,
check: Check,
environment: Environment,
result: CheckResult | None,
fallback_to_default_hostname_generation: bool = True,
coerce_into_valid_hostname: bool = True,
explicit_hostname: HostnameInput | None = None,
) -> str
Resolve the final hostname for a check execution.
Precedence:
- Explicit hostname (if present).
- Per-result override on the
CheckResult(if present). - Check-level strategy on the
Check. - Environment-level strategy on the
Environment. - Watchpost-level strategy on the application.
- Optional fallback to "{service_name}-{environment.name}" if enabled.
The resolved hostname must conform to RFC1123. If it does not and
coerce_into_valid_hostname is True, the hostname is coerced using
coerce_to_rfc1123. Otherwise, a HostnameResolutionError is raised.
Parameters:
-
(watchpostWatchpost) –The Watchpost application providing a default strategy.
-
(checkCheck) –The check for which a hostname is being resolved.
-
(environmentEnvironment) –The environment in which the check runs.
-
(resultCheckResult | None) –Optional result that may contain a per-result hostname override.
-
(fallback_to_default_hostname_generationbool, default:True) –Whether to fall back to "{service_name}-{environment.name}" when no strategy produced a hostname.
-
(coerce_into_valid_hostnamebool, default:True) –Whether to coerce a non-compliant hostname into RFC1123 format.
-
(explicit_hostnameHostnameInput | None, default:None) –An explicit hostname override, if any.
Returns:
-
str–The resolved hostname.
Raises:
-
HostnameResolutionError–If no hostname can be resolved, a strategy fails, or a non-compliant hostname cannot be coerced.
to_strategy
to_strategy(
value: HostnameInput | None,
) -> HostnameStrategy | None
Convert user-facing hostname input into a HostnameStrategy.
Accepts one of the following inputs:
- A string interpreted as a template for
TemplateStrategy. - A callable taking
HostnameContextand returning a hostname orNone. - An object implementing the
HostnameStrategyprotocol.
Parameters:
-
(valueHostnameInput | None) –The value to convert into a strategy, or
Noneto indicate no strategy.
Returns:
-
HostnameStrategy | None–A
HostnameStrategyinstance orNoneif the input wasNone.
Raises:
-
TypeError–If the input type is not supported.
http
Starlette HTTP routes for Watchpost.
This module exposes operational endpoints and the streaming root endpoint:
/healthcheckreturns 204 for liveness checks./executor/statisticsreturns executor statistics as JSON./executor/erroredreturns a list of errored checks as JSON./streams Checkmk-compatible output from running checks.
result
Result types and builders for Watchpost checks.
Classes:
-
CheckResult–Represents the result of a check performed on a system or component.
-
CheckState–Represents the state of a check.
-
ExecutionResult–This is an internal type that represents the final execution result of a
-
Metric–Represents a measurable metric with an optional threshold configuration.
-
OngoingCheckResult–An "ongoing check result" represents a builder that allows you to build up a
-
Thresholds–Represents threshold values with warning and critical levels.
Functions:
-
build_result–Start building up a new check result that allows adding multiple
-
crit–Generates a CheckResult object indicating a CRIT check state.
-
normalize_details–Normalize and format the given details into a string.
-
ok–Generates a CheckResult object indicating an OK check state.
-
unknown–Generates a CheckResult object indicating an UNKNOWN check state.
-
warn–Generates a CheckResult object indicating a WARN check state.
CheckResult
dataclass
CheckResult(
check_state: CheckState,
summary: str,
details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
hostname: HostnameInput | None = None,
)
Represents the result of a check performed on a system or component.
This class encapsulates the result of a check operation, providing details such as the state of the check, a summary, optional details, a name suffix, metrics, and hostname information. It is designed to store and convey the outcome of a check operation in a structured format.
Attributes:
-
check_state(CheckState) –The state of the check, indicating whether it was successful, warning,
-
details(str | None) –A detailed output of the check result, providing additional information
-
hostname(HostnameInput | None) –An optional hostname that overrides the hostname that would have been used
-
metrics(list[Metric] | None) –An optional list of metrics to associate with the check.
-
name_suffix(str | None) –A suffix to add to the check name as defined in the
@checkdecorator. -
summary(str) –A summary of the check result, indicating the outcome of the check.
check_state
instance-attribute
check_state: CheckState = check_state
The state of the check, indicating whether it was successful, warning, critical, or unknown.
details
class-attribute
instance-attribute
details: str | None = normalize_details(details)
A detailed output of the check result, providing additional information beyond the summary.
Checkmk will show this detailed output when you are viewing a specific service.
hostname
class-attribute
instance-attribute
An optional hostname that overrides the hostname that would have been used otherwise.
metrics
class-attribute
instance-attribute
metrics: list[Metric] | None = metrics
An optional list of metrics to associate with the check.
name_suffix
class-attribute
instance-attribute
A suffix to add to the check name as defined in the @check decorator.
This enables a single check function to return multiple results that create multiple services on the Checkmk side.
CheckState
Bases: Enum
Represents the state of a check.
This maps to the Checkmk concept of states exactly.
Attributes:
-
check_function(Callable[..., CheckResult]) –Determines the appropriate check function based on the current check
-
state_marker(str) –Returns a Checkmk output compatible state marker (such as
(!!)for
check_function
property
check_function: Callable[..., CheckResult]
Determines the appropriate check function based on the current check state.
This property evaluates the current CheckState of the instance and
matches it to a corresponding check function (ok, warn, crit, or
unknown).
Returns:
-
Callable[..., CheckResult]–The function corresponding to the current state of the check.
ExecutionResult
dataclass
ExecutionResult(
piggyback_host: str,
service_name: str,
service_labels: dict[str, str],
environment_name: str,
check_state: CheckState,
summary: str,
details: str | None = None,
metrics: list[Metric] | None = None,
check_definition: InvocationInformation | None = None,
)
This is an internal type that represents the final execution result of a check, containing everything required to turn it into Checkmk-compatible output.
Metric
dataclass
Metric(
name: str,
value: int | float,
levels: Thresholds | None = None,
boundaries: Thresholds | None = None,
)
Represents a measurable metric with an optional threshold configuration.
This maps to the Checkmk concept of metrics exactly.
OngoingCheckResult
OngoingCheckResult(
ok_summary: str,
fail_summary: str,
base_details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
alternative_hostname: HostnameInput | None = None,
)
An "ongoing check result" represents a builder that allows you to build up a new check result by adding multiple OK/WARN/UNKNOWN/CRIT results, called "partials", which will eventually result in a regular check result that holds the worst check state provided by the individual results.
Use of this builder greatly simplifies scenarios where your check function validates multiple aspects of a single system or component but only returns a single check result: by allowing you to provide the status of each aspect as you check it through simple function calls on the builder instead of having to manually combine the results into a single check result, you can reduce the complexity of your check function and improve its readability.
Constructing this builder is recommended through the top-level
build_result available in this module.
Classes:
-
Partial–The internal type representing a partial result of a check.
Methods:
-
add_check_result–Add a check result to the builder as a partial result.
-
crit–Add a CRIT result to the builder as a partial result.
-
ok–Add an OK result to the builder as a partial result.
-
to_check_result–Finalize this builder by turning it into a check result.
-
unknown–Add an UNKNOWN result to the builder as a partial result.
-
warn–Add a WARN result to the builder as a partial result.
Attributes:
-
check_state(CheckState) –The overall check state of the builder, calculated based on the worst
check_state
property
check_state: CheckState
The overall check state of the builder, calculated based on the worst check state of the individual results.
Partial
dataclass
Partial(
check_state: CheckState,
summary: str,
details: Details | None,
)
The internal type representing a partial result of a check.
add_check_result
add_check_result(check_result: CheckResult) -> None
Add a check result to the builder as a partial result.
For most use cases you probably want to use the higher-level ok,
warn, crit, and unknown functions instead.
Parameters:
-
(check_resultCheckResult) –The check result to add as a partial result.
crit
Add a CRIT result to the builder as a partial result.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
ok
Add an OK result to the builder as a partial result.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
to_check_result
to_check_result() -> CheckResult
Finalize this builder by turning it into a check result.
The created result holds the cumulative data of all partial results, with the worst check state as determined by the check state of the individual results.
unknown
Add an UNKNOWN result to the builder as a partial result.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
warn
Add a WARN result to the builder as a partial result.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
Thresholds
dataclass
Represents threshold values with warning and critical levels.
This maps to the Checkmk concept of thresholds exactly and thus directly
relates to metrics, see the Metric class.
build_result
build_result(
ok_summary: str,
fail_summary: str,
base_details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
alternative_hostname: HostnameInput | None = None,
) -> OngoingCheckResult
Start building up a new check result that allows adding multiple OK/WARN/UNKNOWN/CRIT results, called "partials", eventually resulting in a regular check result that holds the worst check state provided by the individual results.
Use of this builder greatly simplifies scenarios where your check function validates multiple aspects of a single system or component but only returns a single check result: by allowing you to provide the status of each aspect as you check it through simple function calls on the builder instead of having to manually combine the results into a single check result, you can reduce the complexity of your check function and improve its readability.
Parameters:
-
(ok_summarystr) –Overall check summary that will be shown if the final result is OK.
-
(fail_summarystr) –Overall check summary that will be shown if the final result is WARN, UNKNOWN, or CRIT.
-
(base_detailsDetails | None, default:None) –Optional base details for the check result. They will always be included and then enriched by the details provided by partial results.
-
(name_suffixstr | None, default:None) –Optional suffix for the check result name.
-
(metricslist[Metric] | None, default:None) –Optional list of metrics associated with the check.
-
(alternative_hostnameHostnameInput | None, default:None) –Optional alternative hostname input for the check.
Returns:
-
OngoingCheckResult–An instance of OngoingCheckResult initialized with the provided
-
OngoingCheckResult–parameters and ready to receive partial results.
crit
crit(
summary: str,
details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
alternative_hostname: HostnameInput | None = None,
) -> CheckResult
Generates a CheckResult object indicating a CRIT check state.
This function creates and returns a CheckResult indicating the system or component is in a CRIT state. It allows for passing additional information such as a summary, details, name suffix, metrics, or an alternative hostname.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
-
(name_suffixstr | None, default:None) –A suffix to add to the check name as defined in the
@checkdecorator. This enables a single check function to return multiple results that create multiple services on the Checkmk side. -
(metricslist[Metric] | None, default:None) –An optional list of metrics to associate with the check.
-
(alternative_hostnameHostnameInput | None, default:None) –An optional hostname that overrides the hostname that would have been used otherwise.
Returns:
-
CheckResult–A
CheckResultobject representing the CRIT check result.
normalize_details
normalize_details(details: Details | None) -> str | None
Normalize and format the given details into a string.
This function processes the input details parameter and normalizes it into
a string representation based on its type. If the input is None, it
returns None. For Exception objects, it extracts and formats the
exception details. For dictionaries, it formats each key-value pair as a
newline-separated string. Empty strings are normalized to None. Other
string inputs are returned unchanged.
Parameters:
-
(detailsDetails | None) –The input details to normalize. It can be of type
Details(e.g., exception, string, dictionary), orNone.
Returns:
-
str | None–A formatted string representation of the input details, or
Noneif the -
str | None–input is
Noneor an empty string.
ok
ok(
summary: str,
details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
alternative_hostname: HostnameInput | None = None,
) -> CheckResult
Generates a CheckResult object indicating an OK check state.
This function creates and returns a CheckResult indicating the system or component is in an OK state. It allows for passing additional information such as a summary, details, name suffix, metrics, or an alternative hostname.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
-
(name_suffixstr | None, default:None) –A suffix to add to the check name as defined in the
@checkdecorator. This enables a single check function to return multiple results that create multiple services on the Checkmk side. -
(metricslist[Metric] | None, default:None) –An optional list of metrics to associate with the check.
-
(alternative_hostnameHostnameInput | None, default:None) –An optional hostname that overrides the hostname that would have been used otherwise.
Returns:
-
CheckResult–A
CheckResultobject representing the OK check result.
unknown
unknown(
summary: str,
details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
alternative_hostname: HostnameInput | None = None,
) -> CheckResult
Generates a CheckResult object indicating an UNKNOWN check state.
This function creates and returns a CheckResult indicating the system or component is in an UNKNOWN state. It allows for passing additional information such as a summary, details, name suffix, metrics, or an alternative hostname.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
-
(name_suffixstr | None, default:None) –A suffix to add to the check name as defined in the
@checkdecorator. This enables a single check function to return multiple results that create multiple services on the Checkmk side. -
(metricslist[Metric] | None, default:None) –An optional list of metrics to associate with the check.
-
(alternative_hostnameHostnameInput | None, default:None) –An optional hostname that overrides the hostname that would have been used otherwise.
Returns:
-
CheckResult–A
CheckResultobject representing the UNKNOWN check result.
warn
warn(
summary: str,
details: Details | None = None,
name_suffix: str | None = None,
metrics: list[Metric] | None = None,
alternative_hostname: HostnameInput | None = None,
) -> CheckResult
Generates a CheckResult object indicating a WARN check state.
This function creates and returns a CheckResult indicating the system or component is in a WARN state. It allows for passing additional information such as a summary, details, name suffix, metrics, or an alternative hostname.
Parameters:
-
(summarystr) –A summary of the check result, indicating the outcome of the check. Checkmk will show this summary on pages like a host overview.
-
(detailsDetails | None, default:None) –A detailed output of the check result, providing additional information beyond the summary. Checkmk will show this detailed output when you are viewing a specific service.
-
(name_suffixstr | None, default:None) –A suffix to add to the check name as defined in the
@checkdecorator. This enables a single check function to return multiple results that create multiple services on the Checkmk side. -
(metricslist[Metric] | None, default:None) –An optional list of metrics to associate with the check.
-
(alternative_hostnameHostnameInput | None, default:None) –An optional hostname that overrides the hostname that would have been used otherwise.
Returns:
-
CheckResult–A
CheckResultobject representing the WARN check result.
scheduling_strategy
Scheduling strategies and validation.
Defines how Watchpost decides whether a check should run from the current execution environment against a target environment. Strategies encapsulate constraints (where a check must execute from, which targets it may run against, or that current and target must match) and combine into a single scheduling decision.
Main concepts:
- SchedulingStrategy: Protocol implemented by concrete strategies.
- SchedulingDecision: Outcome used by the executor (SCHEDULE, SKIP, DONT_SCHEDULE).
- DetectImpossibleCombinationStrategy: Validation strategy that detects and
raises
InvalidCheckConfigurationwhen multiple strategies are mutually incompatible, so a check could never be scheduled.
Notes:
- These rules affect what Checkmk will eventually see: if a check is never scheduled in a given environment, no service is reported from that node.
- "Current == Target" refers to running a check from the same environment that it targets (common for in-cluster checks). When this is required, the allowed execution environments and allowed target environments must overlap; otherwise the configuration is impossible.
Example:
from watchpost.environment import Environment from watchpost.datasource import Datasource from watchpost.scheduling_strategy import ( ... MustRunInGivenExecutionEnvironmentStrategy, ... MustRunAgainstGivenTargetEnvironmentStrategy, ... )
Monitoring = Environment("Monitoring") Preprod = Environment("Preprod")
class LogSystem(Datasource): ... # Run from Monitoring, but may target Monitoring or Preprod ... scheduling_strategies = ( ... MustRunInGivenExecutionEnvironmentStrategy(Monitoring), ... MustRunAgainstGivenTargetEnvironmentStrategy(Monitoring, Preprod), ... )
The Watchpost app collects the strategies required by involved datasources and applies them to each check to derive the final scheduling decision.
Classes:
-
DetectImpossibleCombinationStrategy–Detect mutually incompatible scheduling constraints and raise an error.
-
InvalidCheckConfiguration–Should be raised when a check's configuration is contradictory or otherwise
-
MustRunAgainstGivenTargetEnvironmentStrategy–Restrict which target environments the check may run against.
-
MustRunInGivenExecutionEnvironmentStrategy–Require that the check executes from one of the given execution
-
MustRunInTargetEnvironmentStrategy–Require that the current execution environment equals the target
-
SchedulingDecision–Scheduling decision returned by a SchedulingStrategy.
-
SchedulingStrategy–Protocol for pluggable scheduling logic.
DetectImpossibleCombinationStrategy
Bases: SchedulingStrategy
Detect mutually incompatible scheduling constraints and raise an error.
This strategy does not itself restrict scheduling. Instead, it validates the
active strategies for a check and raises InvalidCheckConfiguration when
constraints cannot be satisfied together.
Examples:
- Conflicting required execution environments with no overlap (for example, one datasource requires "Monitoring" while another requires "Preprod").
- Allowed target environments that do not include all environments declared
in the
@checkdecorator. - A "current == target" requirement while the allowed execution and target sets do not overlap, so the check can never run.
InvalidCheckConfiguration
InvalidCheckConfiguration(
check: Check,
reason: str,
cause: Exception | None = None,
)
Bases: Exception
Should be raised when a check's configuration is contradictory or otherwise invalid and cannot be scheduled anywhere until corrected.
This can happen if, for example, two datasources with conflicting scheduling requirements are used in a single check.
MustRunAgainstGivenTargetEnvironmentStrategy
MustRunAgainstGivenTargetEnvironmentStrategy(
*environments: Environment,
)
Bases: SchedulingStrategy
Restrict which target environments the check may run against.
Use this to allow only specific targets (for example, only "stage"). If the requested target is not in the allowed set, the decision is DONT_SCHEDULE.
This strategy does not affect from where the check executes, i.e. the execution environment.
One or more target environments that the check may run against.
MustRunInGivenExecutionEnvironmentStrategy
MustRunInGivenExecutionEnvironmentStrategy(
*environments: Environment,
)
Bases: SchedulingStrategy
Require that the check executes from one of the given execution environments.
Use this when a datasource or check can only run from specific locations (for example, from a monitoring environment). If the current execution environment is not in the allowed set, the decision is DONT_SCHEDULE.
One or more execution environments from which the check may run.
MustRunInTargetEnvironmentStrategy
Bases: SchedulingStrategy
Require that the current execution environment equals the target environment.
This models "run in-environment" behavior where the check must execute inside the environment it is checking. If current != target, the decision is DONT_SCHEDULE.
SchedulingDecision
Bases: IntEnum
Scheduling decision returned by a SchedulingStrategy.
The value communicates what the executor should do with a given check in the current situation. Use this to express whether a check should be run now, temporarily skipped (reusing a previously cached result if available), or never be scheduled on this node.
If you determine that the check's configuration is invalid and can never be
scheduled until fixed, raise InvalidCheckConfiguration instead!
Notes on semantics: - SCHEDULE: The check is eligible to run now. - SKIP: Conditions are temporarily unfavorable; the last known result will be reused if available. The strategy expects that conditions might change later (e.g., outside a maintenance window, or when a datasource becomes reachable again). If no cached result is available, the check will be marked as UNKNOWN. - DONT_SCHEDULE: This node/environment should never run the check (e.g., the check is pinned to another environment). Different from SKIP in that this is a permanent decision for the current environment, not reporting on the check at all.
Attributes:
-
DONT_SCHEDULE–The check should not run at all.
-
SCHEDULE–The check is eligible to run now.
-
SKIP–The check should be skipped temporarily and any prior results, if available,
DONT_SCHEDULE
class-attribute
instance-attribute
The check should not run at all.
This node/environment should never run the check (e.g., the check is pinned to another environment). Different from SKIP in that this is a permanent decision for the current environment, not reporting on the check at all.
This primarily applies for checks that have to run from a certain environment, and the current environment is not suitable.
SKIP
class-attribute
instance-attribute
The check should be skipped temporarily and any prior results, if available, should be reused.
This usually means that the conditions are temporarily unfavorable; the last known result will be reused if available. The strategy expects that conditions might change later (e.g., outside a maintenance window, or when a datasource becomes reachable again). If no cached result is available, the check will be marked as UNKNOWN.
SchedulingStrategy
Bases: Protocol
Protocol for pluggable scheduling logic.
A scheduling strategy decides if and how a check should be executed in the current context. Implementations can consider the check definition, the environment that is attempting to execute the check (current execution environment), and the target environment the check is meant to observe.
Typical concerns handled by a strategy include: - Aligning check execution with datasource availability windows - Respecting environment pinning (e.g., only run from a specific location) - Handling temporary outages by skipping while reusing previous results - Detecting invalid configurations that can never be scheduled
Methods:
-
schedule–Decide whether and how the given check should be executed.
schedule
schedule(
check: Check,
current_execution_environment: Environment,
target_environment: Environment,
) -> SchedulingDecision
Decide whether and how the given check should be executed.
Parameters:
-
(checkCheck) –The check definition whose execution is being considered.
-
(current_execution_environmentEnvironment) –The environment that the check would execute within.
-
(target_environmentEnvironment) –The environment that the check is intended to observe or act upon.
Returns:
-
SchedulingDecision–A SchedulingDecision indicating whether to run the check now
-
SchedulingDecision–(SCHEDULE), skip temporarily and possibly reuse previous results
-
SchedulingDecision–(SKIP), or avoid running it from this environment entirely
-
SchedulingDecision–(DONT_SCHEDULE).
Raises:
-
InvalidCheckConfiguration–The check's configuration is contradictory or otherwise invalid and cannot be scheduled anywhere until corrected.
utils
Utility helpers for Watchpost.
Classes:
-
InvocationInformation–Call-site information for an invocation.
Functions:
-
get_invocation_information–Return call-site information for the caller's caller.
-
normalize_to_timedelta–Normalize a value to a datetime.timedelta.
InvocationInformation
dataclass
Call-site information for an invocation.
Holds the relative path of the module and the line number where the invocation occurred.
get_invocation_information
get_invocation_information() -> (
InvocationInformation | None
)
Return call-site information for the caller's caller.
Inspects the call stack to locate the module and line number of the function that invoked the caller. The module path is made relative to the project root inferred from the watchpost package. If any information cannot be determined, returns None.
Returns:
-
InvocationInformation | None–InvocationInformation with the relative path and line number, or None if
-
InvocationInformation | None–it cannot be determined.
normalize_to_timedelta
normalize_to_timedelta(
value: timedelta | str | None,
) -> timedelta | None
Normalize a value to a datetime.timedelta.
- If value is None, return None.
- If value is already a timedelta, return it unchanged.
- If value is a string, parse it with timelength (e.g., "5m", "2h30m") and return the corresponding timedelta.
Parameters:
-
(valuetimedelta | str | None) –A timedelta, a string time expression, or None.
Returns:
-
timedelta | None–A timedelta corresponding to the input, or None.
vendored
Modules:
local_proxy
Classes:
-
LocalProxy–A proxy to the object bound to a context-local object. All
LocalProxy
LocalProxy(
local: ContextVar[T] | Callable[[], T],
name: str | None = None,
*,
unbound_message: str | None = None,
)
A proxy to the object bound to a context-local object. All
operations on the proxy are forwarded to the bound object. If no
object is bound, a RuntimeError is raised.
:param local: The context-local object that provides the proxied object. :param name: Proxy this attribute from the proxied object. :param unbound_message: The error message to show if the context-local object is unbound.
Proxy a :class:~contextvars.ContextVar to make it easier to
access. Pass a name to proxy that attribute.
.. code-block:: python
_request_var = ContextVar("request")
request = LocalProxy(_request_var)
session = LocalProxy(_request_var, "session")
Proxy an attribute on a :class:Local namespace by calling the
local with the attribute name:
.. code-block:: python
data = Local()
user = data("user")
Proxy the top item on a :class:LocalStack by calling the local.
Pass a name to proxy that attribute.
.. code-block::
app_stack = LocalStack()
current_app = app_stack()
g = app_stack("g")
Pass a function to proxy the return value from that function. This was previously used to access attributes of local objects before that was supported directly.
.. code-block:: python
session = LocalProxy(lambda: request.session)
__repr__ and __class__ are proxied, so repr(x) and
isinstance(x, cls) will look like the proxied object. Use
issubclass(type(x), LocalProxy) to check if an object is a
proxy.
.. code-block:: python
repr(user) # <User admin>
isinstance(user, User) # True
issubclass(type(user), LocalProxy) # True
.. versionchanged:: 2.2.2
__wrapped__ is set when wrapping an object, not only when
wrapping a function, to prevent doctest from failing.
.. versionchanged:: 2.2
Can proxy a ContextVar or LocalStack directly.
.. versionchanged:: 2.2
The name parameter can be used with any proxied object, not
only Local.
.. versionchanged:: 2.2
Added the unbound_message parameter.
.. versionchanged:: 2.0 Updated proxied attributes and methods to reflect the current data model.
.. versionchanged:: 0.6.1 The class can be instantiated with a callable.