lib.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. declare(strict_types=1);
  3. // Shared helpers for the backup server. Included by upload.php and manage.php.
  4. $backupServerConfigFile = __DIR__ . "/config.php";
  5. if (is_file($backupServerConfigFile)) {
  6. require_once $backupServerConfigFile;
  7. }
  8. if (!defined("BACKUP_SERVER_RETENTION")) {
  9. define("BACKUP_SERVER_RETENTION", 30);
  10. }
  11. if (!defined("BACKUP_SERVER_BACKUP_DIR")) {
  12. define("BACKUP_SERVER_BACKUP_DIR", __DIR__ . "/backups/");
  13. }
  14. if (!defined("BACKUP_SERVER_INDEX_FILE")) {
  15. define("BACKUP_SERVER_INDEX_FILE", rtrim((string) BACKUP_SERVER_BACKUP_DIR, "/\\") . "/index.json");
  16. }
  17. if (!defined("BACKUP_SERVER_SETTINGS_FILE")) {
  18. define("BACKUP_SERVER_SETTINGS_FILE", rtrim((string) BACKUP_SERVER_BACKUP_DIR, "/\\") . "/settings.json");
  19. }
  20. if (!defined("BACKUP_SERVER_S3_ENABLED")) {
  21. define("BACKUP_SERVER_S3_ENABLED", false);
  22. }
  23. if (!defined("BACKUP_SERVER_S3_ENDPOINT")) {
  24. define("BACKUP_SERVER_S3_ENDPOINT", "");
  25. }
  26. if (!defined("BACKUP_SERVER_S3_REGION")) {
  27. define("BACKUP_SERVER_S3_REGION", "");
  28. }
  29. if (!defined("BACKUP_SERVER_S3_BUCKET")) {
  30. define("BACKUP_SERVER_S3_BUCKET", "");
  31. }
  32. if (!defined("BACKUP_SERVER_S3_PREFIX")) {
  33. define("BACKUP_SERVER_S3_PREFIX", "");
  34. }
  35. if (!defined("BACKUP_SERVER_S3_ACCESS_KEY")) {
  36. define("BACKUP_SERVER_S3_ACCESS_KEY", "");
  37. }
  38. if (!defined("BACKUP_SERVER_S3_SECRET_KEY")) {
  39. define("BACKUP_SERVER_S3_SECRET_KEY", "");
  40. }
  41. if (!defined("BACKUP_SERVER_S3_PATH_STYLE")) {
  42. define("BACKUP_SERVER_S3_PATH_STYLE", false);
  43. }
  44. if (!defined("BACKUP_SERVER_S3_TIMEOUT")) {
  45. define("BACKUP_SERVER_S3_TIMEOUT", 120);
  46. }
  47. if (!defined("BACKUP_SERVER_S3_RETENTION")) {
  48. define("BACKUP_SERVER_S3_RETENTION", 365);
  49. }
  50. if (!defined("BACKUP_SERVER_LOG_FILE")) {
  51. define("BACKUP_SERVER_LOG_FILE", rtrim((string) BACKUP_SERVER_BACKUP_DIR, "/\\") . "/s3.log");
  52. }
  53. require_once __DIR__ . "/s3.php";
  54. function backupServerEnsureDirectory(string $dir): void
  55. {
  56. if (!is_dir($dir) && !mkdir($dir, 02775, true) && !is_dir($dir)) {
  57. throw new RuntimeException("Directory cannot be created: " . $dir);
  58. }
  59. @chmod($dir, 02775);
  60. }
  61. function backupServerReadJsonFile(string $file): array
  62. {
  63. if (!is_file($file)) {
  64. return [];
  65. }
  66. $decoded = json_decode((string) file_get_contents($file), true);
  67. if (!is_array($decoded)) {
  68. throw new RuntimeException("JSON file is invalid: " . basename($file));
  69. }
  70. return $decoded;
  71. }
  72. function backupServerWriteJsonFile(string $file, array $data): void
  73. {
  74. backupServerEnsureDirectory(dirname($file));
  75. $json = json_encode(
  76. $data,
  77. JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
  78. );
  79. if ($json === false) {
  80. throw new RuntimeException("JSON cannot be encoded.");
  81. }
  82. $tmpFile = $file . ".tmp";
  83. if (file_put_contents($tmpFile, $json . PHP_EOL, LOCK_EX) === false) {
  84. throw new RuntimeException("JSON cannot be written.");
  85. }
  86. @chmod($tmpFile, 0664);
  87. if (!rename($tmpFile, $file)) {
  88. @unlink($tmpFile);
  89. throw new RuntimeException("JSON cannot be saved.");
  90. }
  91. @chmod($file, 0664);
  92. }
  93. function backupServerReadIndex(): array
  94. {
  95. $index = backupServerReadJsonFile((string) BACKUP_SERVER_INDEX_FILE);
  96. $backups = isset($index["backups"]) && is_array($index["backups"])
  97. ? $index["backups"]
  98. : [];
  99. return ["backups" => array_values($backups)];
  100. }
  101. function backupServerWriteIndex(array $backups): void
  102. {
  103. backupServerWriteJsonFile((string) BACKUP_SERVER_INDEX_FILE, [
  104. "backups" => array_values($backups),
  105. ]);
  106. }
  107. function backupServerValidateInstance(string $instance): string
  108. {
  109. $instance = trim($instance);
  110. if (
  111. $instance === "" ||
  112. strlen($instance) > 120 ||
  113. preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]*$/', $instance) !== 1
  114. ) {
  115. throw new RuntimeException("Invalid instance identifier.");
  116. }
  117. return $instance;
  118. }
  119. function backupServerInstanceDir(string $instance): string
  120. {
  121. return rtrim((string) BACKUP_SERVER_BACKUP_DIR, "/\\") . DIRECTORY_SEPARATOR . $instance;
  122. }
  123. function backupServerBackupPath(string $instance, string $filename): string
  124. {
  125. return backupServerInstanceDir($instance) . DIRECTORY_SEPARATOR . $filename;
  126. }
  127. function backupServerGetSettings(): array
  128. {
  129. $settings = backupServerReadJsonFile((string) BACKUP_SERVER_SETTINGS_FILE);
  130. $retention = isset($settings["retention"])
  131. ? max(1, (int) $settings["retention"])
  132. : max(1, (int) BACKUP_SERVER_RETENTION);
  133. $s3Retention = isset($settings["s3_retention"])
  134. ? max(1, (int) $settings["s3_retention"])
  135. : max(1, (int) BACKUP_SERVER_S3_RETENTION);
  136. $instances =
  137. isset($settings["instances"]) && is_array($settings["instances"])
  138. ? $settings["instances"]
  139. : [];
  140. $allowedInstances = [];
  141. foreach ($instances as $instance) {
  142. try {
  143. $allowedInstances[] = backupServerValidateInstance((string) $instance);
  144. } catch (Throwable $exception) {
  145. continue;
  146. }
  147. }
  148. $allowedInstances = array_values(array_unique($allowedInstances));
  149. sort($allowedInstances);
  150. return [
  151. "retention" => $retention,
  152. "s3_retention" => $s3Retention,
  153. "instances" => $allowedInstances,
  154. ];
  155. }
  156. function backupServerWriteSettings(array $settings): void
  157. {
  158. $instances =
  159. isset($settings["instances"]) && is_array($settings["instances"])
  160. ? $settings["instances"]
  161. : backupServerGetSettings()["instances"];
  162. $allowedInstances = [];
  163. foreach ($instances as $instance) {
  164. $allowedInstances[] = backupServerValidateInstance((string) $instance);
  165. }
  166. $allowedInstances = array_values(array_unique($allowedInstances));
  167. sort($allowedInstances);
  168. backupServerWriteJsonFile((string) BACKUP_SERVER_SETTINGS_FILE, [
  169. "retention" => max(1, (int) ($settings["retention"] ?? BACKUP_SERVER_RETENTION)),
  170. "s3_retention" => max(1, (int) ($settings["s3_retention"] ?? BACKUP_SERVER_S3_RETENTION)),
  171. "instances" => $allowedInstances,
  172. ]);
  173. }
  174. function backupServerLog(string $message, array $context = []): void
  175. {
  176. $line = date(DATE_ATOM) . " " . $message;
  177. $encoded = @json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  178. if (is_string($encoded) && $encoded !== "[]") {
  179. $line .= " " . $encoded;
  180. }
  181. @file_put_contents((string) BACKUP_SERVER_LOG_FILE, $line . PHP_EOL, FILE_APPEND | LOCK_EX);
  182. }
  183. function backupServerUpdateIndexRecord(string $instance, string $filename, callable $update): void
  184. {
  185. $index = backupServerReadIndex();
  186. foreach ($index["backups"] as $position => $backup) {
  187. if (
  188. is_array($backup) &&
  189. ($backup["instance"] ?? "") === $instance &&
  190. ($backup["filename"] ?? "") === $filename
  191. ) {
  192. $index["backups"][$position] = $update($backup);
  193. }
  194. }
  195. backupServerWriteIndex($index["backups"]);
  196. }
  197. function backupServerIndexInstances(): array
  198. {
  199. $instances = [];
  200. foreach (backupServerReadIndex()["backups"] as $backup) {
  201. if (is_array($backup)) {
  202. $instance = (string) ($backup["instance"] ?? "");
  203. if ($instance !== "") {
  204. $instances[$instance] = true;
  205. }
  206. }
  207. }
  208. return array_keys($instances);
  209. }
  210. // Uploads every local backup of the instance that is not yet confirmed in S3,
  211. // oldest first. Serves both the immediate upload after receiving a backup and
  212. // the opportunistic retry of earlier failures. Stops at the first failure
  213. // because the endpoint is then most likely unreachable.
  214. function backupServerSyncInstanceS3(string $instance): array
  215. {
  216. $result = ["uploaded" => 0, "pending" => 0, "error" => null];
  217. if (!backupS3Enabled()) {
  218. return $result;
  219. }
  220. $pending = [];
  221. foreach (backupServerReadIndex()["backups"] as $backup) {
  222. if (!is_array($backup) || ($backup["instance"] ?? "") !== $instance) {
  223. continue;
  224. }
  225. if (!empty($backup["s3_uploaded_at"])) {
  226. continue;
  227. }
  228. $filename = basename((string) ($backup["filename"] ?? ""));
  229. if ($filename === "" || !is_file(backupServerBackupPath($instance, $filename))) {
  230. continue;
  231. }
  232. $backup["filename"] = $filename;
  233. $pending[] = $backup;
  234. }
  235. usort($pending, function ($left, $right) {
  236. return strcmp((string) ($left["uploaded_at"] ?? ""), (string) ($right["uploaded_at"] ?? ""));
  237. });
  238. foreach ($pending as $position => $backup) {
  239. $filename = (string) $backup["filename"];
  240. $key = (string) ($backup["s3_key"] ?? "");
  241. if ($key === "") {
  242. $key = backupS3ObjectKey($instance, $filename);
  243. }
  244. try {
  245. backupS3PutFile(backupServerBackupPath($instance, $filename), $key);
  246. } catch (Throwable $exception) {
  247. $result["pending"] = count($pending) - $position;
  248. $result["error"] = $exception->getMessage();
  249. backupServerUpdateIndexRecord($instance, $filename, function (array $record) use ($key, $exception) {
  250. $record["s3_key"] = $key;
  251. $record["s3_last_error"] = $exception->getMessage();
  252. $record["s3_last_attempt_at"] = date(DATE_ATOM);
  253. return $record;
  254. });
  255. backupServerLog("S3 upload failed", [
  256. "instance" => $instance,
  257. "filename" => $filename,
  258. "key" => $key,
  259. "error" => $exception->getMessage(),
  260. ]);
  261. return $result;
  262. }
  263. backupServerUpdateIndexRecord($instance, $filename, function (array $record) use ($key) {
  264. $record["s3_key"] = $key;
  265. $record["s3_uploaded_at"] = date(DATE_ATOM);
  266. unset($record["s3_last_error"], $record["s3_last_attempt_at"], $record["s3_expired"]);
  267. return $record;
  268. });
  269. $result["uploaded"]++;
  270. }
  271. return $result;
  272. }
  273. // Applies both retention tiers for one instance. S3 keeps the newest
  274. // s3_retention archived backups; local keeps the newest retention copies but
  275. // never deletes a file whose S3 upload is still pending.
  276. function backupServerApplyRetention(string $instance): void
  277. {
  278. $index = backupServerReadIndex();
  279. $settings = backupServerGetSettings();
  280. $s3Enabled = backupS3Enabled();
  281. $instanceBackups = [];
  282. $otherBackups = [];
  283. foreach ($index["backups"] as $backup) {
  284. if (!is_array($backup)) {
  285. continue;
  286. }
  287. if (($backup["instance"] ?? "") === $instance) {
  288. $instanceBackups[] = $backup;
  289. } else {
  290. $otherBackups[] = $backup;
  291. }
  292. }
  293. usort($instanceBackups, function ($left, $right) {
  294. return strcmp((string) ($right["uploaded_at"] ?? ""), (string) ($left["uploaded_at"] ?? ""));
  295. });
  296. if ($s3Enabled) {
  297. $archivedSeen = 0;
  298. foreach ($instanceBackups as $position => $backup) {
  299. if (empty($backup["s3_uploaded_at"])) {
  300. continue;
  301. }
  302. $archivedSeen++;
  303. if ($archivedSeen <= $settings["s3_retention"]) {
  304. continue;
  305. }
  306. $filename = basename((string) ($backup["filename"] ?? ""));
  307. $key = (string) ($backup["s3_key"] ?? "");
  308. if ($key === "" && $filename !== "") {
  309. $key = backupS3ObjectKey($instance, $filename);
  310. }
  311. try {
  312. if ($key !== "") {
  313. backupS3DeleteObject($key);
  314. }
  315. } catch (Throwable $exception) {
  316. backupServerLog("S3 retention delete failed", [
  317. "instance" => $instance,
  318. "filename" => $filename,
  319. "key" => $key,
  320. "error" => $exception->getMessage(),
  321. ]);
  322. continue;
  323. }
  324. unset($backup["s3_uploaded_at"], $backup["s3_key"]);
  325. $backup["s3_expired"] = true;
  326. $instanceBackups[$position] = $backup;
  327. }
  328. }
  329. $localSeen = 0;
  330. $kept = [];
  331. foreach ($instanceBackups as $backup) {
  332. $filename = basename((string) ($backup["filename"] ?? ""));
  333. $path = $filename !== "" ? backupServerBackupPath($instance, $filename) : "";
  334. $localExists = $path !== "" && is_file($path);
  335. $inS3 = !empty($backup["s3_uploaded_at"]);
  336. if (!$localExists) {
  337. if ($inS3) {
  338. $kept[] = $backup;
  339. }
  340. // Present in neither store: drop the orphaned record.
  341. continue;
  342. }
  343. $localSeen++;
  344. if ($localSeen <= $settings["retention"]) {
  345. $kept[] = $backup;
  346. continue;
  347. }
  348. if ($inS3) {
  349. @unlink($path);
  350. $backup["local_deleted_at"] = date(DATE_ATOM);
  351. $kept[] = $backup;
  352. continue;
  353. }
  354. if ($s3Enabled && empty($backup["s3_expired"])) {
  355. // The only copy lives locally until the S3 upload succeeds.
  356. $kept[] = $backup;
  357. continue;
  358. }
  359. // S3 disabled (legacy behavior) or the backup already aged out of S3.
  360. @unlink($path);
  361. }
  362. backupServerWriteIndex(array_merge($otherBackups, $kept));
  363. }
  364. function backupServerApplyRetentionAll(): void
  365. {
  366. foreach (backupServerIndexInstances() as $instance) {
  367. backupServerApplyRetention($instance);
  368. }
  369. }