diff --git a/core/src/main/java/dev/puicore/modbridge/core/bds/BdsInstaller.java b/core/src/main/java/dev/puicore/modbridge/core/bds/BdsInstaller.java index 747655d..6a5de05 100644 --- a/core/src/main/java/dev/puicore/modbridge/core/bds/BdsInstaller.java +++ b/core/src/main/java/dev/puicore/modbridge/core/bds/BdsInstaller.java @@ -275,6 +275,8 @@ public static void rollback(Path bds, String backupId, boolean confirmedStopped) } catch (IOException e) { throw new InstallException("元に戻したが、その間に BDS が起動した可能性がある。BDS を止めてから、もう一度 rollback する", e); } + } catch (ReplacementCleanupException e) { + throw new InstallException(e.getMessage(), e); } catch (IOException | RuntimeException e) { throw new InstallException("元に戻せない(" + message(e) + ")。バックアップ " + backupId + " は残っている", e); } @@ -549,86 +551,150 @@ private static Backup readBackup(Path root, String id) throws IOException { } /** - * バックアップから戻す。検査は {@link #readBackup} で済ませてある。 - * - * @param fullWorld true ならワールドのフォルダーごと戻す(rollback)。false なら、ワールドのうち配置で変える - * 2 つの JSON だけを戻す(配置の失敗時。ワールドの DB はロック中で、配置では触らないため) + * バックアップから戻す。配置失敗時は、ワールドのうち配置で触るパック一覧だけを復旧する。 */ - private static void restore(Path root, Backup b, boolean fullWorld) throws IOException { - for (var e : b.existed().entrySet()) { - String rel = e.getKey(); - Path target = root.resolve(rel); - Path saved = e.getValue() ? b.dir().resolve(rel) : null; - if (rel.startsWith("worlds/") && !fullWorld) { - for (String json : List.of("world_behavior_packs.json", "world_resource_packs.json")) { - Path s = saved == null ? null : saved.resolve(json); - if (s != null && Files.isRegularFile(s)) { - // 一時ファイルに写してから置き換える(途中で止まっても JSON が消えたままにならない) - Path tmp = Files.createTempFile(target, "." + json, ".tmp"); - try { - Files.copy(s, tmp, StandardCopyOption.REPLACE_EXISTING); - move(tmp, target.resolve(json)); - } finally { - Files.deleteIfExists(tmp); - } - } else { - Files.deleteIfExists(target.resolve(json)); - } + private static void restore(Path root, Backup backup, boolean fullWorld) throws IOException { + List replacements = new ArrayList<>(); + for (var entry : backup.existed().entrySet()) { + String relative = entry.getKey(); + Path target = root.resolve(relative); + Path saved = entry.getValue() ? backup.dir().resolve(relative) : null; + boolean isWorld = relative.startsWith("worlds/"); + if (isWorld && !fullWorld) { + for (String name : List.of("world_behavior_packs.json", "world_resource_packs.json")) { + Path savedList = saved.resolve(name); // バックアップにはワールドが必ずある + replacements.add(new Replacement(target.resolve(name), + Files.isRegularFile(savedList) ? savedList : null, false, false)); } - continue; + } else { + boolean recreateDbLock = isWorld && Files.isRegularFile(target.resolve("db/LOCK")); + replacements.add(new Replacement(target, saved, true, recreateDbLock)); } - // ロックファイルはバックアップしないので、戻す前にあったら作り直す(LevelDB も無ければ作るが、元の形に揃える) - replaceTree(target, saved, rel.startsWith("worlds/") && Files.isRegularFile(target.resolve("db").resolve("LOCK"))); } + replaceAll(replacements); } - /** - * {@code target} を {@code source} の複製で置き換える({@code source} が null なら消す)。 - * 先に一時フォルダーへ複製してから入れ替えるので、複製に失敗しても {@code target} は元のまま残る。 - */ - private static void replaceTree(Path target, Path source, boolean recreateDbLock) throws IOException { - Path parent = target.getParent(); - Files.createDirectories(parent); - String name = target.getFileName().toString(); - Path staged = null; - Path old = null; + /** 元が無かった対象は source が null。 */ + private record Replacement(Path target, Path source, boolean directory, boolean recreateDbLock) {} + + private static void replaceAll(List replacements) throws IOException { + List swaps = new ArrayList<>(); try { - if (source != null) { - staged = Files.createTempDirectory(parent, "." + name + ".restore"); - copyTree(source, staged, false); - if (recreateDbLock && Files.isDirectory(staged.resolve("db")) && !Files.exists(staged.resolve("db").resolve("LOCK"))) { - Files.createFile(staged.resolve("db").resolve("LOCK")); - } + for (Replacement replacement : replacements) { + var swap = new ReplacementSwap(replacement.target()); + swaps.add(swap); + swap.prepare(replacement); } - if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { - old = parent.resolve("." + name + ".old-" + Long.toHexString(System.nanoTime())); - move(target, old); + for (ReplacementSwap swap : swaps) { + swap.install(); } - if (staged != null) { + } catch (IOException | RuntimeException failure) { + List notRestored = new ArrayList<>(); + for (ReplacementSwap swap : swaps.reversed()) { try { - move(staged, target); - staged = null; - } catch (IOException e) { - if (old != null) { - Path keep = old; - old = null; // 元に戻せなくても、旧フォルダーは消さない - try { - move(keep, target); - } catch (IOException restore) { - e.addSuppressed(restore); - throw new IOException("入れ替えに失敗し、元のフォルダーも戻せなかった。元のフォルダーは " + keep.getFileName() - + " に残している", e); - } - } - throw e; + swap.undo(); + } catch (IOException | RuntimeException undo) { + failure.addSuppressed(undo); + notRestored.add(swap.original == null ? swap.target.getFileName().toString() + : swap.original.getParent().getFileName() + "/" + swap.original.getFileName()); + } + try { + swap.discardStaged(); + } catch (IOException | RuntimeException cleanup) { + failure.addSuppressed(cleanup); } } - } finally { + if (!notRestored.isEmpty()) { + throw new IOException("操作前の状態に戻せなかった。対象または退避先: " + String.join("、", notRestored), failure); + } + throw failure; + } + + IOException cleanupFailure = null; + for (ReplacementSwap swap : swaps) { + if (swap.original == null) { + continue; + } + try { + deleteTree(swap.original); + } catch (IOException | RuntimeException e) { + var failure = new IOException("退避先 " + swap.original.getFileName() + " を削除できない", e); + if (cleanupFailure == null) { + cleanupFailure = failure; + } else { + cleanupFailure.addSuppressed(failure); + } + } + } + if (cleanupFailure != null) { + throw new ReplacementCleanupException(cleanupFailure); + } + } + + private static final class ReplacementCleanupException extends IOException { + private static final long serialVersionUID = 1L; + + ReplacementCleanupException(IOException cause) { + super("入れ替えは完了したが、" + cause.getMessage(), cause); + } + } + + private static final class ReplacementSwap { + private final Path target; + private Path staged; + private Path original; + private boolean installed; + + ReplacementSwap(Path target) { + this.target = target; + } + + void prepare(Replacement replacement) throws IOException { + Path parent = target.getParent(); + String prefix = "." + target.getFileName() + ".restore"; + Files.createDirectories(parent); + if (replacement.source() == null) { + return; + } + if (replacement.directory()) { + staged = Files.createTempDirectory(parent, prefix); + copyTree(replacement.source(), staged, false); + Path dbLock = staged.resolve("db/LOCK"); + if (replacement.recreateDbLock() && Files.isDirectory(dbLock.getParent()) && !Files.exists(dbLock)) { + Files.createFile(dbLock); + } + } else { + staged = Files.createTempFile(parent, prefix, ".tmp"); + Files.copy(replacement.source(), staged, StandardCopyOption.REPLACE_EXISTING); + } + } + + void install() throws IOException { + if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { + Path aside = target.resolveSibling("." + target.getFileName() + ".old-" + Long.toHexString(System.nanoTime())); + move(target, aside); + original = aside; + } if (staged != null) { - deleteTree(staged); + move(staged, target); + installed = true; } - if (old != null) { - deleteTree(old); + } + + void undo() throws IOException { + if (installed) { + move(target, staged); + installed = false; + } + if (original != null) { + move(original, target); + original = null; + } + } + + void discardStaged() throws IOException { + if (staged != null && !installed) { + deleteTree(staged); } } } @@ -648,7 +714,7 @@ private static void writePackDir(Path parent, String name, Pack pack) throws IOE Files.write(p, f.getValue()); } // 書き終えたものと入れ替える(途中で失敗しても、元のフォルダーは残る) - replaceTree(parent.resolve(name), tmp, false); + replaceAll(List.of(new Replacement(parent.resolve(name), tmp, true, false))); } finally { deleteTree(tmp); } diff --git a/core/src/test/java/dev/puicore/modbridge/core/bds/BdsInstallerTest.java b/core/src/test/java/dev/puicore/modbridge/core/bds/BdsInstallerTest.java index 5f1b978..03e1bb8 100644 --- a/core/src/test/java/dev/puicore/modbridge/core/bds/BdsInstallerTest.java +++ b/core/src/test/java/dev/puicore/modbridge/core/bds/BdsInstallerTest.java @@ -16,6 +16,7 @@ import java.nio.channels.FileLock; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; @@ -276,6 +277,48 @@ private Map contentsWithoutLockFile() throws IOException { assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.rollback(bds, id, false)); } + @Test + void 復旧用のコピーをすべて用意できなければ現在のワールドとパックを変えない() throws Exception { + BdsInstaller.apply(bds, packs, null, true); + Map initial = restoredContents(); + compilePacks(packs, "next_ingot"); + String id = BdsInstaller.apply(bds, packs, null, true); + Files.writeString(world.resolve("db/state"), "after update"); + Path blockedParent = bds.resolve("resource_packs"); + Path movedAside = dir.resolve("resource_packs_moved_aside"); + Files.move(blockedParent, movedAside); + Files.writeString(blockedParent, "file blocks restore staging"); + Map before = snapshot(); + + assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.rollback(bds, id, true)); + assertEquals(before, snapshot()); + Files.delete(blockedParent); + Files.move(movedAside, blockedParent); + BdsInstaller.rollback(bds, id, true); + assertEquals(initial, restoredContents()); + } + + @Test + @EnabledOnOs(OS.WINDOWS) + void 復旧の最後にワールドの移動に失敗したら交換済みのパックも戻す() throws Exception { + Path worldFile = world.resolve("level.dat"); + Files.writeString(worldFile, "initial world"); + BdsInstaller.apply(bds, packs, null, true); + Map initial = restoredContents(); + compilePacks(packs, "next_ingot"); + String id = BdsInstaller.apply(bds, packs, null, true); + Files.writeString(worldFile, "world after update"); + Map before = snapshot(); + var denyDelete = (OpenOption) Class.forName("com.sun.nio.file.ExtendedOpenOption").getField("NOSHARE_DELETE").get(null); + try (var reader = FileChannel.open(worldFile, StandardOpenOption.READ, denyDelete)) { + assertTrue(reader.isOpen()); + assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.rollback(bds, id, true)); + } + assertEquals(before, snapshot()); + BdsInstaller.rollback(bds, id, true); + assertEquals(initial, restoredContents()); + } + @Test void 配置の途中で失敗したら元に戻す() throws IOException { Files.writeString(world.resolve("world_resource_packs.json"), "{\"not\":\"an array\"}"); diff --git a/docs/adr/0007-bds-install-and-rollback.md b/docs/adr/0007-bds-install-and-rollback.md index cf99b9f..53111bc 100644 --- a/docs/adr/0007-bds-install-and-rollback.md +++ b/docs/adr/0007-bds-install-and-rollback.md @@ -41,7 +41,7 @@ - **停止の確認**: `--confirm-stopped` の明示に加えて、`db/LOCK` があれば LevelDB のロックを取れるか確かめる。Windows では `MANIFEST-<番号>` と `<番号>.log` も、書き込みを共有しない読み取りモードで開く。開いている書き込みハンドルがあれば断る。読み取りは共有するため、配置中にハンドルを保持したままバックアップできる。RP/BP は BDS が共有するため、対象に加えて同じ `worlds/` にあるほかの実フォルダーの DB も確認する。DB がまだ無いワールドでは、明示だけを使う。[BDS の共有パック](https://learn.microsoft.com/ja-jp/minecraft/creator/documents/bedrockserver/getting-started?view=minecraft-bedrock-stable) - **パックの組み合わせ**: BP の manifest にある RP への依存 UUID・版と、提供された RP のヘッダーを照合する。組が違えば dry-run と apply の両方で拒否する。apply は検査した組を使って配置する。Script API のモジュール依存を含む BP も同じ検査を通す。[Bedrock のパック manifest](https://learn.microsoft.com/en-us/minecraft/creator/reference/content/addonsreference/packmanifest) - **バックアップ**: 配置の前に、ワールドのフォルダー全体・自分のパックのフォルダー・2 つの JSON を `modbridge-backups//` に保存する。何があり、何が無かったかを `backup.json` に記録する。`db/LOCK` は保存しない(ロック中で読めない場合があり、LevelDB が作り直すため)。 -- **入れ替え**: パックのフォルダーもワールドも、一時フォルダーに書き終えてから入れ替える。複製の途中で失敗しても、元のフォルダーは残る。入れ替えに失敗し、元のフォルダーを戻すのにも失敗したときは、元のフォルダーを消さずに残し、その名前を示す。JSON を戻すときも、一時ファイルを経由する。 +- **入れ替え**: 復旧対象のパック、ワールド、JSON は、必要な複製をすべて用意してから入れ替える。途中で失敗した場合は、入れ替え済みの対象も操作前の状態に戻す。戻せなかった元のファイルやフォルダーは消さず、退避先の名前を表示する。入れ替え完了後に退避先の削除だけが失敗した場合は、復旧済みであることを表示する。 - **失敗時の復旧**: 配置の途中で失敗したら、配置で変えたもの(パックのフォルダーと 2 つの JSON)をバックアップから戻す。ワールドの DB はロック中で、配置では触らないので戻さない。復旧にも失敗したら、バックアップの ID を示して rollback を促す。 - **rollback**: ロックで停止を確かめてから、ワールドのフォルダーごと戻す。 - ワールドのフォルダーを入れ替えるときは、対象ワールドのロックを放す。Windows では、開いているファイルを含むフォルダーを動かせないため。入れ替え後に対象のロックを確かめ、BDS が起動していたら知らせる。ほかのワールドのロックは復旧中も保持する。