Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
Expand All @@ -45,6 +47,7 @@
* <ul>
* <li>既定は dry-run(計画を返すだけで、何も変更しない)</li>
* <li>apply は、呼出し側が「BDS を止めた」と明示し、さらにワールドの DB のロックを取れるとき(BDS が動いていないとき)だけ行う</li>
* <li>変更操作は BDS フォルダー内の空の {@code .modbridge-bds.lock} で排他する</li>
* <li>変更の前に、ワールド・パックのフォルダー・パック一覧の JSON をバックアップする。rollback でそこから戻せる</li>
* <li>触るのは、自分のパックのフォルダー({@code behavior_packs/modbridge-bp}・{@code resource_packs/modbridge-rp})と、
* ワールドの {@code world_behavior_packs.json}・{@code world_resource_packs.json} の自分の項目だけ</li>
Expand All @@ -54,6 +57,7 @@ public final class BdsInstaller {
public static final String BP_DIR = "modbridge-bp";
public static final String RP_DIR = "modbridge-rp";
public static final String BACKUP_DIR = "modbridge-backups";
static final String OPERATION_LOCK_FILE = ".modbridge-bds.lock";
static final long MAX_PACK_BYTES = 256L << 20;
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private static final Pattern WORLD_NAME = Pattern.compile("[^/\\\\:*?\"<>|\\x00-\\x1f]{1,128}");
Expand Down Expand Up @@ -193,10 +197,12 @@ public static String apply(Path bds, Path packDir, String world, boolean confirm
Path worldDir = root.resolve("worlds").resolve(plan.world());
Pack bp = prepared.bundle().behavior();
Pack rp = prepared.bundle().resource();
try (WorldLock otherWorlds = WorldLock.acquireOthers(worldDir);
try (MutationLock mutation = MutationLock.acquire(root);
WorldLock otherWorlds = WorldLock.acquireOthers(worldDir);
WorldLock lock = WorldLock.acquire(worldDir)) {
otherWorlds.ensureHeld();
lock.ensureHeld();
mutation.ensureHeld();
String id = backup(root, plan.world());
try {
// 前回と違うパック ID で作り直した場合に備えて、いま入っているパックの UUID の項目も置き換える
Expand Down Expand Up @@ -258,9 +264,11 @@ public static void rollback(Path bds, String backupId, boolean confirmedStopped)
throw new InstallException("バックアップ " + backupId + " を使えない(" + message(e) + ")", e);
}
Path worldDir = root.resolve("worlds").resolve(b.world());
try (WorldLock otherWorlds = WorldLock.acquireOthers(worldDir)) {
try (MutationLock mutation = MutationLock.acquire(root);
WorldLock otherWorlds = WorldLock.acquireOthers(worldDir)) {
otherWorlds.ensureHeld();
WorldLock.acquire(worldDir).close();
mutation.ensureHeld();
restore(root, b, true);
try {
WorldLock.acquire(worldDir).close();
Expand All @@ -274,6 +282,67 @@ public static void rollback(Path bds, String backupId, boolean confirmedStopped)

// ---- ロック ----

/** 同じ BDS フォルダーを更新する ModBridge の処理を、プロセス間と JVM 内で排他する。 */
static final class MutationLock implements AutoCloseable {
private static final String BUSY = "この BDS フォルダーで ModBridge の配置または復旧を実行中";
private static final Set<Path> ACTIVE_ROOTS = ConcurrentHashMap.newKeySet();
private final Path root;
private FileChannel channel;
private FileLock lock;

private MutationLock(Path root) {
this.root = root;
}

static MutationLock acquire(Path root) throws IOException {
Path canonical = root.toRealPath();
// 同一 JVM の別チャネルを閉じると、既存のファイルロックまで外れる OS がある。
if (!ACTIVE_ROOTS.add(canonical)) {
throw new IOException(BUSY);
}
var mutation = new MutationLock(canonical);
try {
mutation.channel = FileChannel.open(canonical.resolve(OPERATION_LOCK_FILE), StandardOpenOption.CREATE,
StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS);
mutation.lock = mutation.channel.tryLock(0, 1, false);
if (mutation.lock == null) {
throw new IOException(BUSY);
}
return mutation;
} catch (IOException | RuntimeException failure) {
try {
mutation.close();
} catch (IOException cleanup) {
failure.addSuppressed(cleanup);
}
if (failure instanceof OverlappingFileLockException) {
throw new IOException(BUSY, failure);
}
if (failure instanceof UnsupportedOperationException) {
throw new IOException("このファイルシステムでは ModBridge の配置・復旧ロックを使えない", failure);
}
throw failure;
}
}

void ensureHeld() throws IOException {
if (!lock.isValid()) {
throw new IOException("ModBridge の配置・復旧ロックが外れた");
}
}

@Override
public void close() throws IOException {
try {
if (channel != null) {
channel.close();
}
} finally {
ACTIVE_ROOTS.remove(root);
}
}
}

/** BDS が動いていてロックを取れない。メッセージは固定の文言(パスを含めない)。 */
static final class LockedException extends IOException {
private static final long serialVersionUID = 1L;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,18 @@ Map<String, String> snapshot() throws IOException {
return out;
}

private Map<String, String> restoredContents() throws IOException {
Map<String, String> out = contentsWithoutLockFile();
out.keySet().removeIf(path -> path.startsWith("modbridge-backups/"));
return out;
}

private Map<String, String> contentsWithoutLockFile() throws IOException {
Map<String, String> out = snapshot();
assertEquals("", out.remove(BdsInstaller.OPERATION_LOCK_FILE), "空のファイルを後続の操作でも同じロック先に使う");
return out;
}

@Test
void dry_runは計画だけを返して何も変更しない() throws IOException {
Map<String, String> before = snapshot();
Expand Down Expand Up @@ -143,7 +155,7 @@ Map<String, String> snapshot() throws IOException {
var e = assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.apply(bds, packs, null, true));
assertTrue(e.getMessage().contains("ロック"), e.getMessage());
}
assertEquals(before, snapshot());
assertEquals(before, contentsWithoutLockFile());
}

@Test
Expand All @@ -158,7 +170,7 @@ Map<String, String> snapshot() throws IOException {
var error = assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.apply(bds, packs, "Archive", true));
assertTrue(error.getMessage().contains("ロック"), error.getMessage());
}
assertEquals(before, snapshot());
assertEquals(before, contentsWithoutLockFile());
BdsInstaller.apply(bds, packs, "Archive", true);
assertTrue(Files.isRegularFile(alternate.resolve("world_resource_packs.json")));
assertEquals(OTHER, Files.readString(world.resolve("world_behavior_packs.json")));
Expand All @@ -179,9 +191,26 @@ Map<String, String> snapshot() throws IOException {
}
assertEquals(installed, snapshot());
BdsInstaller.rollback(bds, id, true);
Map<String, String> restored = snapshot();
restored.keySet().removeIf(path -> path.startsWith("modbridge-backups/"));
assertEquals(original, restored);
assertEquals(original, restoredContents());
}

@Test
void DBロックの無いワールドでも別の配置と復旧は書き込めない() throws Exception {
Files.delete(world.resolve("db/LOCK"));
Map<String, String> original = snapshot();
String id = BdsInstaller.apply(bds, packs, null, true);
Map<String, String> installed = snapshot();
try (var mutation = BdsInstaller.MutationLock.acquire(bds)) {
mutation.ensureHeld();
assertTrue(BdsInstaller.plan(bds, packs, null).ok(), "実行中でも dry-run は可能");
var apply = assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.apply(bds, packs, null, true));
var rollback = assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.rollback(bds, id, true));
assertTrue(apply.getMessage().contains("ModBridge の配置または復旧を実行中"), apply.getMessage());
assertTrue(rollback.getMessage().contains("ModBridge の配置または復旧を実行中"), rollback.getMessage());
}
assertEquals(installed, snapshot());
BdsInstaller.rollback(bds, id, true);
assertEquals(original, restoredContents());
}

@Test
Expand All @@ -196,8 +225,8 @@ Map<String, String> snapshot() throws IOException {
assertTrue(writer.isOpen());
var error = assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.apply(bds, packs, null, true));
assertTrue(error.getMessage().contains("ロック"), error.getMessage());
assertEquals(beforeApply, snapshot());
}
assertEquals(beforeApply, contentsWithoutLockFile());
String id = BdsInstaller.apply(bds, packs, null, true);
Files.createFile(world.resolve("db/LOCK")); // 以前の実行で残ったが、使われていない LOCK
Map<String, String> beforeRollback = snapshot();
Expand All @@ -209,9 +238,7 @@ Map<String, String> snapshot() throws IOException {
}
Files.delete(world.resolve("db/LOCK"));
BdsInstaller.rollback(bds, id, true);
Map<String, String> after = snapshot();
after.keySet().removeIf(path -> path.startsWith("modbridge-backups/"));
assertEquals(beforeApply, after);
assertEquals(beforeApply, restoredContents());
}

@Test
Expand Down Expand Up @@ -244,9 +271,7 @@ Map<String, String> snapshot() throws IOException {
Map<String, String> before = snapshot();
String id = BdsInstaller.apply(bds, packs, null, true);
BdsInstaller.rollback(bds, id, true);
Map<String, String> after = snapshot();
after.keySet().removeIf(k -> k.startsWith("modbridge-backups/"));
assertEquals(before, after);
assertEquals(before, restoredContents());
assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.rollback(bds, "../../etc", true));
assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.rollback(bds, id, false));
}
Expand All @@ -257,9 +282,7 @@ Map<String, String> snapshot() throws IOException {
Map<String, String> before = snapshot();
var e = assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.apply(bds, packs, null, true));
assertTrue(e.getMessage().contains("元に戻した"), e.getMessage());
Map<String, String> after = snapshot();
after.keySet().removeIf(k -> k.startsWith("modbridge-backups/"));
assertEquals(before, after);
assertEquals(before, restoredContents());
}

@Test
Expand Down
1 change: 1 addition & 0 deletions docs/adr/0007-bds-install-and-rollback.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
### 安全策

- **dry-run が既定**: `--apply` を付けない限り、何も変更しない。
- **配置と復旧の排他**: 同じ BDS フォルダーでは、配置と復旧のうち1件だけが書き込める。`.modbridge-bds.lock` を使って、DB の停止確認から操作完了まで排他する。競合した操作はパックやワールドを変更せずに終了する。空のファイルは同じロック先を使うために残し、プロセスが終了すればロックは解除される。
- **停止の確認**: `--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/<UTC 時刻>/` に保存する。何があり、何が無かったかを `backup.json` に記録する。`db/LOCK` は保存しない(ロック中で読めない場合があり、LevelDB が作り直すため)。
Expand Down
Loading