maintenance.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. <?php
  2. /**
  3. * Maintenance: backups and software updates, both driven by the manage client
  4. * in manage-client/ (reference: https://manage.med0.de/client-docs/).
  5. *
  6. * The page holds no update or backup logic of its own — every button calls the
  7. * same documented function the CLI calls, so `php manage-client/bin/manage-client.php
  8. * backup` and the button below do exactly the same thing. The client ships a
  9. * drop-in panel of its own; this page replaces it so the backoffice keeps one
  10. * look, one login and one CSRF token.
  11. *
  12. * Results are rendered on the POST itself rather than after a redirect: an
  13. * update reports several lines (files copied, migrations run, backup location)
  14. * and a flash message holds one.
  15. */
  16. require dirname(__DIR__) . '/app/bootstrap.php';
  17. auth_require();
  18. // An installation may legitimately not carry the client — it is one folder,
  19. // and deploying by FTP works without it. Say so instead of dying on a require.
  20. if (!is_file(APP_ROOT . '/manage-client/lib/client.php')) {
  21. admin_header('Maintenance', 'maintenance');
  22. echo '<h1>Maintenance</h1><div class="card"><p class="help" style="margin:0">'
  23. . 'The backup and update client is not installed: <code>manage-client/</code> '
  24. . 'is missing. See <code>docs/SETUP.md</code>, section 5a.</p></div>';
  25. admin_footer();
  26. exit;
  27. }
  28. require_once APP_ROOT . '/manage-client/lib/client.php';
  29. $messages = [];
  30. $errors = [];
  31. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  32. csrf_verify();
  33. // Archiving media/ and uploading it runs well past the default limit.
  34. @set_time_limit(0);
  35. $action = (string)($_POST['action'] ?? '');
  36. try {
  37. if ($action === 'download') {
  38. // Validates the filename itself and throws on anything that is not
  39. // a backup of this installation.
  40. $path = manageBackupPath((string)($_POST['filename'] ?? ''));
  41. $size = filesize($path);
  42. $fh = fopen($path, 'rb');
  43. if ($size === false || $fh === false) {
  44. throw new RuntimeException('Backup file could not be opened.');
  45. }
  46. header('Content-Type: application/zip');
  47. header('Content-Disposition: attachment; filename="' . addcslashes(basename($path), '"\\') . '"');
  48. header('Content-Length: ' . $size);
  49. header('Cache-Control: private, no-store');
  50. header('X-Content-Type-Options: nosniff');
  51. fpassthru($fh);
  52. fclose($fh);
  53. exit;
  54. }
  55. if ($action === 'backup') {
  56. $messages = array_merge($messages, maintenance_backup('manual'));
  57. manageHeartbeatSendQuietly();
  58. } elseif ($action === 'update') {
  59. // Deliberately a line here rather than a feature of the client: it
  60. // stays visible that the update takes a backup first, and the
  61. // update stops if that backup cannot be written.
  62. if (!empty($_POST['backup_first'])) {
  63. $messages = array_merge($messages, maintenance_backup('update'));
  64. }
  65. $result = manageUpdateApply(['force' => !empty($_POST['force'])]);
  66. $messages[] = sprintf(
  67. 'Update deployed: %s → %s. %d files copied, %d replaced files saved to %s.',
  68. $result['from_version'] !== '' ? $result['from_version'] : 'unknown',
  69. $result['to_version'],
  70. $result['copied'],
  71. $result['backed_up'],
  72. $result['backup_dir'],
  73. );
  74. // Files are deployed even when the hook failed; that difference is
  75. // the whole point of reporting it separately.
  76. $hook = is_array($result['hook'] ?? null) ? $result['hook'] : [];
  77. $applied = $hook['migrations']['applied'] ?? [];
  78. if ($applied !== []) {
  79. $messages[] = 'Migrations run: ' . implode(', ', $applied);
  80. }
  81. if ($hook !== [] && empty($hook['success'])) {
  82. $errors[] = empty($hook['failed_migration'])
  83. ? 'The files are deployed, but the post-update step failed: '
  84. . (string)($hook['error'] ?? 'unknown')
  85. : 'The files are deployed, but migration "' . (string)$hook['failed_migration']
  86. . '" failed: ' . (string)($hook['error'] ?? 'unknown')
  87. . ' Remaining migrations were not attempted — fix the cause, then use "Run migrations" below.';
  88. }
  89. manageHeartbeatSendQuietly();
  90. } elseif ($action === 'migrate') {
  91. $report = manageUpdateRunMigrations();
  92. if ($report['applied'] !== []) {
  93. $messages[] = 'Migrations run: ' . implode(', ', $report['applied']);
  94. }
  95. if (!$report['success']) {
  96. $errors[] = 'Migration "' . (string)$report['failed'] . '" failed: ' . (string)$report['error'];
  97. } elseif ($report['applied'] === []) {
  98. $messages[] = 'No pending migrations.';
  99. }
  100. } elseif ($action === 'heartbeat') {
  101. $result = manageHeartbeatSend();
  102. $messages[] = 'Status reported. Current release: '
  103. . (($result['latest'] ?? '') !== '' ? (string)$result['latest'] : 'none') . '.';
  104. }
  105. } catch (Throwable $e) {
  106. $errors[] = $e->getMessage();
  107. }
  108. }
  109. /**
  110. * One backup, reported as message lines. A failed upload is a warning, not a
  111. * failure: the archive exists locally either way.
  112. */
  113. function maintenance_backup(string $trigger): array
  114. {
  115. $record = manageBackupCreate($trigger);
  116. $lines = [sprintf(
  117. 'Backup created: %s — %d files, %s.',
  118. $record['filename'],
  119. $record['file_count'],
  120. manageFormatBytes((int)$record['size']),
  121. )];
  122. foreach ($record['remote_uploads'] as $upload) {
  123. if (empty($upload['success'])) {
  124. $lines[] = 'Upload to ' . (string)$upload['target'] . ' failed: '
  125. . (string)($upload['error'] ?? 'unknown') . ' The local copy is intact.';
  126. }
  127. }
  128. return $lines;
  129. }
  130. /** An interval as something readable: 604800 -> "every 7 days". */
  131. function maintenance_interval_text(int $seconds): string
  132. {
  133. if ($seconds % 86400 === 0) {
  134. $days = intdiv($seconds, 86400);
  135. return $days === 1 ? 'daily' : 'every ' . $days . ' days';
  136. }
  137. if ($seconds % 3600 === 0) {
  138. $hours = intdiv($seconds, 3600);
  139. return $hours === 1 ? 'hourly' : 'every ' . $hours . ' hours';
  140. }
  141. return 'every ' . max(1, intdiv($seconds, 60)) . ' minutes';
  142. }
  143. // The one place that asks the manage server whether a release is waiting: it is
  144. // a network round trip, so it happens when this page is opened and nowhere else.
  145. // Never throws — an unreachable server still renders the page.
  146. $status = manageClientStatus();
  147. // State of the schedule in app/manage.php.
  148. $autoInterval = (int)MANAGE_BACKUP_AUTO_INTERVAL_SECONDS;
  149. $due = manage_due();
  150. $lastAutoBackup = 0;
  151. foreach ($status['backups'] as $backup) {
  152. if (in_array($backup['trigger'] ?? '', ['automatic', 'cron'], true)) {
  153. $lastAutoBackup = max($lastAutoBackup, strtotime((string)($backup['created_at'] ?? '')) ?: 0);
  154. }
  155. }
  156. $lastHeartbeat = (int)(json_read(manage_state_file())['heartbeat_at'] ?? 0);
  157. // An instance whose server has no release yet answers the manifest with 404.
  158. // That is a normal state — a new project, nothing published — and reads far
  159. // too much like a broken connection when it is shown as a failed check.
  160. $noReleaseYet = $status['update_error'] !== null
  161. && str_contains($status['update_error'], 'HTTP 404');
  162. $update = $status['update'];
  163. $capabilities = manageRemoteCapabilities();
  164. admin_header('Maintenance', 'maintenance');
  165. flash_render();
  166. ?>
  167. <h1>Maintenance</h1>
  168. <?php foreach ($messages as $line): ?>
  169. <div class="flash flash-ok"><?= e($line) ?></div>
  170. <?php endforeach; ?>
  171. <?php foreach ($errors as $line): ?>
  172. <div class="flash flash-error"><?= e($line) ?></div>
  173. <?php endforeach; ?>
  174. <?php if (!$status['configured']): ?>
  175. <div class="flash flash-error">
  176. Not connected to the manage server. Create an instance there, then fill in
  177. <code>MANAGE_INSTANCE</code> and <code>MANAGE_TOKEN</code> in
  178. <code>manage-client/config.php</code>. Backups can still be made locally.
  179. </div>
  180. <?php endif; ?>
  181. <div class="card">
  182. <table>
  183. <tr>
  184. <td>Installed version</td>
  185. <td><?= e($status['version'] !== '' ? $status['version'] : 'unknown') ?></td>
  186. <td class="help" style="margin:0">PHP <?= e($status['php_version']) ?></td>
  187. </tr>
  188. <tr>
  189. <td>Current release</td>
  190. <td>
  191. <?php if ($update !== null && $update['available']): ?>
  192. <span class="tag tag-lock"><?= e($update['latest']) ?> available</span>
  193. <?php elseif ($update !== null): ?>
  194. <?= e($update['latest'] !== '' ? $update['latest'] : '—') ?>
  195. <?php else: ?>
  196. —
  197. <?php endif; ?>
  198. </td>
  199. <td class="help" style="margin:0">
  200. <?php if ($noReleaseYet): ?>
  201. No release has been published on the manage server yet.
  202. <?php elseif ($status['update_error'] !== null): ?>
  203. Check failed: <?= e($status['update_error']) ?>
  204. <?php elseif ($update !== null && $update['available']): ?>
  205. Back up first, then deploy.
  206. <?php elseif ($update !== null): ?>
  207. Up to date.
  208. <?php else: ?>
  209. <?= e($status['instance'] !== '' ? $status['instance'] : 'no instance configured') ?>
  210. <?php endif; ?>
  211. </td>
  212. </tr>
  213. <tr>
  214. <td>Last backup</td>
  215. <td><?= e($status['last_backup_at'] ?? 'never') ?></td>
  216. <td class="help" style="margin:0"><?= count($status['backups']) ?> kept locally</td>
  217. </tr>
  218. <tr>
  219. <td>Release migrations</td>
  220. <td><?= count($status['pending_migrations']) ?> pending</td>
  221. <td class="help" style="margin:0">
  222. <?= $status['pending_migrations'] === []
  223. ? 'Nothing to run.'
  224. : e(implode(', ', array_column($status['pending_migrations'], 'id'))) ?>
  225. </td>
  226. </tr>
  227. </table>
  228. </div>
  229. <h2>Backup</h2>
  230. <div class="card">
  231. <p class="help" style="margin-top:0">
  232. Archives <code>data/</code> and <code>media/</code> — galleries, showreel,
  233. front page, settings — and uploads it to the manage server. Gallery photos
  234. are not included: they live in the S3 bucket, which is their own backup.
  235. Nor are <code>config/</code> credentials, because a backup can be
  236. downloaded again from the server.
  237. </p>
  238. <form method="post">
  239. <?= csrf_field() ?>
  240. <input type="hidden" name="action" value="backup">
  241. <button type="submit" style="margin:0">Back up now</button>
  242. </form>
  243. </div>
  244. <h2>Schedule</h2>
  245. <div class="card">
  246. <p class="help" style="margin-top:0">
  247. This host is assumed to have no cron, so the backoffice drives both jobs:
  248. opening any admin page past the interval starts them in the background
  249. (<code>manage-worker.php</code>). Updates are never part of that, and the
  250. release check runs only when this page is opened.
  251. </p>
  252. <table>
  253. <tr>
  254. <td>Automatic backup</td>
  255. <td><?= $autoInterval > 0 ? e(maintenance_interval_text($autoInterval)) : 'off' ?></td>
  256. <td class="help" style="margin:0">
  257. <?php if ($autoInterval <= 0): ?>
  258. <code>MANAGE_BACKUP_AUTO_INTERVAL_SECONDS</code> is 0 — only cron or the button above make backups.
  259. <?php elseif (in_array('backup', $due, true)): ?>
  260. Due now — starts on the next admin page load.
  261. <?php else: ?>
  262. Next <?= e(date('Y-m-d H:i', $lastAutoBackup + $autoInterval)) ?>.
  263. <?php endif; ?>
  264. </td>
  265. </tr>
  266. <tr>
  267. <td>Heartbeat</td>
  268. <td><?= e(maintenance_interval_text(manage_heartbeat_interval())) ?></td>
  269. <td class="help" style="margin:0">
  270. <?php if ($lastHeartbeat === 0): ?>
  271. Not sent yet.
  272. <?php else: ?>
  273. Last <?= e(date('Y-m-d H:i', $lastHeartbeat)) ?>.
  274. <?php endif; ?>
  275. </td>
  276. </tr>
  277. </table>
  278. <p class="help">
  279. If the host does offer cron, point it at
  280. <code>manage-worker.php?key=…</code> every 15 minutes instead — the key
  281. is in <code>data/worker-key.json</code>, and the jobs are the same code
  282. either way. See <code>scripts/manage-client.cron</code>.
  283. </p>
  284. </div>
  285. <h2>Update</h2>
  286. <div class="card">
  287. <?php if ($update !== null && $update['available']): ?>
  288. <p style="margin-top:0">
  289. Version <strong><?= e($update['latest']) ?></strong> is ready
  290. <?php if (!empty($update['manifest']['published_at'])): ?>
  291. (published <?= e($update['manifest']['published_at']) ?>)
  292. <?php endif; ?>.
  293. </p>
  294. <?php endif; ?>
  295. <p class="help" style="margin-top:0">
  296. Files are replaced while the site stays online, and there is no rollback:
  297. the replaced files are copied to <code>data/manage/updates/</code> for
  298. manual recovery. <code>config/</code>, <code>data/</code> and
  299. <code>media/</code> are never touched. Deleted files are not removed —
  300. an update overlays what is there.
  301. <?php if ($status['pending_migrations'] === []): ?>
  302. Afterwards, check <a href="migrate.php">Data migration</a>.
  303. <?php endif; ?>
  304. </p>
  305. <form method="post" onsubmit="return confirm('Deploy the update now? Files will be overwritten.');">
  306. <?= csrf_field() ?>
  307. <input type="hidden" name="action" value="update">
  308. <p class="help" style="margin-bottom:.4rem"><label style="display:inline;text-transform:none;letter-spacing:0">
  309. <input type="checkbox" name="backup_first" value="1" checked>
  310. Create a backup first
  311. </label></p>
  312. <p class="help" style="margin-bottom:.4rem"><label style="display:inline;text-transform:none;letter-spacing:0">
  313. <input type="checkbox" name="force" value="1">
  314. Deploy even if no newer version is offered
  315. </label></p>
  316. <button type="submit" style="margin-top:1rem"
  317. <?= $update !== null && !$update['available'] ? 'class="btn-ghost"' : '' ?>>
  318. Deploy update
  319. </button>
  320. </form>
  321. </div>
  322. <?php if ($status['pending_migrations'] !== []): ?>
  323. <h2>Pending release migrations</h2>
  324. <div class="card">
  325. <p class="help" style="margin-top:0">
  326. Shipped with a release and normally run by the update itself. These are
  327. left over — usually because one failed, or because the update ran with
  328. migrations skipped.
  329. </p>
  330. <table style="margin-bottom:1rem">
  331. <?php foreach ($status['pending_migrations'] as $migration): ?>
  332. <tr><td><?= e($migration['id']) ?></td></tr>
  333. <?php endforeach; ?>
  334. </table>
  335. <form method="post">
  336. <?= csrf_field() ?>
  337. <input type="hidden" name="action" value="migrate">
  338. <button type="submit" style="margin:0">Run migrations</button>
  339. </form>
  340. </div>
  341. <?php endif; ?>
  342. <h2>Local backups</h2>
  343. <div class="card">
  344. <?php if ($status['backups'] === []): ?>
  345. <p class="help" style="margin:0">No backup has been made yet.</p>
  346. <?php else: ?>
  347. <table>
  348. <tr>
  349. <th>File</th><th>Created</th><th>Trigger</th>
  350. <th>Files</th><th>Size</th><th>Upload</th><th></th>
  351. </tr>
  352. <?php foreach ($status['backups'] as $backup): ?>
  353. <tr>
  354. <td><?= e((string)($backup['filename'] ?? '')) ?></td>
  355. <td><?= e((string)($backup['created_at'] ?? '')) ?></td>
  356. <td><?= e((string)($backup['trigger'] ?? '')) ?></td>
  357. <td><?= (int)($backup['file_count'] ?? 0) ?></td>
  358. <td><?= e(manageFormatBytes((int)($backup['size'] ?? 0))) ?></td>
  359. <td>
  360. <?php $uploads = is_array($backup['remote_uploads'] ?? null) ? $backup['remote_uploads'] : []; ?>
  361. <?php if ($uploads === []): ?>
  362. —
  363. <?php else: foreach ($uploads as $upload): ?>
  364. <span class="tag <?= empty($upload['success']) ? 'tag-expired' : 'tag-lock' ?>">
  365. <?= e((string)($upload['target'] ?? '?')) ?><?= empty($upload['success']) ? ' failed' : '' ?>
  366. </span>
  367. <?php endforeach; endif; ?>
  368. </td>
  369. <td>
  370. <form method="post">
  371. <?= csrf_field() ?>
  372. <input type="hidden" name="action" value="download">
  373. <input type="hidden" name="filename" value="<?= e((string)($backup['filename'] ?? '')) ?>">
  374. <button type="submit" class="btn-ghost" style="margin:0;padding:.4rem 1rem">Download</button>
  375. </form>
  376. </td>
  377. </tr>
  378. <?php endforeach; ?>
  379. </table>
  380. <?php endif; ?>
  381. <p class="help">
  382. Kept locally: <?= (int)MANAGE_BACKUP_LOCAL_RETENTION ?>. Older ones are
  383. deleted here after each new backup; the manage server keeps its own,
  384. longer history.
  385. </p>
  386. </div>
  387. <?php
  388. $unsupported = [];
  389. foreach ($capabilities as $type => $capability) {
  390. if ($capability['configured'] && !$capability['available']) {
  391. $unsupported[] = $type;
  392. }
  393. }
  394. ?>
  395. <?php if ($unsupported !== []): ?>
  396. <div class="flash flash-error">
  397. Configured backup targets this server cannot use:
  398. <?= e(implode(', ', $unsupported)) ?>. Those uploads will fail.
  399. </div>
  400. <?php endif; ?>
  401. <?php foreach ($status['errors'] as $line): ?>
  402. <div class="flash flash-error"><?= e($line) ?></div>
  403. <?php endforeach; ?>
  404. <div class="card">
  405. <h2 style="margin-top:0">Report status</h2>
  406. <p class="help" style="margin-top:0">
  407. Sends version, PHP version, free disk space and the time of the last
  408. backup to the manage server. Normally an hourly cron job; this is the
  409. manual version of it.
  410. </p>
  411. <form method="post">
  412. <?= csrf_field() ?>
  413. <input type="hidden" name="action" value="heartbeat">
  414. <button type="submit" class="btn-ghost" style="margin:0">Send heartbeat</button>
  415. </form>
  416. </div>
  417. <p class="help">
  418. Same operations from the shell:
  419. <code>php manage-client/bin/manage-client.php status|check|backup|update|migrate|heartbeat</code>.
  420. See <code>docs/SETUP.md</code>.
  421. </p>
  422. <?php admin_footer(); ?>