fromscratch-pystack 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fromscratch_pystack-0.5.0.dist-info/METADATA +510 -0
- fromscratch_pystack-0.5.0.dist-info/RECORD +43 -0
- fromscratch_pystack-0.5.0.dist-info/WHEEL +4 -0
- fromscratch_pystack-0.5.0.dist-info/entry_points.txt +3 -0
- fromscratch_pystack-0.5.0.dist-info/licenses/LICENSE +21 -0
- pystack/__init__.py +1 -0
- pystack/_version.py +24 -0
- pystack/adapters/__init__.py +1 -0
- pystack/adapters/db_storage.py +157 -0
- pystack/adapters/os_pebble.py +118 -0
- pystack/adapters/pebble_db.py +85 -0
- pystack/cli.py +127 -0
- pystack/environment.py +272 -0
- pystack/plugins/__init__.py +1 -0
- pystack/plugins/_dbcrash_child.py +56 -0
- pystack/plugins/_schedagents.py +37 -0
- pystack/plugins/_schedalerts.py +103 -0
- pystack/plugins/_schedweb.py +79 -0
- pystack/plugins/_shared.py +26 -0
- pystack/plugins/_webdemo.py +171 -0
- pystack/plugins/base.py +201 -0
- pystack/plugins/coldb_plugin.py +165 -0
- pystack/plugins/crypto_plugin.py +115 -0
- pystack/plugins/docdb_plugin.py +172 -0
- pystack/plugins/git_plugin.py +94 -0
- pystack/plugins/graphdb_plugin.py +206 -0
- pystack/plugins/kv_plugin.py +156 -0
- pystack/plugins/llm_plugin.py +102 -0
- pystack/plugins/mq_plugin.py +290 -0
- pystack/plugins/net_plugin.py +247 -0
- pystack/plugins/pydb_plugin.py +111 -0
- pystack/plugins/registry.py +150 -0
- pystack/plugins/sched_plugin.py +235 -0
- pystack/plugins/search_plugin.py +151 -0
- pystack/plugins/tsdb_plugin.py +175 -0
- pystack/plugins/vecdb_plugin.py +168 -0
- pystack/plugins/web_plugin.py +95 -0
- pystack/py.typed +0 -0
- pystack/web/__init__.py +1 -0
- pystack/web/app.py +138 -0
- pystack/web/static/app.js +105 -0
- pystack/web/static/style.css +158 -0
- pystack/web/templates/index.html +59 -0
pystack/environment.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""PyStack environment -- boot and wire everything together.
|
|
2
|
+
|
|
3
|
+
The environment is the control room. It creates a database, registers
|
|
4
|
+
the Pebble adapter, and provides a ready-to-use integrated runtime.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import contextlib
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from pebble import run_source
|
|
12
|
+
from py_os.kernel import Kernel
|
|
13
|
+
from py_os.shell import Shell
|
|
14
|
+
from pydb.database import Database
|
|
15
|
+
from pydb.executor import execute
|
|
16
|
+
from pydb.formatter import format_results
|
|
17
|
+
from pydb.query import Query
|
|
18
|
+
from pydb.sql_parser import parse_sql
|
|
19
|
+
|
|
20
|
+
from pystack.adapters.os_pebble import (
|
|
21
|
+
register_pebble_command,
|
|
22
|
+
register_save_command,
|
|
23
|
+
register_sql_command,
|
|
24
|
+
)
|
|
25
|
+
from pystack.adapters.pebble_db import make_db_module
|
|
26
|
+
from pystack.plugins.base import Plugin
|
|
27
|
+
from pystack.plugins.coldb_plugin import ColDBPlugin
|
|
28
|
+
from pystack.plugins.crypto_plugin import CryptoPlugin
|
|
29
|
+
from pystack.plugins.docdb_plugin import DocDBPlugin
|
|
30
|
+
from pystack.plugins.git_plugin import GitPlugin
|
|
31
|
+
from pystack.plugins.graphdb_plugin import GraphDBPlugin
|
|
32
|
+
from pystack.plugins.kv_plugin import KVPlugin
|
|
33
|
+
from pystack.plugins.llm_plugin import LLMPlugin
|
|
34
|
+
from pystack.plugins.mq_plugin import MQPlugin
|
|
35
|
+
from pystack.plugins.net_plugin import NetPlugin
|
|
36
|
+
from pystack.plugins.pydb_plugin import PyDBPlugin
|
|
37
|
+
from pystack.plugins.registry import PluginRegistry
|
|
38
|
+
from pystack.plugins.sched_plugin import PySchedulerPlugin
|
|
39
|
+
from pystack.plugins.search_plugin import SearchPlugin
|
|
40
|
+
from pystack.plugins.tsdb_plugin import TSDBPlugin
|
|
41
|
+
from pystack.plugins.vecdb_plugin import VecDBPlugin
|
|
42
|
+
from pystack.plugins.web_plugin import WebPlugin
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class PyStackEnvironment:
|
|
46
|
+
"""Manage the lifecycle of an integrated PyStack session.
|
|
47
|
+
|
|
48
|
+
Creates a PyDB database and runs Pebble programs through Pebble's
|
|
49
|
+
public API, handing each run this environment's own ``db`` module and
|
|
50
|
+
plugin modules (nothing is shared between environments).
|
|
51
|
+
|
|
52
|
+
In OS mode, also boots a PyOS kernel and shell with integrated
|
|
53
|
+
``pebble`` and ``sql`` commands.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
db_path: Directory for PyDB data files.
|
|
57
|
+
os_mode: If True, boot a PyOS kernel and register shell commands.
|
|
58
|
+
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
__slots__ = (
|
|
62
|
+
"_closed",
|
|
63
|
+
"_database",
|
|
64
|
+
"_db_module",
|
|
65
|
+
"_db_path",
|
|
66
|
+
"_kernel",
|
|
67
|
+
"_os_mode",
|
|
68
|
+
"_plugin_registry",
|
|
69
|
+
"_shell",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
db_path: str | Path = "pystack_data",
|
|
75
|
+
*,
|
|
76
|
+
os_mode: bool = False,
|
|
77
|
+
) -> None:
|
|
78
|
+
"""Create and boot the integrated environment."""
|
|
79
|
+
self._db_path = Path(db_path)
|
|
80
|
+
self._closed = False
|
|
81
|
+
self._os_mode = os_mode
|
|
82
|
+
self._kernel: Kernel | None = None
|
|
83
|
+
self._shell: Shell | None = None
|
|
84
|
+
self._plugin_registry = PluginRegistry()
|
|
85
|
+
|
|
86
|
+
self._database = Database(path=self._db_path)
|
|
87
|
+
self._database.load()
|
|
88
|
+
# This environment's own ``db`` module; it is only placed on Pebble's
|
|
89
|
+
# shared module shelf while one of *our* programs runs.
|
|
90
|
+
self._db_module = make_db_module(self._database)
|
|
91
|
+
self._register_all_plugins()
|
|
92
|
+
|
|
93
|
+
if os_mode:
|
|
94
|
+
self._boot_os()
|
|
95
|
+
|
|
96
|
+
# Activate every plugin exactly once, in every mode. Passing the
|
|
97
|
+
# shell (which is None outside OS mode) means plugin Pebble modules
|
|
98
|
+
# and on_boot() hooks always run, while shell commands are only
|
|
99
|
+
# registered when there is a shell to register them in.
|
|
100
|
+
self._plugin_registry.activate_all(shell=self._shell, data_dir=self._db_path)
|
|
101
|
+
|
|
102
|
+
def _register_all_plugins(self) -> None:
|
|
103
|
+
"""Register all built-in integration plugins with the registry.
|
|
104
|
+
|
|
105
|
+
Add the crypto, web, git, net, search, mq, kv, docdb, graphdb,
|
|
106
|
+
tsdb, vecdb, coldb, llm, and sched plugins so the registry can wire their
|
|
107
|
+
Pebble modules, shell commands, and boot hooks during activation.
|
|
108
|
+
"""
|
|
109
|
+
plugins: list[Plugin] = [
|
|
110
|
+
CryptoPlugin(),
|
|
111
|
+
WebPlugin(),
|
|
112
|
+
GitPlugin(),
|
|
113
|
+
NetPlugin(),
|
|
114
|
+
SearchPlugin(),
|
|
115
|
+
MQPlugin(),
|
|
116
|
+
PyDBPlugin(),
|
|
117
|
+
PySchedulerPlugin(),
|
|
118
|
+
KVPlugin(),
|
|
119
|
+
DocDBPlugin(),
|
|
120
|
+
GraphDBPlugin(),
|
|
121
|
+
TSDBPlugin(),
|
|
122
|
+
VecDBPlugin(),
|
|
123
|
+
ColDBPlugin(),
|
|
124
|
+
LLMPlugin(),
|
|
125
|
+
]
|
|
126
|
+
for plugin in plugins:
|
|
127
|
+
self._plugin_registry.register(plugin)
|
|
128
|
+
|
|
129
|
+
def _boot_os(self) -> None:
|
|
130
|
+
"""Boot the PyOS kernel and register the pebble and sql shell commands."""
|
|
131
|
+
kernel = Kernel()
|
|
132
|
+
kernel.boot()
|
|
133
|
+
shell = Shell(kernel=kernel)
|
|
134
|
+
|
|
135
|
+
register_pebble_command(shell, kernel, self.run_pebble_source)
|
|
136
|
+
register_sql_command(shell, self.run_sql)
|
|
137
|
+
register_save_command(shell, self.save)
|
|
138
|
+
|
|
139
|
+
# Discover any third-party plugins installed via entry points so
|
|
140
|
+
# they are activated alongside the built-ins.
|
|
141
|
+
self._plugin_registry.discover()
|
|
142
|
+
|
|
143
|
+
self._kernel = kernel
|
|
144
|
+
self._shell = shell
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def plugin_registry(self) -> PluginRegistry:
|
|
148
|
+
"""Return the plugin registry."""
|
|
149
|
+
return self._plugin_registry
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def database(self) -> Database:
|
|
153
|
+
"""Return the PyDB database instance."""
|
|
154
|
+
return self._database
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def kernel(self) -> Kernel | None:
|
|
158
|
+
"""Return the PyOS kernel, or None if not in OS mode."""
|
|
159
|
+
return self._kernel
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def shell(self) -> Shell | None:
|
|
163
|
+
"""Return the PyOS shell, or None if not in OS mode."""
|
|
164
|
+
return self._shell
|
|
165
|
+
|
|
166
|
+
def execute_shell(self, command: str) -> str:
|
|
167
|
+
"""Execute a command in the PyOS shell.
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
command: The shell command to execute.
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
The command output.
|
|
174
|
+
|
|
175
|
+
Raises:
|
|
176
|
+
RuntimeError: If not in OS mode.
|
|
177
|
+
|
|
178
|
+
"""
|
|
179
|
+
if self._shell is None:
|
|
180
|
+
msg = "Not in OS mode -- call PyStackEnvironment(os_mode=True)"
|
|
181
|
+
raise RuntimeError(msg)
|
|
182
|
+
return self._shell.execute(command)
|
|
183
|
+
|
|
184
|
+
def save(self) -> None:
|
|
185
|
+
"""Save the database and every plugin's data.
|
|
186
|
+
|
|
187
|
+
Every part is tried even if an earlier one fails.
|
|
188
|
+
|
|
189
|
+
Raises:
|
|
190
|
+
ExceptionGroup: If anything couldn't be saved, after trying
|
|
191
|
+
everything.
|
|
192
|
+
|
|
193
|
+
"""
|
|
194
|
+
failures = self._save_everything()
|
|
195
|
+
if failures:
|
|
196
|
+
names = ", ".join(name for name, _ in failures)
|
|
197
|
+
msg = f"pystack could not save {names}"
|
|
198
|
+
raise ExceptionGroup(msg, [exc for _, exc in failures])
|
|
199
|
+
|
|
200
|
+
def shutdown(self) -> None:
|
|
201
|
+
"""Save everything, shut plugins down and stop the OS kernel.
|
|
202
|
+
|
|
203
|
+
Never raises -- it runs in ``finally:`` blocks, where an error would
|
|
204
|
+
hide the real one -- but prints one line per failure to stderr.
|
|
205
|
+
Safe to call more than once; later calls do nothing.
|
|
206
|
+
"""
|
|
207
|
+
if self._closed:
|
|
208
|
+
return
|
|
209
|
+
self._closed = True
|
|
210
|
+
for name, exc in self._save_everything():
|
|
211
|
+
sys.stderr.write(f"pystack: could not save {name}: {exc}\n")
|
|
212
|
+
for name, exc in self._plugin_registry.shutdown_all():
|
|
213
|
+
sys.stderr.write(f"pystack: could not shut down {name}: {exc}\n")
|
|
214
|
+
if self._kernel is not None:
|
|
215
|
+
with contextlib.suppress(Exception):
|
|
216
|
+
self._kernel.shutdown()
|
|
217
|
+
self._kernel = None
|
|
218
|
+
|
|
219
|
+
def _save_everything(self) -> list[tuple[str, Exception]]:
|
|
220
|
+
"""Save the database and every plugin, returning what failed."""
|
|
221
|
+
failures: list[tuple[str, Exception]] = []
|
|
222
|
+
try:
|
|
223
|
+
self._database.save()
|
|
224
|
+
except Exception as exc: # noqa: BLE001 -- reported by save()/shutdown()
|
|
225
|
+
failures.append(("database", exc))
|
|
226
|
+
failures.extend(self._plugin_registry.save_all(self._db_path))
|
|
227
|
+
return failures
|
|
228
|
+
|
|
229
|
+
def run_pebble_source(self, source: str) -> str:
|
|
230
|
+
"""Compile and run a Pebble source string with database access.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
source: The Pebble source code.
|
|
234
|
+
|
|
235
|
+
Returns:
|
|
236
|
+
The captured stdout output from the program.
|
|
237
|
+
|
|
238
|
+
"""
|
|
239
|
+
modules = {"db": self._db_module, **self._plugin_registry.pebble_modules()}
|
|
240
|
+
return run_source(source, modules=modules, base_dir=Path.cwd())
|
|
241
|
+
|
|
242
|
+
def run_pebble_file(self, file_path: str | Path) -> str:
|
|
243
|
+
"""Compile and run a Pebble file with database access.
|
|
244
|
+
|
|
245
|
+
Args:
|
|
246
|
+
file_path: Path to the .pbl file.
|
|
247
|
+
|
|
248
|
+
Returns:
|
|
249
|
+
The captured stdout output.
|
|
250
|
+
|
|
251
|
+
Raises:
|
|
252
|
+
FileNotFoundError: If the file doesn't exist.
|
|
253
|
+
|
|
254
|
+
"""
|
|
255
|
+
path = Path(file_path)
|
|
256
|
+
source = path.read_text(encoding="utf-8")
|
|
257
|
+
return self.run_pebble_source(source)
|
|
258
|
+
|
|
259
|
+
def run_sql(self, sql: str) -> str:
|
|
260
|
+
"""Execute a SQL statement and return formatted results.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
sql: The SQL text.
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
Formatted result string.
|
|
267
|
+
|
|
268
|
+
"""
|
|
269
|
+
parsed = parse_sql(sql)
|
|
270
|
+
results = execute(parsed, self._database)
|
|
271
|
+
columns = parsed.columns if isinstance(parsed, Query) and parsed.columns else None
|
|
272
|
+
return format_results(results, columns=columns)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Plugin system for extending PyStack with new components."""
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""The helper program for the ``dbcrash`` demo -- the one that gets unplugged.
|
|
2
|
+
|
|
3
|
+
It opens a journalled PyDB database, records three job runs (each one
|
|
4
|
+
committed, so each is written in the journal "diary" first), then starts a
|
|
5
|
+
fourth inside a transaction and dies without warning. Think of a clerk who
|
|
6
|
+
writes three finished jobs in the diary, picks up a fourth, and the lights go
|
|
7
|
+
out before it is signed off.
|
|
8
|
+
|
|
9
|
+
Run it with ``python -m pystack.plugins._dbcrash_child <folder>``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
from datetime import UTC, date, datetime
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from pydb.database import Database
|
|
18
|
+
from pydb.schema import Column, Schema
|
|
19
|
+
from pydb.transaction import Transaction
|
|
20
|
+
from pydb.types import DataType
|
|
21
|
+
|
|
22
|
+
TABLE = "job_runs"
|
|
23
|
+
COMMITTED_RUNS = (
|
|
24
|
+
("nightly-backup", date(2026, 10, 15), datetime(2026, 10, 15, 2, 0, tzinfo=UTC)),
|
|
25
|
+
("tidy-logs", date(2026, 10, 16), datetime(2026, 10, 16, 3, 15, tzinfo=UTC)),
|
|
26
|
+
("send-report", date(2026, 10, 17), datetime(2026, 10, 17, 7, 30, tzinfo=UTC)),
|
|
27
|
+
)
|
|
28
|
+
UNFINISHED_RUN = ("rebuild-index", date(2026, 10, 17), datetime(2026, 10, 17, 8, 0, tzinfo=UTC))
|
|
29
|
+
CRASH_EXIT_CODE = 9 # unusual on purpose: a program that hits an error exits with 1
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def runs_schema() -> Schema:
|
|
33
|
+
"""Return the job-run table's columns: a name, a run date and a start time."""
|
|
34
|
+
return Schema(
|
|
35
|
+
columns=[
|
|
36
|
+
Column("job", DataType.TEXT),
|
|
37
|
+
Column("run_date", DataType.DATE),
|
|
38
|
+
Column("started", DataType.TIMESTAMP),
|
|
39
|
+
]
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def crash_mid_transaction(folder: Path) -> None:
|
|
44
|
+
"""Commit three job runs, start a fourth, then die without committing."""
|
|
45
|
+
db = Database(folder, journal=True)
|
|
46
|
+
runs = db.create_table(TABLE, runs_schema())
|
|
47
|
+
for job, run_date, started in COMMITTED_RUNS:
|
|
48
|
+
runs.insert({"job": job, "run_date": run_date, "started": started})
|
|
49
|
+
txn = Transaction(db)
|
|
50
|
+
job, run_date, started = UNFINISHED_RUN
|
|
51
|
+
txn.get_table(TABLE).insert({"job": job, "run_date": run_date, "started": started})
|
|
52
|
+
os._exit(CRASH_EXIT_CODE) # the power cut: no commit, no close, no clean-up
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
if __name__ == "__main__":
|
|
56
|
+
crash_mid_transaction(Path(sys.argv[1]))
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""The ``schedagents`` demo: a scheduler that hands jobs to helpers on other desks.
|
|
2
|
+
|
|
3
|
+
Imagine a head chef who does not cook every dish herself. She pins an
|
|
4
|
+
order to the board and a kitchen helper picks it up. Some orders say
|
|
5
|
+
"any helper will do"; others say "only the helper with the grill". That
|
|
6
|
+
is what PyScheduler's remote agents do: the scheduler holds the timetable,
|
|
7
|
+
and small agents (``build-01``, and ``gpu-01`` tagged ``gpu``) take the
|
|
8
|
+
jobs, run them, and report back.
|
|
9
|
+
|
|
10
|
+
PyScheduler's own demo does the work: it starts a scheduler, an embedded
|
|
11
|
+
message broker and both agents, runs one job pinned to ``build-01`` and
|
|
12
|
+
one job that needs the ``gpu`` tag, and prints which agent ran each. This
|
|
13
|
+
command runs it in a temporary folder on the main thread (the jobs are
|
|
14
|
+
child processes) and returns what it printed.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import contextlib
|
|
18
|
+
import io
|
|
19
|
+
import tempfile
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from pyscheduler.demo_agents import run_agents_demo
|
|
23
|
+
|
|
24
|
+
AGENTS_SECONDS = 30.0
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def schedagents_cmd(_args: list[str]) -> str:
|
|
28
|
+
"""Run the remote-agents demo and return which agent ran each job."""
|
|
29
|
+
lines = ["Starting a scheduler, a broker and two agents (build-01 and gpu-01, tagged gpu)..."]
|
|
30
|
+
out = io.StringIO()
|
|
31
|
+
with (
|
|
32
|
+
tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp,
|
|
33
|
+
contextlib.redirect_stdout(out),
|
|
34
|
+
):
|
|
35
|
+
run_agents_demo(Path(tmp), seconds=AGENTS_SECONDS)
|
|
36
|
+
lines.extend(out.getvalue().splitlines())
|
|
37
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""The ``schedalerts`` demo: a failing job, its alert, and where the alert went.
|
|
2
|
+
|
|
3
|
+
A smoke alarm is only useful if someone hears it. PyScheduler's alerts
|
|
4
|
+
work the same way: when a job fails, the scheduler writes the alert down
|
|
5
|
+
first (so it can never be forgotten), then hands it to each notifier the
|
|
6
|
+
routes pick. Here the only notifier is a ``log`` notifier, a notebook
|
|
7
|
+
next to the config that gets one line per alert.
|
|
8
|
+
|
|
9
|
+
The demo writes that config into a temporary folder, runs the scheduler
|
|
10
|
+
in-process on PyNet's event loop, triggers a job that always fails, waits
|
|
11
|
+
until the alert has been delivered, and prints the alert, its delivery
|
|
12
|
+
and the notebook line.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import tempfile
|
|
17
|
+
import textwrap
|
|
18
|
+
import time
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from pyscheduler.client import ApiClient
|
|
23
|
+
|
|
24
|
+
from pystack.plugins.sched_plugin import RUN_DATE, with_scheduler
|
|
25
|
+
|
|
26
|
+
FAILING_JOB = "nightly-report"
|
|
27
|
+
ALERT_LOG = "alerts.log"
|
|
28
|
+
DONE_SECONDS = 5.0
|
|
29
|
+
POLL = 0.02
|
|
30
|
+
|
|
31
|
+
CONFIG = """
|
|
32
|
+
notifiers:
|
|
33
|
+
team-log: {type: log, path: alerts.log}
|
|
34
|
+
routes:
|
|
35
|
+
- {match: "alert.#", notify: [team-log]}
|
|
36
|
+
jobs:
|
|
37
|
+
nightly-report:
|
|
38
|
+
command: exit 1
|
|
39
|
+
schedule: manual
|
|
40
|
+
criticality: high
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def write_config(folder: Path) -> Path:
|
|
45
|
+
"""Write the demo's ``pysched.yaml`` into ``folder`` and return its path."""
|
|
46
|
+
header = (
|
|
47
|
+
"scheduler:\n"
|
|
48
|
+
" name: pystack-alerts\n"
|
|
49
|
+
f" state_dir: {folder / 'state'}\n"
|
|
50
|
+
f" log_dir: {folder / 'logs'}\n"
|
|
51
|
+
" listen: 127.0.0.1:0\n"
|
|
52
|
+
)
|
|
53
|
+
path = folder / "pysched.yaml"
|
|
54
|
+
path.write_text(header + textwrap.dedent(CONFIG).lstrip("\n"), encoding="utf-8")
|
|
55
|
+
return path
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def wait_for_sent_alert(client: ApiClient) -> dict[str, Any]:
|
|
59
|
+
"""Wait until the failing job's alert has a sent delivery, and return it.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
TimeoutError: If no alert was delivered within ``DONE_SECONDS``.
|
|
63
|
+
|
|
64
|
+
"""
|
|
65
|
+
deadline = time.monotonic() + DONE_SECONDS
|
|
66
|
+
while True:
|
|
67
|
+
for alert in client.alerts(job=FAILING_JOB)["alerts"]:
|
|
68
|
+
if any(d["status"] == "sent" for d in alert["deliveries"]):
|
|
69
|
+
return alert
|
|
70
|
+
if time.monotonic() > deadline:
|
|
71
|
+
msg = f"no alert was delivered within {DONE_SECONDS:g} s"
|
|
72
|
+
raise TimeoutError(msg)
|
|
73
|
+
time.sleep(POLL)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def alert_story(client: ApiClient, log_path: Path) -> list[str]:
|
|
77
|
+
"""Trigger the failing job, wait for its alert and describe where it went."""
|
|
78
|
+
run = client.trigger(FAILING_JOB, run_date=RUN_DATE)["run"]
|
|
79
|
+
lines = [f"Triggered {run['run_id']}, a job that always fails."]
|
|
80
|
+
alert = wait_for_sent_alert(client)
|
|
81
|
+
lines.append("")
|
|
82
|
+
lines.append(f"Alert {alert['alert_id']}:")
|
|
83
|
+
lines.append(f" kind: {alert['kind']} criticality: {alert['criticality']}")
|
|
84
|
+
lines.append(f" message: {alert['message']}")
|
|
85
|
+
lines.extend(
|
|
86
|
+
f" delivered to {d['notifier']}: {d['status']} (attempt {d['attempts']})"
|
|
87
|
+
for d in alert["deliveries"]
|
|
88
|
+
)
|
|
89
|
+
entries = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines()]
|
|
90
|
+
lines.append("")
|
|
91
|
+
lines.append(f"The {ALERT_LOG} notebook now has {len(entries)} line(s); the newest says:")
|
|
92
|
+
lines.append(f" {entries[-1]['kind']} alert for {entries[-1]['run_id']}")
|
|
93
|
+
return lines
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def schedalerts_cmd(_args: list[str]) -> str:
|
|
97
|
+
"""Run the alert demo and return its story."""
|
|
98
|
+
lines = ["Starting a scheduler with a log notifier and a route for every alert..."]
|
|
99
|
+
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
|
100
|
+
folder = Path(tmp)
|
|
101
|
+
config = write_config(folder)
|
|
102
|
+
lines.extend(with_scheduler(config, lambda client: alert_story(client, folder / ALERT_LOG)))
|
|
103
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""The ``schedweb`` demo: PyScheduler's web UI over a few days of real runs.
|
|
2
|
+
|
|
3
|
+
A shop window is more fun with the shelves stocked. This command asks
|
|
4
|
+
PyScheduler's own demo to stock them: a folder with a dozen jobs (chains,
|
|
5
|
+
a file watcher, a flaky job and one that always fails critically), a user
|
|
6
|
+
``admin`` with password ``demo``, and three days of runs. Then it opens
|
|
7
|
+
the shop on a free loopback port and waits for Ctrl-C, so you can look at
|
|
8
|
+
the job board, the graph and the timeline in your browser.
|
|
9
|
+
|
|
10
|
+
``schedweb --seconds N`` stops by itself after ``N`` seconds (that is how
|
|
11
|
+
the tests use it). Once the UI is listening, a helper checks that the
|
|
12
|
+
login page answers, so the output says whether the shop really opened.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import tempfile
|
|
16
|
+
import threading
|
|
17
|
+
import urllib.request
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from pyscheduler.demo import LOGIN_NAME, LOGIN_PASSWORD, seed_demo, serve_demo
|
|
21
|
+
|
|
22
|
+
CHECK_TIMEOUT = 5.0
|
|
23
|
+
USAGE = "usage: schedweb [--seconds N]"
|
|
24
|
+
FLAG_AND_VALUE = 2
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def parse_seconds(args: list[str]) -> float | None:
|
|
28
|
+
"""Return the ``--seconds`` value from ``args``, or None to serve until Ctrl-C.
|
|
29
|
+
|
|
30
|
+
Raises:
|
|
31
|
+
ValueError: If the arguments are not ``--seconds <positive number>``.
|
|
32
|
+
|
|
33
|
+
"""
|
|
34
|
+
if not args:
|
|
35
|
+
return None
|
|
36
|
+
if len(args) != FLAG_AND_VALUE or args[0] != "--seconds":
|
|
37
|
+
raise ValueError(USAGE)
|
|
38
|
+
seconds = float(args[1])
|
|
39
|
+
if seconds <= 0:
|
|
40
|
+
raise ValueError(USAGE)
|
|
41
|
+
return seconds
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def check_login(url: str, found: list[str]) -> None:
|
|
45
|
+
"""Fetch ``url``'s login page and note how it answered in ``found``."""
|
|
46
|
+
try:
|
|
47
|
+
with urllib.request.urlopen(f"{url}/login", timeout=CHECK_TIMEOUT) as response:
|
|
48
|
+
found.append(f"The login page answered {response.status}.")
|
|
49
|
+
except OSError as exc:
|
|
50
|
+
found.append(f"The login page did not answer: {exc}")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def schedweb_cmd(args: list[str]) -> str:
|
|
54
|
+
"""Seed a demo folder, serve the web UI, and report where it was and how it went."""
|
|
55
|
+
try:
|
|
56
|
+
seconds = parse_seconds(args)
|
|
57
|
+
except ValueError:
|
|
58
|
+
return USAGE
|
|
59
|
+
found: list[str] = []
|
|
60
|
+
checks: list[threading.Thread] = []
|
|
61
|
+
|
|
62
|
+
def ready(url: str) -> None:
|
|
63
|
+
"""Remember the address and check the login page from a helper thread."""
|
|
64
|
+
found.append(f"The web UI was at {url} (log in as {LOGIN_NAME} / {LOGIN_PASSWORD}).")
|
|
65
|
+
check = threading.Thread(target=check_login, args=(url, found), daemon=True)
|
|
66
|
+
checks.append(check)
|
|
67
|
+
check.start()
|
|
68
|
+
|
|
69
|
+
lines = ["Stocking a PyScheduler demo with a dozen jobs and three days of runs..."]
|
|
70
|
+
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
|
71
|
+
folder = Path(tmp) / "demo"
|
|
72
|
+
seed_demo(folder)
|
|
73
|
+
lines.append("Opening the web UI. Press Ctrl-C to stop.")
|
|
74
|
+
serve_demo(folder, seconds=seconds, ready=ready)
|
|
75
|
+
for check in checks:
|
|
76
|
+
check.join(CHECK_TIMEOUT)
|
|
77
|
+
lines.extend(found)
|
|
78
|
+
lines.append("The web UI has stopped.")
|
|
79
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Shared helpers used by multiple plugins.
|
|
2
|
+
|
|
3
|
+
Some Pebble handler functions appear in more than one plugin -- for
|
|
4
|
+
example, both the web and net plugins need URL parsing. Instead of
|
|
5
|
+
copying the code (which is like writing the same homework answer
|
|
6
|
+
twice!), we put shared handlers here so every plugin can reuse them.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from pebble import Value as PebbleValue
|
|
10
|
+
from pynet.url import parse_url
|
|
11
|
+
|
|
12
|
+
from pystack.plugins.base import pebble_handler
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@pebble_handler
|
|
16
|
+
def url_parse(args: list[PebbleValue]) -> PebbleValue:
|
|
17
|
+
"""Parse a URL string into a dict with scheme, host, port, and path."""
|
|
18
|
+
url_string = str(args[0])
|
|
19
|
+
parsed = parse_url(url_string)
|
|
20
|
+
result: dict[str, PebbleValue] = {
|
|
21
|
+
"scheme": parsed.scheme,
|
|
22
|
+
"host": parsed.host,
|
|
23
|
+
"port": parsed.port,
|
|
24
|
+
"path": parsed.path,
|
|
25
|
+
}
|
|
26
|
+
return result
|