Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
scheduler.py · 15.3 KB · 377 lines
1"""system_scheduler -- the Flower-style board for daemon-scheduled tasks.
2
3Dan's bar: "celery flower would do better than that" -- the raw /daemon/*
4JSON (admin-token-gated, unreadable) is not an operator surface. This page
5is: the task board (schedule, next run, last outcome, run count) joined
6with the run history (scheduler_runs records the daemon appends per
7execution -- result JSON, error + type, duration), plus the two controls
8an operator actually reaches for: Run now and Pause/Resume.
9
10Identity posture: public execute like every page object; everything is
11gated on an ADMIN identity inside (anonymous/non-admin get a prompt, no
12data). POST actions mutate the scheduler trigger's task state directly --
13the same state the daemon reads -- so Run now simply sets next_run to now
14and the next daemon poll executes it; results then appear here because the
15daemon records them as scheduler_runs rows. Live: subscribes to
16scheduler_runs over /ws (admin read permission gates the push), with a
1760s poll fallback.
18"""
19
20import html
21import json
22import os
23import time
24from datetime import datetime, timezone
25
26import object_records
27import object_state
28
29_logger = None
30
31_TASK_PREFIX = "task_"
32_RUNS_SHOWN = 50
33
34
35def _base_dir():
36 return os.environ.get("DBBASIC_DATA_DIR", "data")
37
38
39def _tasks():
40 rows, invalid = [], 0
41 for key, value in object_state.get_object_state("scheduler", _base_dir()).items():
42 if not key.startswith(_TASK_PREFIX):
43 continue
44 try:
45 task = json.loads(value)
46 except (ValueError, TypeError):
47 invalid += 1
48 continue
49 if not isinstance(task, dict):
50 invalid += 1
51 continue
52 task["_key"] = key
53 rows.append(task)
54 rows.sort(key=lambda t: str(t.get("id") or ""))
55 return rows, invalid
56
57
58def _runs():
59 try:
60 rows = object_records.read_collection_records("scheduler_runs", base_dir=_base_dir())
61 except Exception:
62 return None # collection not installed
63 rows.sort(key=lambda r: r.get("started_at") or "", reverse=True)
64 return rows
65
66
67def _when(epoch):
68 if not epoch:
69 return "—"
70 try:
71 return datetime.fromtimestamp(int(epoch), tz=timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
72 except (ValueError, TypeError, OSError):
73 return "—"
74
75
76def _esc(value):
77 return html.escape(str(value or ""))
78
79
80_DAYS = {"0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday",
81 "4": "Thursday", "5": "Friday", "6": "Saturday", "7": "Sunday",
82 "sun": "Sunday", "mon": "Monday", "tue": "Tuesday", "wed": "Wednesday",
83 "thu": "Thursday", "fri": "Friday", "sat": "Saturday"}
84
85
86def describe_schedule(schedule, task_type=""):
87 """Render a schedule in plain English.
88
89 "10 6 * * *" is precise and completely opaque to anyone who does not
90 write cron daily -- and an operator who cannot read WHEN a task runs
91 cannot tell whether it ran when it should have. So the board leads
92 with the English and keeps the cron string as the small print.
93 """
94 text = str(schedule or "").strip()
95 if not text:
96 return ""
97 if str(task_type).strip() == "onetime":
98 return f"Once at {text[:16].replace('T', ' ')}"
99 if str(task_type).strip() == "interval":
100 return f"Every {text} seconds" if text.isdigit() else ""
101
102 parts = text.split()
103 if len(parts) != 5:
104 return ""
105 minute, hour, dom, month, dow = parts
106
107 def _every(field):
108 return field.startswith("*/") and field[2:].isdigit()
109
110 if _every(minute) and hour == dom == month == dow == "*":
111 return f"Every {minute[2:]} minutes"
112 if minute.isdigit() and hour == "*" and dom == month == dow == "*":
113 return f"Hourly at :{int(minute):02d}"
114 if _every(hour) and minute.isdigit() and dom == month == dow == "*":
115 return f"Every {hour[2:]} hours at :{int(minute):02d}"
116 if not (minute.isdigit() and hour.isdigit()):
117 return ""
118
119 at = f"{int(hour):02d}:{int(minute):02d} UTC"
120 if dom == month == dow == "*":
121 return f"Daily at {at}"
122 if dow != "*" and dom == "*":
123 # Only a single named day is describable: "1-5" is weekdays and
124 # "1,4" is twice a week -- calling either "Weekly" would be a
125 # confident wrong answer, so those fall back to the raw cron.
126 day = _DAYS.get(dow.lower())
127 return f"Weekly on {day} at {at}" if day else ""
128 if dom.isdigit() and month == "*" and dow == "*":
129 return f"Monthly on day {int(dom)} at {at}"
130 if dom.isdigit() and month.isdigit() and dow == "*":
131 return f"Yearly on {int(month)}/{int(dom)} at {at}"
132 return ""
133
134
135def _task_rows_html(tasks, latest_by_task):
136 if not tasks:
137 return '<tr><td colspan="8" class="muted">No task_* entries in the scheduler trigger state.</td></tr>'
138 out = []
139 for task in tasks:
140 tid = str(task.get("id") or task.get("_key"))
141 last = latest_by_task.get(tid)
142 if last is None:
143 last_cell = '<span class="muted">never</span>'
144 else:
145 badge = ('<span class="ok">&#10003; ok</span>' if last.get("ok") == "true"
146 else '<span class="bad">&#10007; failed</span>')
147 last_cell = (f"{badge} <span class=\"muted\">{_esc(last.get('started_at', ''))[:16]}"
148 f" &middot; {_esc(last.get('duration_ms'))}ms</span>")
149 failing = int(task.get("consecutive_failures") or 0)
150 if failing:
151 # The task row itself says it is failing -- true even when the
152 # scheduler_runs collection is not installed.
153 last_cell = (
154 f'<span class="bad">&#10007; failing x{failing}</span> '
155 f'<span class="muted">{_when(task.get("last_error_at"))}</span>'
156 f'<br><code class="muted">{_esc(str(task.get("last_error") or "")[:200])}</code>'
157 )
158 elif task.get("last_error") and last is None:
159 last_cell = (f'{last_cell} <span class="muted">(last error: '
160 f'{_esc(str(task.get("last_error"))[:120])})</span>')
161 status = str(task.get("status") or "")
162 toggle = ("pause" if status == "active" else "resume")
163 english = describe_schedule(task.get("schedule"), task.get("type"))
164 schedule_cell = (
165 (f"<strong>{_esc(english)}</strong><br>" if english else "")
166 + f"<code class=\"muted\" title=\"minute hour day-of-month month day-of-week\">"
167 f"{_esc(task.get('schedule'))}</code>"
168 + (f" <span class=\"muted\">{_esc(task.get('type'))}</span>" if not english else "")
169 )
170 # A package that declares a schedule says WHY it exists; showing it
171 # here is the difference between a board of cron strings and a board
172 # an operator can reason about at 3am.
173 description = str(task.get("description") or "")
174 out.append(
175 "<tr>"
176 f"<td><code>{_esc(tid)}</code>"
177 + (f"<br><span class=\"muted\">{_esc(description)}</span>" if description else "")
178 + "</td>"
179 f"<td><code>{_esc(task.get('object_id'))}</code>.{_esc(task.get('method', 'POST'))}</td>"
180 f"<td>{schedule_cell}</td>"
181 f"<td class=\"{'ok' if status == 'active' else 'warn'}\">{_esc(status)}</td>"
182 f"<td>{_when(task.get('next_run'))}</td>"
183 f"<td>{last_cell}</td>"
184 f"<td>{_esc(task.get('run_count') or 0)}</td>"
185 "<td>"
186 f"<button data-act=\"run_now\" data-key=\"{_esc(task['_key'])}\">Run now</button> "
187 f"<button data-act=\"{toggle}\" data-key=\"{_esc(task['_key'])}\">{toggle.capitalize()}</button>"
188 "</td>"
189 "</tr>"
190 )
191 return "".join(out)
192
193
194def _run_rows_html(runs):
195 if runs is None:
196 return ('<tr><td colspan="6" class="warn">scheduler_runs collection not installed '
197 "&mdash; reinstall the system-dashboard package to record run history.</td></tr>")
198 if not runs:
199 return '<tr><td colspan="6" class="muted">No runs recorded yet.</td></tr>'
200 out = []
201 for run in runs[:_RUNS_SHOWN]:
202 ok = run.get("ok") == "true"
203 detail = run.get("result") if ok else run.get("error")
204 detail_html = ""
205 if detail:
206 label = "result" if ok else _esc(run.get("error_type") or "error")
207 detail_html = (f"<details><summary>{label}</summary>"
208 f"<pre>{_esc(detail)}</pre></details>")
209 out.append(
210 "<tr>"
211 f"<td>{_esc(run.get('started_at', ''))[:19]}</td>"
212 f"<td><code>{_esc(run.get('task_id'))}</code></td>"
213 f"<td><code>{_esc(run.get('object_id'))}</code></td>"
214 f"<td>{'<span class=ok>&#10003; ok</span>' if ok else '<span class=bad>&#10007; failed</span>'}</td>"
215 f"<td>{_esc(run.get('duration_ms'))}ms</td>"
216 f"<td>{detail_html}</td>"
217 "</tr>"
218 )
219 return "".join(out)
220
221
222_SCRIPT = """
223document.addEventListener('click', async (e) => {
224 const btn = e.target.closest('button[data-act]');
225 if (!btn) return;
226 btn.disabled = true;
227 const resp = await fetch('/scheduler', {
228 method: 'POST',
229 headers: {'Content-Type': 'application/json'},
230 body: JSON.stringify({action: btn.dataset.act, key: btn.dataset.key}),
231 });
232 if (!resp.ok) { alert('Action failed: ' + resp.status); btn.disabled = false; return; }
233 location.reload();
234});
235let reloadTimer = null;
236function queueReload() {
237 if (reloadTimer) return;
238 reloadTimer = setTimeout(() => location.reload(), 400);
239}
240function trySubscribe() {
241 if (window.dbbasicSubscribe) { window.dbbasicSubscribe('scheduler_runs', queueReload); }
242 else { setTimeout(trySubscribe, 1500); }
243}
244trySubscribe();
245setTimeout(() => location.reload(), 60000);
246"""
247
248
249def _page(body, *, title="Scheduler"):
250 return {
251 "content_type": "text/html; charset=utf-8",
252 "body": f"""<!doctype html>
253<html lang="en">
254<head>
255<meta charset="utf-8">
256<meta name="viewport" content="width=device-width, initial-scale=1">
257<title>{title}</title>
258<link rel="stylesheet" href="/style">
259<style>
260.wrap {{ max-width: 1100px; margin: 0 auto; padding: 1.25rem; }}
261table {{ width: 100%; border-collapse: collapse; }}
262th, td {{ text-align: left; padding: 0.45rem 0.6rem; border-bottom: 1px solid var(--line, #333); vertical-align: top; }}
263th {{ font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted, #999); }}
264.muted {{ color: var(--muted, #999); }}
265.ok {{ color: var(--positive, #52d273); }}
266.bad {{ color: var(--danger, #ff6b6b); }}
267.warn {{ color: var(--warning, #f1b747); }}
268.tiles {{ display: flex; gap: 0.75rem; flex-wrap: wrap; margin: 1rem 0; }}
269.tile {{ background: var(--panel, #1a1a22); border: 1px solid var(--line, #333); border-radius: 8px; padding: 0.6rem 1rem; min-width: 130px; }}
270.tile .n {{ font-size: 1.3rem; font-weight: 600; }}
271.tile .l {{ font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted, #999); }}
272h2 {{ font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted, #999); margin: 1.5rem 0 0.5rem; }}
273pre {{ white-space: pre-wrap; max-width: 480px; font-size: 0.75rem; margin: 0.3rem 0 0; }}
274details summary {{ cursor: pointer; }}
275button {{ cursor: pointer; }}
276</style>
277</head>
278<body>
279<script src="/nav"></script>
280<div class="wrap">
281<h1>Scheduler</h1>
282{body}
283</div>
284</body>
285</html>""",
286 }
287
288
289def GET(request):
290 identity = request.get("_identity") or {}
291 user_id = identity.get("user_id")
292 if "admin" not in (identity.get("roles") or []):
293 prompt = ('<a href="/login?next=/scheduler">Sign in</a> with an admin account to see '
294 "scheduled tasks and their run history."
295 if not user_id else
296 "You are signed in, but the scheduler board needs an admin role.")
297 return _page(f'<p class="muted">{prompt}</p>')
298
299 tasks, invalid = _tasks()
300 runs = _runs()
301 latest_by_task = {}
302 failures_24h = runs_24h = 0
303 if runs:
304 cutoff = datetime.fromtimestamp(time.time() - 86400, tz=timezone.utc).isoformat()
305 for run in runs:
306 tid = str(run.get("task_id") or "")
307 if tid and tid not in latest_by_task:
308 latest_by_task[tid] = run # runs sorted newest-first
309 if (run.get("started_at") or "") >= cutoff:
310 runs_24h += 1
311 if run.get("ok") != "true":
312 failures_24h += 1
313
314 now = int(time.time())
315 due = sum(1 for t in tasks
316 if t.get("status") == "active" and (t.get("next_run") or 0) and int(t.get("next_run") or 0) <= now)
317 tiles = (
318 f'<div class="tiles">'
319 f'<div class="tile"><div class="n">{sum(1 for t in tasks if t.get("status") == "active")}</div><div class="l">Active tasks</div></div>'
320 f'<div class="tile"><div class="n">{due}</div><div class="l">Due now</div></div>'
321 f'<div class="tile"><div class="n">{runs_24h}</div><div class="l">Runs (24h)</div></div>'
322 f'<div class="tile"><div class="n {"bad" if failures_24h else ""}">{failures_24h}</div><div class="l">Failures (24h)</div></div>'
323 + (f'<div class="tile"><div class="n warn">{invalid}</div><div class="l">Invalid entries</div></div>' if invalid else "")
324 + "</div>"
325 )
326 body = f"""{tiles}
327<h2>Tasks</h2>
328<table>
329<thead><tr><th>Task</th><th>Target</th><th>Schedule</th><th>Status</th><th>Next Run</th><th>Last Run</th><th>Runs</th><th>Actions</th></tr></thead>
330<tbody>{_task_rows_html(tasks, latest_by_task)}</tbody>
331</table>
332<p class="muted" style="font-size:0.75rem;margin:0.5rem 0 0">
333Cron fields are <code>minute hour day-of-month month day-of-week</code>
334(all times UTC). <code>*</code> means every, <code>*/5</code> means every 5th.
335</p>
336<h2>Recent Runs</h2>
337<table>
338<thead><tr><th>Started</th><th>Task</th><th>Target</th><th>Outcome</th><th>Duration</th><th>Detail</th></tr></thead>
339<tbody>{_run_rows_html(runs)}</tbody>
340</table>
341<script>{_SCRIPT}</script>"""
342 return _page(body)
343
344
345def POST(request):
346 identity = request.get("_identity") or {}
347 if "admin" not in (identity.get("roles") or []):
348 return {"status": 403, "error": "Scheduler actions require an admin session."}
349
350 action = str(request.get("action") or "").strip()
351 key = str(request.get("key") or "").strip()
352 if action not in ("run_now", "pause", "resume") or not key.startswith(_TASK_PREFIX):
353 return {"status": 400, "error": "action must be run_now|pause|resume with a task_* key"}
354
355 manager = object_state.ObjectStateManager("scheduler", base_dir=_base_dir())
356 raw = manager.get(key)
357 if not raw:
358 return {"status": 404, "error": f"No such task entry: {key}"}
359 try:
360 task = json.loads(raw)
361 except (ValueError, TypeError):
362 return {"status": 409, "error": f"Task entry is not valid JSON: {key}"}
363
364 if action == "run_now":
365 task["next_run"] = int(time.time())
366 task["status"] = "active"
367 elif action == "pause":
368 task["status"] = "paused"
369 else: # resume
370 task["status"] = "active"
371 task["next_run"] = None # daemon recomputes from the schedule
372 manager.set(key, json.dumps(task))
373 if _logger:
374 _logger.info("scheduler task action", action=action, key=key,
375 actor=identity.get("user_id"))
376 return {"status": 200, "ok": True, "action": action, "key": key,
377 "next_run": task.get("next_run"), "task_status": task.get("status")}