askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
backups.py · 7.3 KB · 177 lines
| 1 | """system_backups -- the scheduled-backup page an admin lands on from the |
| 2 | urgent attention badge. |
| 3 | |
| 4 | Shows object_backup_schedule.status in words: is it on, where it writes, |
| 5 | the last good backup (when, how big, how long, how much was new), the last |
| 6 | restore test (when, which snapshot, what it checked, what differed), and |
| 7 | every problem. Two buttons call the admin API (POST |
| 8 | /admin/backups/scheduled/run and /test) with the visitor's own session, so |
| 9 | the page itself holds no power the visitor does not. |
| 10 | |
| 11 | Identity posture: public execute like every page object; anonymous and |
| 12 | non-admin visitors get a prompt and no data. |
| 13 | """ |
| 14 | |
| 15 | import html |
| 16 | import os |
| 17 | from datetime import datetime, timezone |
| 18 | |
| 19 | import object_backup_schedule |
| 20 | |
| 21 | |
| 22 | def _base_dir(): |
| 23 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 24 | |
| 25 | |
| 26 | def _esc(value): |
| 27 | return html.escape(str(value if value is not None else "")) |
| 28 | |
| 29 | |
| 30 | def _age(stamp): |
| 31 | text = str(stamp or "").replace("Z", "+00:00") |
| 32 | if not text: |
| 33 | return "never" |
| 34 | try: |
| 35 | moment = datetime.fromisoformat(text) |
| 36 | except ValueError: |
| 37 | return _esc(stamp) |
| 38 | if moment.tzinfo is None: |
| 39 | moment = moment.replace(tzinfo=timezone.utc) |
| 40 | seconds = max(0, int((datetime.now(timezone.utc) - moment).total_seconds())) |
| 41 | if seconds < 3600: |
| 42 | ago = f"{seconds // 60}m ago" |
| 43 | elif seconds < 172800: |
| 44 | ago = f"{seconds // 3600}h ago" |
| 45 | else: |
| 46 | ago = f"{seconds // 86400}d ago" |
| 47 | return f"{_esc(text[:19].replace('T', ' '))} UTC ({ago})" |
| 48 | |
| 49 | |
| 50 | def _mb(value): |
| 51 | try: |
| 52 | return f"{int(value) / (1024 * 1024):.1f} MB" |
| 53 | except (TypeError, ValueError): |
| 54 | return "—" |
| 55 | |
| 56 | |
| 57 | _SCRIPT = """ |
| 58 | document.addEventListener('click', async (e) => { |
| 59 | const btn = e.target.closest('button[data-path]'); |
| 60 | if (!btn) return; |
| 61 | btn.disabled = true; |
| 62 | const resp = await fetch(btn.dataset.path, {method: 'POST'}); |
| 63 | let body = {}; |
| 64 | try { body = await resp.json(); } catch (err) {} |
| 65 | if (!resp.ok) { alert(body.error || ('Failed: ' + resp.status)); btn.disabled = false; return; } |
| 66 | document.getElementById('note').textContent = |
| 67 | 'Started. This page reloads every 15 seconds; the result appears below when it finishes.'; |
| 68 | }); |
| 69 | setTimeout(() => location.reload(), 15000); |
| 70 | """ |
| 71 | |
| 72 | |
| 73 | def _page(body): |
| 74 | return { |
| 75 | "content_type": "text/html; charset=utf-8", |
| 76 | "body": f"""<!doctype html> |
| 77 | <html lang="en"> |
| 78 | <head> |
| 79 | <meta charset="utf-8"> |
| 80 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 81 | <title>Backups</title> |
| 82 | <link rel="stylesheet" href="/style"> |
| 83 | <style> |
| 84 | .wrap {{ max-width: 900px; margin: 0 auto; padding: 1.25rem; }} |
| 85 | table {{ width: 100%; border-collapse: collapse; }} |
| 86 | th, td {{ text-align: left; padding: 0.45rem 0.6rem; border-bottom: 1px solid var(--line, #333); vertical-align: top; }} |
| 87 | th {{ width: 30%; font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted, #999); }} |
| 88 | .muted {{ color: var(--muted, #999); }} |
| 89 | .ok {{ color: var(--positive, #52d273); }} |
| 90 | .bad {{ color: var(--danger, #ff6b6b); }} |
| 91 | .warn {{ color: var(--warning, #f1b747); }} |
| 92 | h2 {{ font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted, #999); margin: 1.5rem 0 0.5rem; }} |
| 93 | button {{ cursor: pointer; margin-right: 0.5rem; }} |
| 94 | </style> |
| 95 | </head> |
| 96 | <body> |
| 97 | <script src="/nav"></script> |
| 98 | <div class="wrap"> |
| 99 | <h1>Backups</h1> |
| 100 | {body} |
| 101 | </div> |
| 102 | </body> |
| 103 | </html>""", |
| 104 | } |
| 105 | |
| 106 | |
| 107 | def _rows(pairs): |
| 108 | return "".join(f"<tr><th>{label}</th><td>{value}</td></tr>" for label, value in pairs) |
| 109 | |
| 110 | |
| 111 | def GET(request): |
| 112 | identity = request.get("_identity") or {} |
| 113 | if "admin" not in (identity.get("roles") or []): |
| 114 | prompt = ('<a href="/login?next=/backups">Sign in</a> with an admin account to see ' |
| 115 | "the backup status." if not identity.get("user_id") else |
| 116 | "You are signed in, but the backup page needs an admin role.") |
| 117 | return _page(f'<p class="muted">{prompt}</p>') |
| 118 | |
| 119 | status = object_backup_schedule.status(_base_dir()) |
| 120 | if not status.get("enabled"): |
| 121 | return _page( |
| 122 | '<p class="warn">Scheduled backups are <strong>off</strong>. Nothing is copied ' |
| 123 | "off this box. Set <code>" |
| 124 | f"{_esc(object_backup_schedule.DESTINATION_ENV)}</code> to a mounted disk, an NFS " |
| 125 | "share or a folder another tool syncs away, and restart the daemon. See " |
| 126 | "<code>docs/scheduled-backups.md</code> in the server's source.</p>") |
| 127 | |
| 128 | problems = status.get("problems") or [] |
| 129 | verdict = ('<p class="ok"><strong>Healthy.</strong> The last backup completed and its ' |
| 130 | "restore test passed.</p>" if status.get("healthy") else |
| 131 | '<p class="bad"><strong>Needs attention.</strong></p><ul>' + "".join( |
| 132 | f'<li class="bad">{_esc(p.get("message"))}</li>' for p in problems) + "</ul>") |
| 133 | warnings = "".join(f'<p class="warn">{_esc(w)}</p>' for w in status.get("warnings") or []) |
| 134 | running = status.get("running") or {} |
| 135 | running_line = (f'<p class="muted">Running now: {_esc(running.get("kind"))} since ' |
| 136 | f'{_age(running.get("started_at"))}</p>' if running else "") |
| 137 | |
| 138 | good = status.get("last_good_backup") or {} |
| 139 | last = status.get("last_backup") or {} |
| 140 | test = status.get("last_restore_test") or {} |
| 141 | checked = test.get("checked") or {} |
| 142 | backup_rows = _rows([ |
| 143 | ("Destination", f"<code>{_esc(status.get('destination'))}</code>"), |
| 144 | ("Interval / keep", f"every {_esc(status.get('interval_seconds'))}s, " |
| 145 | f"keep {_esc(status.get('keep'))} snapshots"), |
| 146 | ("Last good backup", f"{_esc(good.get('name')) or '—'}<br>" |
| 147 | f"<span class=muted>{_age(good.get('finished_at'))}</span>"), |
| 148 | ("Size", f"{_mb(good.get('bytes'))} in {_esc(good.get('files'))} files " |
| 149 | f"({_esc(good.get('linked'))} linked, {_esc(good.get('copied'))} copied, " |
| 150 | f"{_mb(good.get('copied_bytes'))} written)" if good else "—"), |
| 151 | ("Duration", f"{_esc(good.get('total_seconds'))}s" if good else "—"), |
| 152 | ("Last attempt", ('<span class=ok>ok</span>' if last.get("ok") else |
| 153 | f'<span class=bad>failed: {_esc(last.get("error"))}</span>') |
| 154 | + f" <span class=muted>{_age(last.get('started_at'))}</span>" |
| 155 | if last else "never"), |
| 156 | ]) |
| 157 | test_rows = _rows([ |
| 158 | ("Result", ('<span class=ok>passed</span>' if test.get("ok") else |
| 159 | '<span class=bad>FAILED</span>') if test else "never run"), |
| 160 | ("Snapshot", _esc(test.get("snapshot")) or "—"), |
| 161 | ("When", _age(test.get("tested_at"))), |
| 162 | ("Checked", f"{_esc(checked.get('files'))} files, {_esc(checked.get('collections'))} " |
| 163 | f"collections, {_esc(checked.get('records'))} records, " |
| 164 | f"{_esc(checked.get('schemas'))} schemas" if checked else "—"), |
| 165 | ("Differences", "<br>".join(_esc(e) for e in test.get("errors") or []) or "none"), |
| 166 | ("Warnings", "<br>".join(_esc(w) for w in test.get("warnings") or []) or "none"), |
| 167 | ]) |
| 168 | body = f"""{verdict}{warnings}{running_line} |
| 169 | <p><button data-path="/admin/backups/scheduled/run">Back up now</button> |
| 170 | <button data-path="/admin/backups/scheduled/test">Test the newest backup now</button></p> |
| 171 | <p class="muted" id="note"></p> |
| 172 | <h2>Backups</h2> |
| 173 | <table><tbody>{backup_rows}</tbody></table> |
| 174 | <h2>Restore test</h2> |
| 175 | <table><tbody>{test_rows}</tbody></table> |
| 176 | <script>{_SCRIPT}</script>""" |
| 177 | return _page(body) |