diff --git a/.github/workflows/ogl-net10-shutdown.yml b/.github/workflows/ogl-net10-shutdown.yml index 91be4080..1e4abfa4 100644 --- a/.github/workflows/ogl-net10-shutdown.yml +++ b/.github/workflows/ogl-net10-shutdown.yml @@ -14,6 +14,7 @@ on: - 'OpenSim/Region/Application/OpenSimBackground.cs' - 'tools/ci/Net10ShutdownRegression/**' - 'tools/ci/LegacyKeyframeFixture/**' + - 'tools/ci/test_ogl_keyframe_batch.py' - 'tools/migration/KeyframeLegacyConverter/**' - 'doc/NexVerse/KEYFRAME_LEGACY_MIGRATION.md' - 'tools/ci/verify_net10_shutdown.py' @@ -63,6 +64,8 @@ jobs: run: | dotnet run --project tools/migration/KeyframeLegacyConverter/KeyframeLegacyConverter.csproj -c Release -- /tmp/ogl-legacy-ci.bin /tmp/ogl-keyframe-ci.ogkf dotnet run --project tools/ci/Net10ShutdownRegression/Net10ShutdownRegression.csproj -c Release -- /tmp/ogl-keyframe-ci.ogkf + - name: Verify read-only batch export and all-or-nothing rollback + run: python3 tools/ci/test_ogl_keyframe_batch.py /tmp/ogl-legacy-ci.bin - name: Stop a real multi-region .NET 10 simulator using its console run: python3 tools/ci/smoke_g1_multi_region_shutdown.py --regions 12 - name: Inject test-only blocked region close in CI checkout diff --git a/doc/NexVerse/KEYFRAME_LEGACY_MIGRATION.md b/doc/NexVerse/KEYFRAME_LEGACY_MIGRATION.md index 34a331ea..49de2798 100644 --- a/doc/NexVerse/KEYFRAME_LEGACY_MIGRATION.md +++ b/doc/NexVerse/KEYFRAME_LEGACY_MIGRATION.md @@ -58,3 +58,40 @@ failed records are not overwritten. legacy record using isolated .NET 8 test code, converts it without BinaryFormatter in .NET 10 and checks OGKF restore. This is not a substitute for testing a backed-up real-world movement record. + +## Batch migration from a read-only MariaDB / MySQL export + +Export the UUID and HEX blob columns using a **read-only database account** +against a **stopped region / consistent backup**, keeping the original +database and the exported file for rollback: + +```sql +SELECT UUID, HEX(KeyframeMotion) +FROM prims +WHERE KeyframeMotion IS NOT NULL + AND OCTET_LENGTH(KeyframeMotion) >= 9 + AND HEX(SUBSTRING(KeyframeMotion, 1, 5)) = '0001000000'; +``` + +Store the two-column result as UTF-8 **tab-delimited text without headers** +(`uuidblobhex`), for example `legacy-keyframes.tsv`. Never paste +database credentials into command logs or commit the export to GitHub. + +```bash +dotnet run --project tools/migration/KeyframeLegacyConverter/KeyframeLegacyConverter.csproj \ + -c Release -- --batch-hex legacy-keyframes.tsv converted-keyframes.tsv +``` + +The batch converter processes at most 100,000 rows, rejects malformed, +duplicate or unsupported rows, checks **each result** against the actual +.NET 10 keyframe reader and writes a three-column report: +`UUIDSHA256(original BLOB)HEX(new OGKF BLOB)`. + +The batch report is created atomically only after **every row passes**; +it does not connect to SQL, issue UPDATE statements, replace existing +files, or modify live region data. The SHA-256 is a verification guard for +an eventual operator-reviewed per-row update on a **staging restore**. + +Do not apply updates based on UUID alone. Check the original per-object +BLOB digest in the same transaction and verify the number of updated rows. +Not every historical BinaryFormatter variant is necessarily supported. diff --git a/tools/ci/test_ogl_keyframe_batch.py b/tools/ci/test_ogl_keyframe_batch.py new file mode 100644 index 00000000..ad751429 --- /dev/null +++ b/tools/ci/test_ogl_keyframe_batch.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""CI: verify read-only conversion of old NRBF blobs in batch TSV format.""" +import hashlib +from pathlib import Path +import subprocess +import sys +import tempfile +import uuid + +ROOT = Path(__file__).resolve().parents[2] +PROJECT = ROOT / "tools/migration/KeyframeLegacyConverter/KeyframeLegacyConverter.csproj" +original = Path(sys.argv[1]).read_bytes() +obj1, obj2 = uuid.uuid4(), uuid.uuid4() + + +def run_batch(source, target, success): + command = ["dotnet", "run", "--no-build", "--project", str(PROJECT), + "-c", "Release", "--", "--batch-hex", str(source), str(target)] + result = subprocess.run(command, capture_output=True, text=True, timeout=90) + assert (result.returncode == 0) == success, ( + f"unexpected batch exit {result.returncode}: {result.stdout}\n{result.stderr}") + return result + + +with tempfile.TemporaryDirectory(prefix="ogl-keyframe-batch-") as folder: + root = Path(folder) + source, target = root / "legacy.tsv", root / "converted.tsv" + source.write_text(f"{obj1}\t{original.hex()}\n{obj2}\t{original.hex()}\n") + run_batch(source, target, True) + rows = [r.split("\t") for r in target.read_text().splitlines()] + assert len(rows) == 2 and all(len(r) == 3 for r in rows) + assert {r[0] for r in rows} == {str(obj1), str(obj2)} + for obj, hash_value, hex_record in rows: + assert hash_value == hashlib.sha256(original).hexdigest().upper() + assert bytes.fromhex(hex_record).startswith(b"OGKF\x01") + + original_target = target.read_bytes() + run_batch(source, target, False) + assert target.read_bytes() == original_target, "existing output was modified" + + target.unlink() + source.write_text(f"{obj1}\t{original.hex()}\n{obj2}\tDEADBEEF\n") + run_batch(source, target, False) + assert not target.exists(), "failed batch left an output file" + assert not list(root.glob("*.tmp")), "failed batch left temporary files" + + source.write_text(f"{obj1}\t{original.hex()}\n{obj1}\t{original.hex()}\n") + run_batch(source, target, False) + assert not target.exists(), "duplicate UUID batch left an output" + + source.write_text("") + run_batch(source, target, False) + assert not target.exists(), "empty batch left an output" +print("PASS: two NRBF records convert with SHA-256, existing output unchanged," + " invalid/duplicate/empty batches have no output") diff --git a/tools/ci/verify_net10_shutdown.py b/tools/ci/verify_net10_shutdown.py index 8df61abe..4451706d 100644 --- a/tools/ci/verify_net10_shutdown.py +++ b/tools/ci/verify_net10_shutdown.py @@ -37,4 +37,7 @@ assert "NrbfDecoder.DecodeClassRecord(" in converter assert "new BinaryFormatter(" not in converter assert "FileMode.CreateNew" in converter assert "KeyframeMotion.FromData(null, converted)" in converter +assert "ConvertBatch(" in converter +assert "SHA256.HashData(original)" in converter +assert "File.Move(temporary, output)" in converter print("PASS: shutdown isolation, byte-only keyframe migration and ACK queue lifetime") diff --git a/tools/migration/KeyframeLegacyConverter/Program.cs b/tools/migration/KeyframeLegacyConverter/Program.cs index 7bf252da..3fe59e5a 100644 --- a/tools/migration/KeyframeLegacyConverter/Program.cs +++ b/tools/migration/KeyframeLegacyConverter/Program.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Formats.Nrbf; using System.IO; +using System.Security.Cryptography; using OpenMetaverse; using OpenSim.Region.Framework.Scenes; @@ -15,6 +16,9 @@ internal static class Program private static int Main(string[] args) { + if (args.Length == 3 && args[0] == "--batch-hex") + return ConvertBatch(args[1], args[2]); + if (args.Length != 2 || args[0] is "-h" or "--help") { Console.Error.WriteLine("Usage: dotnet run --project tools/migration/KeyframeLegacyConverter -- legacy.bin migrated.ogkf"); @@ -32,14 +36,7 @@ internal static class Program if (!input.Exists || input.Length == 0 || input.Length > MaxBytes) throw new InvalidDataException("Input size must be within 1..4 MiB."); byte[] legacy = File.ReadAllBytes(source); - byte[] converted = Convert(legacy); - - // The target runtime itself must accept the output; never store an - // unvalidated conversion as a replacement for a region's record. - KeyframeMotion? tested = KeyframeMotion.FromData(null, converted); - if (tested is null || tested.HasLegacySerialization || - !converted.AsSpan().SequenceEqual(tested.Serialize())) - throw new InvalidDataException("Generated OGKF payload failed runtime validation."); + byte[] converted = ConvertVerified(legacy); using FileStream target = new FileStream(destination, FileMode.CreateNew, FileAccess.Write, FileShare.None); @@ -58,6 +55,114 @@ internal static class Program } } + // Read-only MariaDB/MySQL export path: a TSV of UUID and HEX(KeyframeMotion) + // becomes a TSV of UUID, original SHA-256 and verified OGKF HEX. The source + // database is never contacted. Neither input nor output is overwritten. + // A malformed or unsupported row aborts the WHOLE batch and emits no file. + private static int ConvertBatch(string inputPath, string outputPath) + { + string input = Path.GetFullPath(inputPath); + string output = Path.GetFullPath(outputPath); + if (string.Equals(input, output, StringComparison.Ordinal)) + { + Console.Error.WriteLine("Batch input and output must be different."); + return 1; + } + + string? directory = Path.GetDirectoryName(output); + if (directory is null || !Directory.Exists(directory) || File.Exists(output)) + { + Console.Error.WriteLine("Batch output directory must exist and output must not exist."); + return 1; + } + + string temporary = Path.Combine(directory, "." + Path.GetFileName(output) + + "." + Guid.NewGuid().ToString("N") + ".tmp"); + try + { + HashSet seen = new HashSet(); + int count = 0; + using (FileStream file = new FileStream(temporary, FileMode.CreateNew, + FileAccess.Write, FileShare.None)) + using (StreamWriter writer = new StreamWriter(file)) + using (StreamReader reader = new StreamReader(input)) + { + string? line; + while ((line = reader.ReadLine()) is not null) + { + count++; + if (count > 100000) + throw new InvalidDataException("More than 100000 records in keyframe batch."); + + string[] columns = line.Split('\t'); + if (columns.Length != 2 || + !Guid.TryParseExact(columns[0], "D", out Guid objectId) || + !seen.Add(objectId)) + throw new InvalidDataException("Invalid or duplicate object UUID at line " + count); + + string hex = columns[1]; + if (hex.Length < 18 || hex.Length % 2 != 0 || + hex.Length > MaxBytes * 2) + throw new InvalidDataException("Invalid BLOB length at line " + count); + + byte[] original; + try { original = System.Convert.FromHexString(hex); } + catch (FormatException error) + { + throw new InvalidDataException("Invalid exported HEX at line " + count, error); + } + + byte[] converted; + try { converted = ConvertVerified(original); } + catch (Exception error) when (error is InvalidDataException or + InvalidOperationException or ArgumentException or NotSupportedException) + { + throw new InvalidDataException("Invalid NRBF movement at line " + count, error); + } + + writer.Write(objectId.ToString("D")); + writer.Write('\t'); + writer.Write(System.Convert.ToHexString(SHA256.HashData(original))); + writer.Write('\t'); + writer.WriteLine(System.Convert.ToHexString(converted)); + } + if (count == 0) + throw new InvalidDataException("Batch export is empty."); + writer.Flush(); + file.Flush(true); + } + File.Move(temporary, output); // will not overwrite an existing file + Console.WriteLine("PASS: converted " + count + " legacy keyframes, hashes retained."); + Console.WriteLine("Input retained: " + input); + Console.WriteLine("Output (UUID, original SHA-256, verified OGKF HEX): " + output); + return 0; + } + catch (Exception error) when (error is IOException or InvalidDataException or + InvalidOperationException or ArgumentException or NotSupportedException) + { + Console.Error.WriteLine("Legacy keyframe batch rejected; no output installed: " + + error.Message); + return 1; + } + finally + { + if (File.Exists(temporary)) + File.Delete(temporary); + } + } + + private static byte[] ConvertVerified(byte[] legacy) + { + byte[] converted = Convert(legacy); + // The target runtime itself must accept the output; never store an + // unvalidated conversion as a replacement for a region's record. + KeyframeMotion? tested = KeyframeMotion.FromData(null, converted); + if (tested is null || tested.HasLegacySerialization || + !converted.AsSpan().SequenceEqual(tested.Serialize())) + throw new InvalidDataException("Generated OGKF payload failed runtime validation."); + return converted; + } + private static byte[] Convert(byte[] bytes) { using MemoryStream source = new MemoryStream(bytes, false);