A greenhouse, end to end¶
This example puts four DAGs together. Devices in two greenhouse zones write readings to files. The first DAG stores them and raises alarms for hot devices. A second diagnoses each alarm and waits for an operator. An acknowledgement starts maintenance; an unanswered alarm pages the operator. A fourth DAG rolls up the readings by zone.
The shared models, SQLite connection and pager are in examples/showcase/dags/greenhouse.py.
The files and database live under /tmp/schedr-greenhouse. The example uses local
files and SQLite, so run its tasks on the same machine, as the standalone below does.
Run it¶
In one terminal, start the standalone with the showcase’s DAG root:
make standalone DAGS=examples/showcase/dags
make standalone alone loads examples/, not the showcase: examples/.schedrignore keeps
showcase/ out of that root. In another terminal, run:
make showcase
Once all four DAGs appear in the UI, this command unpauses them and starts the simulator and
a pager receiver. Open the UI at http://localhost:8080 and watch the runs and their graphs.
The simulator writes three rounds of readings, including a corrupt file and two hot devices.
It posts an acknowledgement for dev-a1 one minute after the last round and leaves dev-b2
unanswered. It does not check that the alarm run has started first; if ingestion is delayed,
post another ack after that run starts. Watch the maintenance run for the first and the
timeout for the second. To acknowledge by hand, run schedr events post ack --key dev-a1 --data '{"by":"ana","action":"recalibrate"}'. The receiver prints pager requests in the
second terminal. The rollup runs every five minutes. Ctrl-C stops the simulator; stop the
standalone separately with Ctrl-C.
Ingest readings¶
"""Batches of device files: each checked, stored or quarantined, then scanned for anomalies.
A poke trigger looks at the inbox every five seconds and gathers what came within thirty into
one run. Each file gets its own `validate`; a file that parses goes on to `store` in its lane, a
corrupt one to `quarantine`, and one bad file stops nothing else. `detect` runs under a hard
memory cap and posts an `anomaly` event for each device that ran hot: `anomaly_response` starts
a run per device from it.
"""
import asyncio
import json
import os
import shutil
import tempfile
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
from pathlib import Path
from typing import cast
from greenhouse import (
INBOX,
Anomaly,
Corrupt,
Reading,
Readings,
pager,
readings_db,
zone_of,
)
from schedr import Dag, Data, Event, Notify, api, dag_ctx, resource, task, trigger
class Arrived(Data, frozen=True):
"""A file found in the inbox."""
path: str
@dataclass
class IngestParams:
"""A run's thresholds; an event run uses the defaults."""
hot_celsius: float = 32.0
def _new_names(after: str | None) -> list[str]:
INBOX.mkdir(parents=True, exist_ok=True)
return sorted(
n for n in os.listdir(INBOX) if n.endswith(".jsonl") and (after is None or n > after)
)
@trigger.poke(every=timedelta(seconds=5), batch=timedelta(seconds=30))
async def inbox_files(after: str | None) -> list[Event[Arrived]]:
"""The files not seen yet. Their names start with a timestamp, so later ones sort after."""
names = await asyncio.to_thread(_new_names, after)
return [Event(name, Arrived(str(INBOX / name))) for name in names]
@task
def paths(batch: list[Event[Arrived]]) -> list[str]:
"""The batch's files, for one `validate` each."""
return [item.data.path for item in batch]
@resource
def workspace() -> str:
"""A scratch folder for the run's parsing, removed by the cleanup however the run ends."""
return tempfile.mkdtemp(prefix=f"greenhouse-{dag_ctx.run.id}-")
@workspace.cleanup(retries=2)
def remove_workspace(path: str) -> None:
shutil.rmtree(path, ignore_errors=True)
print(f"removed {path}")
def _reading(line: str) -> Reading:
"""One line, its fields checked: a `ValueError` or `TypeError` for a bad one."""
fields = cast("dict[str, object]", json.loads(line))
device, at, celsius, humidity = (fields[k] for k in ("device", "at", "celsius", "humidity"))
if not (isinstance(device, str) and isinstance(at, str)):
raise TypeError(f"device and at must be strings: {line!r}")
if not (isinstance(celsius, (int, float)) and isinstance(humidity, (int, float))):
raise TypeError(f"celsius and humidity must be numbers: {line!r}")
datetime.fromisoformat(at)
return Reading(device, at, float(celsius), float(humidity))
@task
def validate(work: str, path: str) -> Readings | Corrupt:
"""Parses one file into the workspace first, so a half-read file is never stored."""
copy = Path(work) / Path(path).name
try:
shutil.copyfile(path, copy)
lines = copy.read_text().splitlines()
readings = [_reading(line) for line in lines if line.strip()]
except (OSError, KeyError, ValueError, TypeError) as error:
return Corrupt(path, f"{type(error).__name__}: {error}")
if not readings:
return Corrupt(path, "no readings")
return Readings(path, readings)
@task(connections=[readings_db])
def store(batch: Readings) -> int:
"""Writes one file's readings; a file sent again changes nothing (its rows are keyed)."""
with readings_db() as db:
db.executemany(
"insert or ignore into readings values (?, ?, ?, ?, ?)",
[(r.device, zone_of(r.device), r.at, r.celsius, r.humidity) for r in batch.readings],
)
Path(batch.path).unlink(missing_ok=True)
return len(batch.readings)
@task
def quarantine(bad: Corrupt) -> str:
"""Moves a corrupt file aside, with why next to it."""
folder = Path(bad.path).parent.parent / "quarantine" # beside the inbox it came from
folder.mkdir(parents=True, exist_ok=True)
target = folder / Path(bad.path).name
if Path(bad.path).exists():
shutil.move(bad.path, target)
target.with_suffix(".why").write_text(bad.reason + "\n")
print(f"quarantined {target.name}: {bad.reason}")
return str(target)
# A hard cap: past 256 MiB the task's allocations fail and it fails, instead of the worker
# killing it, or another task, when its pod runs short.
@task(memory="256MiB", hard_memory_limit=True)
def detect(parsed: list[Readings | Corrupt], hot_celsius: float) -> list[Anomaly]:
"""The hottest reading of each device over the threshold, one event per device."""
hottest: dict[str, Reading] = {}
for result in parsed:
if isinstance(result, Readings):
for r in result.readings:
if r.celsius > hot_celsius and (
r.device not in hottest or r.celsius > hottest[r.device].celsius
):
hottest[r.device] = r
found = [Anomaly(r.device, r.celsius, r.at) for r in hottest.values()]
for anomaly in found:
# Keyed by device and time: a trigger starts one run per key ever, so the device's next
# alarm needs a key of its own; posted again (a retry), it is the same event.
key = f"{anomaly.device}@{anomaly.at}"
api.post_event(
"anomaly",
key=key,
data={"device": anomaly.device, "celsius": anomaly.celsius, "at": anomaly.at},
idempotency_key=key,
)
return found
@task
def summary(
stored: Sequence[int | None] | None,
quarantined: Sequence[str | None] | None,
found: list[Anomaly],
) -> str:
"""One line on the batch.
In a lane, `store` or `quarantine` was skipped (`None`); a whole mapped task is `None` when
no file took its way (a batch of only good files).
"""
text = (
f"{sum(n for n in stored or [] if n is not None)} readings stored, "
f"{sum(q is not None for q in quarantined or [])} files quarantined, "
f"{len(found)} anomalies"
)
print(text)
return text
with Dag(
"readings_ingest",
description="Checks batches of device files, stores or quarantines them, then finds anomalies.",
trigger=inbox_files(),
params=IngestParams,
tags=["showcase"],
notify={pager: [Notify.RUN_FAILED]},
):
work = workspace()
batch: list[Event[Arrived]] = dag_ctx.event.data # pyright: ignore[reportAny]
parsed = validate.partial(work=work).expand(path=paths(batch))
stored = store.expand(batch=parsed.on(Readings))
moved = quarantine.expand(bad=parsed.on(Corrupt))
hot: float = dag_ctx.params.hot_celsius # pyright: ignore[reportAny]
summary(stored, moved, detect(parsed, hot))
A poke trigger batches new files. A
resource supplies a scratch folder, and mapping validates
each file. Outcomes send good readings to the SQLite
connection and corrupt files to quarantine. detect gathers the parsed
results, applies the run’s threshold parameter, and posts an
anomaly event for each hot device. Its key combines the
device and reading time, so a later alarm can start another run. The task also has a hard
memory limit.
Respond to an alarm¶
"""One run per hot device: diagnose it, wait for an operator, then maintain it or escalate.
An `anomaly` event (posted by `readings_ingest`, keyed `dev-a1@<time>`: one run per alarm, not
per device) starts a run; its data names the device. Two probes
race and `first_of` takes whichever answers first. Then the run waits for the operator's `ack`
for that device (`schedr events post ack --key dev-a1 --data '{"by": "ana"}'`), for at most
`ACK_WAIT`: acknowledged, it starts `device_maintenance` and waits for that run; not, it pages.
"""
import asyncio
import random
from datetime import timedelta
from greenhouse import pager, wait
from schedr import (
Dag,
Event,
EventNamed,
Failed,
Notify,
RunIf,
TimedOut,
TriggerDagOperator,
dag_ctx,
first_of,
task,
wait_for,
)
from schedr.types import Json
ACK_WAIT = wait(minutes=2)
"""How long an operator has to acknowledge; then the pager is told."""
async def _ping(device: str, delay: float) -> float:
"""Stands in for asking the device: a round trip of `delay` seconds."""
del device # what a real client would address
await asyncio.sleep(delay)
return round(delay * 1000)
@task
def device_of(alarm: Json) -> str:
"""The alarm's device, from its data."""
if not (isinstance(alarm, dict) and isinstance(device := alarm.get("device"), str)):
raise ValueError(f"an anomaly event's data names its device: {alarm!r}")
return device
@task
async def probe_radio(device: str) -> str:
"""Pings the device three times at once, over the radio link."""
times = await asyncio.gather(*(_ping(device, random.uniform(0.1, 0.6)) for _ in range(3)))
return f"{device} answers over radio in {min(times):.0f} ms"
@task
async def probe_gateway(device: str) -> str:
"""Asks the zone's gateway for the device's last heartbeat."""
ago = await _ping(device, random.uniform(0.1, 0.6))
return f"{device} last seen by its gateway {ago:.0f} ms ago"
@task
def diagnose(finding: str, winner: str, anomaly: Json) -> str:
"""Whichever probe answered first, with the reading that raised the alarm."""
text = f"{finding} (via {winner}); reading: {anomaly}"
print(text)
return text
@task
def requested(ack: Event[Json]) -> str:
"""What the operator asked for: a recalibration unless they said otherwise."""
said = ack.data if isinstance(ack.data, dict) else {}
print(f"acknowledged by {said.get('by', 'someone')}")
return str(said.get("action", "recalibrate"))
# Skipped, not run with `None`, when the acknowledgement came (the edge from `ack` not taken).
@task(run_if=RunIf.ALL_SUCCEEDED)
def escalate(timed_out: TimedOut, diagnosis: str) -> None:
"""No one acknowledged in time: the pager hears of it."""
del timed_out
pager.send(
f"{dag_ctx.event.key}: no acknowledgement in {ACK_WAIT}", data={"diagnosis": diagnosis}
)
@task
def done(run_id: str) -> str:
return f"maintenance run {run_id} succeeded"
@task
def maintenance_failed(result: Failed) -> None:
pager.send(
f"maintenance of {dag_ctx.event.key} ended {result.state}", data={"run": result.run_id}
)
# `pager` among the DAG's channels: its tasks' own `pager.send` posts there too.
with Dag(
"anomaly_response",
description="Diagnoses a hot device, waits for an operator, then maintains it or escalates.",
trigger=EventNamed("anomaly"),
tags=["showcase"],
notify={pager: [Notify.RUN_FAILED]},
):
alarm: Json = dag_ctx.event.data # pyright: ignore[reportAny]
# An output: the wait below takes it as its key, so an operator acks by device.
device = device_of(alarm)
finding, winner = first_of(probe_radio(device), probe_gateway(device), with_winner=True)
diagnosis = diagnose(finding, winner, alarm)
ack = wait_for(EventNamed("ack", key=device), max_wait=ACK_WAIT)
diagnosis >> ack
escalate(ack.on(TimedOut), diagnosis)
started = TriggerDagOperator(
"start_maintenance",
dag="device_maintenance",
params={"device": device, "action": requested(ack.on(Event[Json]))},
max_wait=timedelta(minutes=5),
# Skipped when no one acknowledged: `requested` was, though `device_of` ran.
run_if=RunIf.ALL_SUCCEEDED,
)
done(started.on(str))
maintenance_failed(started.on(Failed))
Each new anomaly key starts a run. Two probes race, and
first_of supplies the first answer for the diagnosis. The run then
waits for an ack event, keyed by device. An acknowledgement
supplies the action for a chained maintenance run, which the response
waits for. A timeout or failed maintenance sends a pager notification.
Maintain a device¶
"""Maintaining one device, started by `anomaly_response` once an operator acknowledged.
The command task talks to the device with a token from schedr's secrets (`greenhouse/devices`,
put in by `make standalone`), registers a cleanup handle before it starts changing the device,
and says how it went by its exit code: 0 fixed remotely, 3 a site visit is needed. The
outcome routes to the closing step.
"""
from dataclasses import dataclass
from datetime import timedelta
from schedr import (
Chained,
CommandOperator,
Dag,
EmptyOperator,
Outcome,
StepDefaults,
dag_ctx,
secrets,
task,
)
@dataclass
class MaintenanceParams:
"""What a maintenance run is given; the defaults let it run on its own."""
device: str = "dev-a1"
action: str = "recalibrate"
class Result(Outcome):
"""What the device said, by the command's exit code."""
FIXED = 0
NEEDS_VISIT = 3
# A device whose name ends in 2 "needs a visit": the scenario's way to show both paths.
SCRIPT = r"""
set -eu
test -n "$DEVICE_TOKEN"
echo "$ACTION on $DEVICE with a token of ${#DEVICE_TOKEN} characters"
schedr task-ctx cleanup add Session device="$DEVICE"
sleep 2
case "$DEVICE" in *2) echo "sensor drift too large: replace the probe"; exit 3 ;; esac
echo "calibrated"
"""
CLEANUP = r"""
schedr task-ctx cleanup list Session --field device | while read -r d; do
echo "closing the maintenance session on $d"
done
"""
@task
def visit_ticket(device: str) -> str:
text = f"ticket: send someone to {device}"
print(text)
return text
@task
def fixed_report(device: str, action: str) -> str:
return f"{device}: {action} done remotely"
with Dag(
"device_maintenance",
description="Maintains one device, once an operator acknowledged its anomaly.",
trigger=Chained(by=["anomaly_response"]),
params=MaintenanceParams,
defaults=StepDefaults(retries=1, retry_delay=timedelta(seconds=5)),
tags=["showcase"],
):
device: str = dag_ctx.params.device # pyright: ignore[reportAny]
action: str = dag_ctx.params.action # pyright: ignore[reportAny]
work = CommandOperator(
"maintain",
["sh", "-c", SCRIPT],
env={
"DEVICE": device,
"ACTION": action,
"DEVICE_TOKEN": secrets["greenhouse/devices"]["token"],
},
outcomes=Result,
cleanup=CLEANUP,
cleanup_handles=["Session"],
cleanup_timeout=timedelta(seconds=20),
retries=0,
)
report = fixed_report(device, action)
ticket = visit_ticket(device)
work.on(Result.FIXED) >> report
work.on(Result.NEEDS_VISIT) >> ticket
[report, ticket] >> EmptyOperator("closed")
The chained trigger accepts runs from anomaly_response. A
command task receives the device and action as parameters and a token
from secrets. It registers a cleanup handle
and uses its exit code to route to a remote-fix report or a visit ticket. Both paths join at
closed.
Roll up the readings¶
"""Every five minutes, each zone's readings summed up; a warm zone gets its vents opened.
A run covers `since` to `planned_for`. Its poke sensor waits until the window has readings at
all, for at most a minute: an empty window ends `TimedOut` and the run records that, without
failing. Each zone is a group of its own, with its own retries. A branch then picks what follows
from the summaries. `schedr runs backfill greenhouse_rollup --from ... --to ...` fills windows
already past, oldest first.
"""
from datetime import datetime, timedelta
from typing import cast
from greenhouse import FAST, ZONES, ZoneSummary, readings_db, wait
from schedr import (
Dag,
Every,
RunIf,
StepDefaults,
Task,
TimedOut,
branch,
dag_ctx,
group,
sensor,
task,
)
from schedr.sensors import NOT_YET, NotYet
WARM_CELSIUS = 28.0
def _count(since: datetime, until: datetime) -> int:
with readings_db() as db:
row = cast(
"tuple[int]",
db.execute(
"select count(*) from readings where at >= ? and at < ?",
(since.isoformat(), until.isoformat()),
).fetchone(),
)
return row[0]
@sensor.poke(
every=timedelta(seconds=1 if FAST else 10), max_wait=wait(minutes=1), connections=[readings_db]
)
async def has_readings(since: datetime, until: datetime) -> int | NotYet:
"""The window's readings once there are any; a late device still counts."""
found = _count(since, until)
return found if found else NOT_YET
@task(connections=[readings_db])
def summarize(zone: str, since: datetime, until: datetime) -> ZoneSummary:
with readings_db() as db:
count, mean, top = cast(
"tuple[int, float | None, float | None]",
db.execute(
"""select count(*), avg(celsius), max(celsius) from readings
where zone = ? and at >= ? and at < ?""",
(zone, since.isoformat(), until.isoformat()),
).fetchone(),
)
return ZoneSummary(
zone=zone, readings=count, mean_celsius=mean, max_celsius=top, since=since, until=until
)
# Both skipped for a window without readings, where the zones' summaries were.
@task(run_if=RunIf.ALL_SUCCEEDED)
def ventilate(summaries: list[ZoneSummary]) -> list[str]:
opened = [s.zone for s in summaries if s.mean_celsius and s.mean_celsius > WARM_CELSIUS]
print(f"opening the vents of {', '.join(opened)}")
return opened
@task
def all_normal() -> None:
print("every zone within range")
@task
def quiet(timed_out: TimedOut, since: datetime, until: datetime) -> str:
del timed_out
return f"no readings from {since:%H:%M} to {until:%H:%M}"
with Dag(
"greenhouse_rollup",
description="Sums up each zone's readings every 5 minutes, and opens a warm zone's vents.",
trigger=Every(timedelta(minutes=5)),
tags=["showcase"],
):
since: datetime = dag_ctx.run.since
until: datetime = dag_ctx.run.planned_for
readings = has_readings(since, until)
quiet(readings.on(TimedOut), since, until)
summaries: list[ZoneSummary] = []
for zone in ZONES:
# The group's tasks are `zone_a.summarize`, ...: retried on their own.
with group(
zone, defaults=StepDefaults(retries=2, retry_delay=timedelta(seconds=10))
) as per_zone:
summaries.append(summarize(zone, since, until))
readings.on(int) >> per_zone
vents = ventilate(summaries)
normal = all_normal()
@branch
def act(summaries: list[ZoneSummary]) -> list[Task]:
"""Decides at run time, from the summaries, which path runs."""
warm = any(s.mean_celsius and s.mean_celsius > WARM_CELSIUS for s in summaries)
return [vents] if warm else [normal]
act.override(run_if=RunIf.ALL_SUCCEEDED)(summaries) >> [vents, normal]
Every five minutes, a scheduled run covers its run window. A
sensor waits for readings; if it times out, quiet records the empty window.
Otherwise, one group per zone summarizes its readings, and a
branch chooses whether to open vents for warm zones or report that
all are normal. Past windows can be backfilled.
Test the DAGs¶
examples/showcase/test_showcase.py uses run_dag to run each DAG
on its own. It checks ingestion and quarantine, an unanswered alarm, both maintenance outcomes,
and rollups with and without readings. The test supplies its own events, connection and secret
where needed. It sets GREENHOUSE_FAST=1 for shorter waits and passes that name through
[worker] pass_env, because a worker’s processes get a clean environment.