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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@

## Терминал владельца

- `restores inspect-region` проверяет участок верхнего мира DJ2 по выбранному
холодному бэкапу. В отчёте видны границы, объём, покрытие чанков и хеш снимка.
- `action-history` ищет серверные действия DJ2 по координатам, периоду и UUID.
Поиск показывает качество покрытия, а материалы инцидента можно сохранить
с собственной проверенной копией мира.
Expand Down
3 changes: 3 additions & 0 deletions docs/ADMIN.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ volume runtime**: пересоздание контейнера сохраняе
Можно сохранить отдельный комплект с журналом, диагностикой и проверенной
копией мира. [Журнал действий DJ2](ACTION_ATTRIBUTION.md).

`restores inspect-region` проверяет участок верхнего мира остановленного DJ2
по выбранному холодному бэкапу. [Команда и требования](REGION_RECOVERY.md#проверка-участка-перед-восстановлением).

```powershell
uv run omk admin --config .omk-admin/operator.toml diagnostics dj2
```
Expand Down
25 changes: 25 additions & 0 deletions docs/REGION_RECOVERY.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,31 @@ FTB Backups 1.1.0.1 и автоматическая политика хране
Практический список команд — [commands/dj2/RECOVERY.md](commands/dj2/RECOVERY.md),
запуск нового стенда — [commands/dj2/TESTING.md](commands/dj2/TESTING.md).

## Проверка участка перед восстановлением

Для DJ2 можно сверить выделение в верхнем мире с управляемым холодным
бэкапом. Команда использует существующую настройку
[`backups.toml`](../deploy/owner/backups.example.toml) и ожидает штатно
остановленный источник. Идентификатор снимка берётся из `backups list --server dj2`.

```text
uv run omk admin --config .omk-admin/operator.toml restores inspect-region --server dj2 --snapshot SNAPSHOT_ID --minimum 130 241 130 --maximum 135 243 134
```

Обе точки включаются в участок. Укажите меньшую координату по каждой оси
в `--minimum`. Допустимы высоты от 0 до 255 и до 64 чанков внутри сохранённой
границы мира.

Команда проверяет SHA-256 архива и наличие всех чанков в обоих сохранениях.
Имя мира, сид и параметры генератора должны совпасть. Формат сохранений,
версии модов и реестры Forge сверяются по `level.dat`. В ответе остаются
границы, объём участка, идентификатор и хеш снимка. Хеши текущего `level.dat`
и выбранных чанков позволяют опознать сохранение, которое участвовало в проверке.

Мир и хранилище бэкапов подключаются к проверке только для чтения. Для
будущего применения отдельно нужны свежая копия, подтверждение владельца
и проверка результата на подготовленном томе.

## Требуемое поведение

Администратор выбирает сервер/измерение, трёхмерную область и доступный снимок до грифа.
Expand Down
65 changes: 60 additions & 5 deletions omk/owner/admin_restores.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from omk.owner.panels import owner_volumes
from omk.shared.nbt import MAX_BYTES
from omk.shared.profiles import PROJECT_ROOT
from omk.worlds import incident_players, incident_recovery
from omk.worlds import incident_players, incident_recovery, region_restore_inspection


def target_for(config, server, source):
Expand All @@ -38,7 +38,7 @@ def destination(target, *, unused=False):


def worker(record, action, *, evidence_sha256=None):
source, target, settings = record["source"], record["target"], record["settings"]
source, settings = record["source"], record["settings"]
request = {
"action": action,
"operation": record["operation"],
Expand All @@ -50,6 +50,8 @@ def worker(record, action, *, evidence_sha256=None):
for k in ("max_bytes", "max_count", "staging_bytes", "reserve_bytes")
},
}
if action == "inspect-region":
request.update(record["selection"])
if "expected" in record:
request["expected"] = record["expected"]
if "incident" in record:
Expand Down Expand Up @@ -84,11 +86,15 @@ def worker(record, action, *, evidence_sha256=None):
"--mount",
f"type=volume,source={source['data_volume']},target=/current,readonly",
"--mount",
f"type=volume,source={target['data_volume']},target=/restore"
+ ("" if action == "apply" else ",readonly"),
"--mount",
f"type=bind,source={PROJECT_ROOT / 'omk'},target=/src/omk,readonly",
]
if action != "inspect-region":
target = record["target"]
mode = "" if action == "apply" else ",readonly"
args += [
"--mount",
f"type=volume,source={target['data_volume']},target=/restore{mode}",
]
if action == "evidence":
args += ["--log-driver", "none"]
for filename in ("__init__.py", "nbt.py"):
Expand All @@ -115,6 +121,13 @@ def worker(record, action, *, evidence_sha256=None):
raise AdminError("Restore worker response exceeds limit")
result = json.loads(text)
if result.get("ok") is not True or not isinstance(result.get("result"), dict):
reason = result.get("region_reason")
if (
action == "inspect-region"
and isinstance(reason, str)
and reason in region_restore_inspection.REASONS
):
raise AdminError(region_restore_inspection.REASONS[reason])
kind = result.get("error_type", "InvalidResponse")
if not isinstance(kind, str) or not re.fullmatch(r"[A-Za-z]{1,64}", kind):
kind = "InvalidResponse"
Expand Down Expand Up @@ -367,6 +380,35 @@ def run(config, operation, *, verify=False, environment=None):
return {"ok": True, "operation": operation, "stage": "staged", **result}


def inspect_region(config, server, snapshot, minimum, maximum):
"""Run a read-only check against a selected backup and the stopped source."""
from omk.worlds.world_cutover import require_clear # noqa: PLC0415

if not isinstance(snapshot, str) or not re.fullmatch(
r"snapshot-[a-f0-9]{32}", snapshot
):
raise AdminError("Invalid selected restore snapshot")
with backups.locked(config):
require_clear(config, server)
source = backups.target_for(config, server)
backups.local_engine()
checkpoint = backups.checkpoint(source)
record = {
"operation": uuid4().hex,
"source": source,
"settings": backups.settings(),
"snapshot": snapshot,
"selection": {"minimum": minimum, "maximum": maximum},
}
result = worker(record, "inspect-region")
if (
backups.target_for(config, server) != source
or backups.checkpoint(source) != checkpoint
):
raise AdminError("Stopped source changed during region inspection")
return {"ok": True, "server": server, **result}


def add_restore_parser(actions):
parser = actions.add_parser(
"restores", help="Owner Linux restore staging; no lifecycle or promotion"
Expand All @@ -379,11 +421,24 @@ def add_restore_parser(actions):
"--incident",
help="Private JSON selection for a single-player rescue or object quarantine",
)
inspection = sub.add_parser(
"inspect-region", help="Check a historical overworld selection without changes"
)
inspection.add_argument("--server", required=True)
inspection.add_argument("--snapshot", required=True)
for flag in ("--minimum", "--maximum"):
inspection.add_argument(
flag, type=int, nargs=3, metavar=("X", "Y", "Z"), required=True
)
for action in ("apply", "verify", "status"):
sub.add_parser(action).add_argument("--operation", required=True)


def run_restores(config, args):
if args.restore_action == "inspect-region":
return inspect_region(
config, args.server, args.snapshot, args.minimum, args.maximum
)
if args.restore_action == "plan":
path = getattr(args, "incident", None)
incident = (
Expand Down
95 changes: 54 additions & 41 deletions omk/worlds/forge112_regions.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,57 @@ def apply(self, path):
os.fsync(target.fileno())


def read_region_locations(source, size):
"""Check the Anvil sector table of a bounded seekable region stream."""
if not 2 * SECTOR <= size <= 1024**3 or size % SECTOR:
raise ValueError("Unsupported region size")
header = source.read(SECTOR)
if len(header) != SECTOR:
raise ValueError("Truncated region location table")
locations = {}
occupied = {0, 1}
for index in range(1024):
offset = int.from_bytes(header[index * 4 : index * 4 + 3], "big")
count = header[index * 4 + 3]
if offset == count == 0:
continue
sectors = set(range(offset, offset + count))
if (
offset < 2
or not count
or (offset + count) * SECTOR > size
or occupied & sectors
):
raise ValueError("Invalid or overlapping region allocation")
occupied.update(sectors)
locations[index] = offset, count
return locations


def read_chunk_record(source, location, coordinates):
"""Read and check one Anvil chunk from a region file or a ZIP entry."""
offset, count = location
source.seek(offset * SECTOR)
header = source.read(5)
if len(header) != 5:
raise ValueError("Truncated chunk header")
length, codec = struct.unpack(">IB", header)
if codec != 2 or not 1 < length <= count * SECTOR - 4:
raise ValueError("Unsupported chunk compression")
compressed = source.read(length - 1)
if len(compressed) != length - 1:
raise ValueError("Truncated compressed chunk")
inflater = zlib.decompressobj()
raw = inflater.decompress(compressed, MAX_BYTES + 1)
if len(raw) > MAX_BYTES or not inflater.eof or inflater.unused_data:
raise ValueError("Invalid or oversized chunk NBT")
name, root = read_nbt(raw)
level = value(root, "Level", 10)
if (value(level, "xPos", 3), value(level, "zPos", 3)) != coordinates:
raise ValueError("Chunk coordinates differ from region entry")
return name, root, raw


class Region:
"""Read chunks from one Minecraft 1.12 Anvil region file."""

Expand All @@ -95,27 +146,8 @@ def __init__(self, path: Path, world: Path):
self.path = path
self.x, self.z = map(int, match.groups())
self.size = path.stat().st_size
if not 2 * SECTOR <= self.size <= 1024**3 or self.size % SECTOR:
raise ValueError("Unsupported region size")
with path.open("rb") as source:
header = source.read(SECTOR)
self.locations = {}
occupied = {0, 1}
for index in range(1024):
offset = int.from_bytes(header[index * 4 : index * 4 + 3], "big")
count = header[index * 4 + 3]
if offset == count == 0:
continue
sectors = set(range(offset, offset + count))
if (
offset < 2
or not count
or (offset + count) * SECTOR > self.size
or occupied & sectors
):
raise ValueError("Invalid or overlapping region allocation")
occupied.update(sectors)
self.locations[index] = offset, count
self.locations = read_region_locations(source, self.size)

def chunk(self, index):
"""Decode the stored chunk at the requested region coordinates."""
Expand All @@ -125,28 +157,9 @@ def record(self, index):
"""Read the complete chunk record and its original uncompressed bytes."""
if index not in self.locations:
raise ValueError("Landing chunk is not saved")
offset, count = self.locations[index]
coordinates = self.x * 32 + index % 32, self.z * 32 + index // 32
with self.path.open("rb") as source:
source.seek(offset * SECTOR)
header = source.read(5)
if len(header) != 5:
raise ValueError("Truncated chunk header")
length, codec = struct.unpack(">IB", header)
if codec != 2 or not 1 < length <= count * SECTOR - 4:
raise ValueError("Unsupported chunk compression")
compressed = source.read(length - 1)
if len(compressed) != length - 1:
raise ValueError("Truncated compressed chunk")
inflater = zlib.decompressobj()
raw = inflater.decompress(compressed, MAX_BYTES + 1)
if len(raw) > MAX_BYTES or not inflater.eof or inflater.unused_data:
raise ValueError("Invalid or oversized chunk NBT")
name, root = read_nbt(raw)
level = value(root, "Level", 10)
expected = self.x * 32 + index % 32, self.z * 32 + index // 32
if (value(level, "xPos", 3), value(level, "zPos", 3)) != expected:
raise ValueError("Chunk coordinates differ from region entry")
return name, root, raw
return read_chunk_record(source, self.locations[index], coordinates)

def replacement(self, index, name, root):
"""Encode a verified chunk inside its current allocation."""
Expand Down
8 changes: 7 additions & 1 deletion omk/worlds/owner_restore_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
incident_recovery,
linux_restore_policy as policy,
linux_world_restore as raw,
region_restore_inspection,
)

PLAN = ".omk-owner-restore-plan.json"
Expand Down Expand Up @@ -211,6 +212,8 @@ def execute(
):
if sys.platform != "linux":
raise ValueError("Owner world restore requires Linux")
if request.get("action") == "inspect-region":
return region_restore_inspection.inspect(request, storage, current)
functions = {"plan": plan, "apply": apply, "verify": verify}
if "incident" in request:
return incident_recovery.execute(request, storage, target, current)
Expand All @@ -227,5 +230,8 @@ def execute(
result = execute(json.loads(data))
print(json.dumps({"ok": True, "result": result}))
except Exception as error:
print(json.dumps({"ok": False, "error_type": type(error).__name__}))
report = {"ok": False, "error_type": type(error).__name__}
if isinstance(error, region_restore_inspection.InspectionRefused):
report["region_reason"] = error.reason
print(json.dumps(report))
raise SystemExit(1) from None
Loading
Loading