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
96 changes: 71 additions & 25 deletions core/src/main/java/dev/puicore/modbridge/core/bds/BdsInstaller.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@
import dev.puicore.modbridge.core.scan.SafeArchive;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
Expand Down Expand Up @@ -272,56 +274,100 @@ static final class LockedException extends IOException {
}

/**
* ワールドの DB(LevelDB)のロック。BDS が動いていれば、ロックを取れない。
* DB がまだ無いワールドでは、ロックの検査を省く(呼出し側の明示だけに頼る)。
* LevelDB のロック、または Windows の DB ファイルの書き込み共有拒否を保持する。
* DB がまだ無いワールドでは、呼出し側の停止確認だけを使う。
*/
private static final class WorldLock implements AutoCloseable {
private final FileChannel channel;
private static final Pattern MUTABLE_LEVELDB_FILE = Pattern.compile("MANIFEST-[0-9]+|[0-9]+\\.log");
private final List<FileChannel> channels;
private final FileLock lock;

private WorldLock(FileChannel channel, FileLock lock) {
this.channel = channel;
private WorldLock(List<FileChannel> channels, FileLock lock) {
this.channels = channels;
this.lock = lock;
}

static WorldLock acquire(Path worldDir) throws IOException {
Path lockFile = worldDir.resolve("db").resolve("LOCK");
if (!Files.isRegularFile(lockFile)) {
return new WorldLock(null, null);
Path db = worldDir.resolve("db");
if (Files.notExists(db, LinkOption.NOFOLLOW_LINKS)) {
return new WorldLock(List.of(), null);
}
FileChannel ch;
try {
ch = FileChannel.open(lockFile, StandardOpenOption.WRITE);
} catch (IOException e) {
throw new LockedException(); // Windows では、BDS が開いていると開けない
if (!Files.isDirectory(db, LinkOption.NOFOLLOW_LINKS)) {
throw new LockedException();
}
FileLock l;
List<FileChannel> opened = new ArrayList<>();
try {
l = ch.tryLock();
} catch (OverlappingFileLockException | IOException e) {
l = null;
FileLock lock = null;
Path lockFile = db.resolve("LOCK");
if (!Files.notExists(lockFile, LinkOption.NOFOLLOW_LINKS)) {
FileChannel channel = FileChannel.open(lockFile, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS);
opened.add(channel);
lock = channel.tryLock();
if (lock == null) {
throw new LockedException();
}
}
if (System.getProperty("os.name").startsWith("Windows")) {
acquireWindowsFiles(db, opened);
}
return new WorldLock(opened, lock);
} catch (IOException | UncheckedIOException | ReflectiveOperationException | UnsupportedOperationException
| OverlappingFileLockException failure) {
var locked = failure instanceof LockedException e ? e : new LockedException();
if (locked != failure) {
locked.addSuppressed(failure);
}
try {
new WorldLock(opened, null).close();
} catch (IOException cleanup) {
locked.addSuppressed(cleanup);
}
throw locked;
}
}

private static void acquireWindowsFiles(Path db, List<FileChannel> opened) throws IOException, ReflectiveOperationException {
List<Path> journals;
try (Stream<Path> files = Files.list(db)) {
journals = files.filter(p -> MUTABLE_LEVELDB_FILE.matcher(p.getFileName().toString()).matches()).toList();
}
if (journals.isEmpty()) {
return;
}
if (l == null) {
ch.close();
// Windows の OpenJDK が提供する拡張。利用できなければ停止を確認できない扱いにする。
if (!(Class.forName("com.sun.nio.file.ExtendedOpenOption").getField("NOSHARE_WRITE").get(null)
instanceof OpenOption denyWrites)) {
throw new LockedException();
}
return new WorldLock(ch, l);
for (Path file : journals) {
// 読み込みは共有するので、このチャネルを保ったままバックアップできる。
opened.add(FileChannel.open(file, StandardOpenOption.READ, denyWrites, LinkOption.NOFOLLOW_LINKS));
}
}

/** ロックを持っている間に呼ぶ(DB の無いワールドでは何もしない)。 */
void ensureHeld() throws IOException {
if (lock != null && !lock.isValid()) {
if ((lock != null && !lock.isValid()) || channels.stream().anyMatch(ch -> !ch.isOpen())) {
throw new IOException("ワールドの DB のロックが外れた");
}
}

@Override
public void close() throws IOException {
if (lock != null) {
lock.release();
IOException failure = null;
for (FileChannel channel : channels) {
try {
channel.close(); // このチャネルの FileLock も解放される
} catch (IOException e) {
if (failure == null) {
failure = e;
} else {
failure.addSuppressed(e);
}
}
}
if (channel != null) {
channel.close();
if (failure != null) {
throw failure;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import javax.imageio.ImageIO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.io.TempDir;

class BdsInstallerTest {
Expand Down Expand Up @@ -122,6 +124,36 @@ Map<String, String> snapshot() throws IOException {
assertEquals(before, snapshot());
}

@Test
@EnabledOnOs(OS.WINDOWS)
void LOCKがなくても書き込み中のDBでは配置も復旧もしない() throws Exception {
Files.delete(world.resolve("db/LOCK"));
Path journal = world.resolve("db/000001.log");
Files.writeString(world.resolve("db/MANIFEST-000001"), "manifest");
Files.writeString(journal, "world state");
Map<String, String> beforeApply = snapshot();
try (var writer = FileChannel.open(journal, StandardOpenOption.WRITE)) {
assertTrue(writer.isOpen());
var error = assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.apply(bds, packs, null, true));
assertTrue(error.getMessage().contains("ロック"), error.getMessage());
assertEquals(beforeApply, snapshot());
}
String id = BdsInstaller.apply(bds, packs, null, true);
Files.createFile(world.resolve("db/LOCK")); // 以前の実行で残ったが、使われていない LOCK
Map<String, String> beforeRollback = snapshot();
try (var writer = FileChannel.open(journal, StandardOpenOption.WRITE)) {
assertTrue(writer.isOpen());
var error = assertThrows(BdsInstaller.InstallException.class, () -> BdsInstaller.rollback(bds, id, true));
assertTrue(error.getMessage().contains("ロック"), error.getMessage());
assertEquals(beforeRollback, snapshot());
}
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);
}

@Test
void 配置すると自分の項目だけを足し_ほかのパックと世界のデータは残す_やり直しても重複しない() throws IOException, Exception {
String id = BdsInstaller.apply(bds, packs, null, true);
Expand Down
9 changes: 7 additions & 2 deletions docs/adr/0007-bds-install-and-rollback.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
### 安全策

- **dry-run が既定**: `--apply` を付けない限り、何も変更しない。
- **停止の確認**: `--confirm-stopped` の明示に加えて、ワールドの DB のロック(`db/LOCK`)を取れるかで確かめる。BDS の実行中は LevelDB がロックを持つので、取れなければ断る。DB がまだ無いワールドでは、明示だけに頼る。
- **停止の確認**: `--confirm-stopped` の明示に加えて、`db/LOCK` があれば LevelDB のロックを取れるか確かめる。Windows では `MANIFEST-<番号>` と `<番号>.log` も、書き込みを共有しない読み取りモードで開く。開いている書き込みハンドルがあれば断る。読み取りは共有するため、配置中にハンドルを保持したままバックアップできる。DB がまだ無いワールドでは、明示だけを使う。
- **バックアップ**: 配置の前に、ワールドのフォルダー全体・自分のパックのフォルダー・2 つの JSON を `modbridge-backups/<UTC 時刻>/` に保存する。何があり、何が無かったかを `backup.json` に記録する。`db/LOCK` は保存しない(ロック中で読めない場合があり、LevelDB が作り直すため)。
- **入れ替え**: パックのフォルダーもワールドも、一時フォルダーに書き終えてから入れ替える。複製の途中で失敗しても、元のフォルダーは残る。入れ替えに失敗し、元のフォルダーを戻すのにも失敗したときは、元のフォルダーを消さずに残し、その名前を示す。JSON を戻すときも、一時ファイルを経由する。
- **失敗時の復旧**: 配置の途中で失敗したら、配置で変えたもの(パックのフォルダーと 2 つの JSON)をバックアップから戻す。ワールドの DB はロック中で、配置では触らないので戻さない。復旧にも失敗したら、バックアップの ID を示して rollback を促す。
Expand Down Expand Up @@ -72,10 +72,15 @@
- BP には、アイテム・ブロック・レシピ 2 つのファイルが入った。
- `world_behavior_packs.json` に、自分の項目が 1 つ入った。

## DB の停止確認(2026-11-28)

- Minecraft for Windows 26.65 の隔離ローカルワールドでは、利用中にも `db/LOCK` が無かった。DB の書き込みファイルを使う検査では、ワールドを開いている間は拒否し、保存して閉じると通過した。閉じた DB のコピーを使って配置・復旧し、復旧後のワールドのファイルが配置前と一致した。
- Linux では WSL の ext4 上で別プロセスに LevelDB 1.23 を開かせると、CLI の配置と復旧はどちらもロックを検出して拒否された。DB を閉じた後は両方が成功した。

## 未検証・既知の制約

- **実際の BDS で、配置したアドオンが読み込まれるかは未確認**。BDS の起動には、Minecraft の EULA とプライバシーポリシーへの同意が要る。これは owner の判断を待っている。
- Linux の BDS での確認も未実施。LevelDB のロックは Linux でも `fcntl` で取られ、Java の `tryLock` と同じ仕組みなので検出できる見込み(推測)。
- Windows・Linux の公式 BDS が使うワールドを対象にした停止確認は未実施。
- バックアップはワールド全体を複製するので、大きなワールドでは時間と容量がかかる。古いバックアップは自動では消さない。
- Windows では、フォルダーの置き換えは原子的ではない(2 回の移動の間に、一瞬だけ対象が無い)。
- Windows のジャンクションは、シンボリックリンクとして検出できない。パックのフォルダーがジャンクションなら、リンク先は消さずに、実フォルダーへ置き換わる。
Expand Down
Loading