nadzoring.dns_lookup.monitor module

Continuous DNS server health and performance monitoring.

class nadzoring.dns_lookup.monitor.AlertEvent(server: str, alert_type: str, message: str, value: float | None, threshold: float | None, timestamp: datetime = <factory>)[source]

Bases: object

A threshold breach detected during a monitoring cycle.

Variables:
  • server (str) – IP address or domain of the offending target.

  • alert_type (str) – One of "resolution_failure", "high_latency", "low_success_rate", or "health_degraded".

  • message (str) – Human-readable description of the breach.

  • value (float | None) – Measured value that triggered the alert, or None.

  • threshold (float | None) – Configured threshold that was breached, or None.

  • timestamp (datetime.datetime) – UTC time the alert was raised.

__init__(server: str, alert_type: str, message: str, value: float | None, threshold: float | None, timestamp: datetime = <factory>) → None[source]
alert_type: str
message: str
server: str
threshold: float | None
timestamp: datetime
to_dict() → dict[str, Any][source]

Serialise to a JSON-compatible dictionary.

Returns:

Dictionary representation of this alert.

value: float | None
class nadzoring.dns_lookup.monitor.CycleResult(cycle: int, timestamp: ~datetime.datetime, domain: str, samples: list[~nadzoring.dns_lookup.monitor.ServerSample], health_score: int | None = None, health_status: str | None = None, alerts: list[~nadzoring.dns_lookup.monitor.AlertEvent] = <factory>)[source]

Bases: object

Aggregated result of one monitoring cycle.

Variables:
  • cycle (int) – 1-based cycle counter.

  • timestamp (datetime.datetime) – UTC timestamp when the cycle started.

  • domain (str) – Domain that was queried.

  • samples (list[nadzoring.dns_lookup.monitor.ServerSample]) – Per-server performance samples.

  • health_score (int | None) – DNS health score 0-100, or None when disabled.

  • health_status (str | None) – One of "healthy", "degraded", "unhealthy", or None.

  • alerts (list[nadzoring.dns_lookup.monitor.AlertEvent]) – Alert events raised during this cycle.

__init__(cycle: int, timestamp: ~datetime.datetime, domain: str, samples: list[~nadzoring.dns_lookup.monitor.ServerSample], health_score: int | None = None, health_status: str | None = None, alerts: list[~nadzoring.dns_lookup.monitor.AlertEvent] = <factory>) → None[source]
alerts: list[AlertEvent]
cycle: int
domain: str
health_score: int | None = None
health_status: str | None = None
samples: list[ServerSample]
timestamp: datetime
to_dict() → dict[str, Any][source]

Serialise to a JSON-compatible dictionary.

Returns:

Dictionary representation of this cycle result.

class nadzoring.dns_lookup.monitor.DNSMonitor(config: MonitorConfig)[source]

Bases: object

Continuously monitor DNS servers for health and performance.

Each cycle benchmarks every configured server, optionally runs a full health check, evaluates thresholds, dispatches alerts, and persists the result to a JSONL log file.

SIGINT and SIGTERM are handled gracefully: the loop finishes the current cycle, then stops.

Parameters:

config – Monitoring configuration.

Example

>>> config = MonitorConfig(
...     domain="example.com",
...     nameservers=["8.8.8.8", "1.1.1.1"],
...     interval=60.0,
...     log_file="dns_monitor.jsonl",
... )
>>> monitor = DNSMonitor(config)
>>> monitor.run()
__init__(config: MonitorConfig) → None[source]

Initialize a DNSMonitor.

Parameters:

config (MonitorConfig) – dns monitoring configuration

_append_log(result: CycleResult) → None[source]
_build_cycle_result() → CycleResult[source]
_dispatch_alerts(alerts: list[AlertEvent]) → None[source]
_handle_signal(_signum: int, _frame: object) → None[source]
_history: deque[CycleResult]
_interruptible_sleep(seconds: float) → None[source]
_log_path: Path | None
_print_summary(result: CycleResult) → None[source]
_run_health_check() → tuple[int | None, str | None][source]
_sample_server(server: str, ts: datetime) → ServerSample[source]
_server_report_lines(server: str) → list[str][source]
_tick() → None[source]
history() → list[CycleResult][source]

Return a snapshot of the in-memory monitoring history.

Returns:

List of CycleResult objects, oldest first.

report() → str[source]

Return a human-readable session summary.

Computes per-server mean, stdev, min, and max response times, overall success rates, and health score trends across the full in-memory history.

Returns:

Multi-line string for printing or logging.

Example

>>> monitor.run_cycles(5)
>>> print(monitor.report())
run() → None[source]

Start the blocking monitoring loop.

Runs until stop() is called or the process receives SIGINT / SIGTERM.

run_cycles(count: int) → list[CycleResult][source]

Run a fixed number of cycles and return the results.

Useful for CI pipelines, tests, and cron-based scheduling where the caller controls the loop.

Parameters:

count – Number of cycles to execute.

Returns:

List of CycleResult objects, one per executed cycle.

Example

>>> results = monitor.run_cycles(10)
>>> print(len(results))
10
stop() → None[source]

Signal the monitoring loop to stop after the current cycle.

class nadzoring.dns_lookup.monitor.MonitorConfig(domain: str = 'google.com', nameservers: list[str] = <factory>, record_type: ~nadzoring.dns_lookup.types.RecordType = 'A', interval: float = 60.0, queries_per_sample: int = 3, max_response_time_ms: float = 500.0, min_success_rate: float = 0.95, run_health_check: bool = True, max_history: int = 1440, log_file: str | None = None, alert_callback: ~collections.abc.Callable[[~nadzoring.dns_lookup.monitor.AlertEvent], None] | None = None, timeout_config: ~nadzoring.utils.timeout.TimeoutConfig = <factory>)[source]

Bases: object

Configuration for a DNSMonitor instance.

Variables:
  • domain (str) – Domain name to query on every check cycle.

  • nameservers (list[str]) – DNS server IPs to monitor.

  • record_type (nadzoring.dns_lookup.types.RecordType) – DNS record type to query.

  • interval (float) – Seconds between successive check cycles.

  • queries_per_sample (int) – Queries sent to each server per cycle.

  • max_response_time_ms (float) – Alert threshold for average response time in milliseconds.

  • min_success_rate (float) – Alert threshold for success rate (0.0-1.0).

  • run_health_check (bool) – Whether to run a full health check each cycle. Set to False for high-frequency monitoring.

  • max_history (int) – Maximum cycle results kept in memory.

  • log_file (str | None) – Path to a JSONL file where results are appended. None disables file logging.

  • alert_callback (collections.abc.Callable[[nadzoring.dns_lookup.monitor.AlertEvent], None] | None) – Callable invoked with an AlertEvent on every threshold breach.

  • timeout_config (nadzoring.utils.timeout.TimeoutConfig) – Unified timeout configuration.

Example

>>> config = MonitorConfig(
...     domain="example.com",
...     nameservers=["8.8.8.8", "1.1.1.1"],
...     interval=30.0,
...     max_response_time_ms=200.0,
...     log_file="dns_monitor.jsonl",
... )
__init__(domain: str = 'google.com', nameservers: list[str] = <factory>, record_type: ~nadzoring.dns_lookup.types.RecordType = 'A', interval: float = 60.0, queries_per_sample: int = 3, max_response_time_ms: float = 500.0, min_success_rate: float = 0.95, run_health_check: bool = True, max_history: int = 1440, log_file: str | None = None, alert_callback: ~collections.abc.Callable[[~nadzoring.dns_lookup.monitor.AlertEvent], None] | None = None, timeout_config: ~nadzoring.utils.timeout.TimeoutConfig = <factory>) → None[source]
alert_callback: Callable[[AlertEvent], None] | None = None
domain: str = 'google.com'
interval: float = 60.0
log_file: str | None = None
max_history: int = 1440
max_response_time_ms: float = 500.0
min_success_rate: float = 0.95
nameservers: list[str]
queries_per_sample: int = 3
record_type: RecordType = 'A'
run_health_check: bool = True
timeout_config: TimeoutConfig
class nadzoring.dns_lookup.monitor.ServerSample(server: str, timestamp: datetime, avg_response_time_ms: float | None, min_response_time_ms: float | None, max_response_time_ms: float | None, success_rate: float, records: list[str], error: str | None = None)[source]

Bases: object

A single performance sample for one DNS server.

Variables:
  • server (str) – IP address of the queried DNS server.

  • timestamp (datetime.datetime) – UTC timestamp of the measurement.

  • avg_response_time_ms (float | None) – Average response time in milliseconds, or None when all queries failed.

  • min_response_time_ms (float | None) – Minimum observed response time, or None.

  • max_response_time_ms (float | None) – Maximum observed response time, or None.

  • success_rate (float) – Fraction of successful queries (0.0-1.0).

  • records (list[str]) – DNS records returned by the server.

  • error (str | None) – Last error message, or None on success.

__init__(server: str, timestamp: datetime, avg_response_time_ms: float | None, min_response_time_ms: float | None, max_response_time_ms: float | None, success_rate: float, records: list[str], error: str | None = None) → None[source]
avg_response_time_ms: float | None
error: str | None = None
max_response_time_ms: float | None
min_response_time_ms: float | None
records: list[str]
server: str
success_rate: float
timestamp: datetime
to_dict() → dict[str, Any][source]

Serialise to a JSON-compatible dictionary.

Returns:

Dictionary representation of this sample.

nadzoring.dns_lookup.monitor.evaluate_thresholds(samples: list[ServerSample], health_score: int | None, health_status: str | None, config: MonitorConfig) → list[AlertEvent][source]

Evaluate samples against configured thresholds.

Parameters:
  • samples – Per-server samples from the current cycle.

  • health_score – DNS health score 0-100, or None.

  • health_status – Health status string, or None.

  • config – Monitor configuration holding the threshold values.

Returns:

List of AlertEvent objects; empty when all metrics are within configured thresholds.

nadzoring.dns_lookup.monitor.load_log(path: str | Path) → list[dict[str, Any]][source]

Load a JSONL monitoring log written by DNSMonitor.

Parameters:

path – Path to the .jsonl file.

Returns:

List of cycle-result dictionaries, one per non-empty line.

Raises:

FileNotFoundError – If path does not exist.

Example

>>> cycles = load_log("dns_monitor.jsonl")
>>> rts = [
...     s["avg_response_time_ms"] for c in cycles for s in c["samples"] if s["avg_response_time_ms"] is not None
... ]
>>> print(f"Mean RT: {sum(rts) / len(rts):.2f}ms")