testserver/patches/server/0319-Allow-Saving-of-Oversi...

252 lines
11 KiB
Diff
Raw Normal View History

2021-06-11 12:02:28 +00:00
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Fri, 15 Feb 2019 01:08:19 -0500
Subject: [PATCH] Allow Saving of Oversized Chunks
2021-06-13 09:41:07 +00:00
Note 1.17 update: With 1.17, Entities are no longer stored in chunk slices, so this needs updating!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
2021-06-11 12:02:28 +00:00
The Minecraft World Region File format has a hard cap of 1MB per chunk.
This is due to the fact that the header of the file format only allocates
a single byte for sector count, meaning a maximum of 256 sectors, at 4k per sector.
This limit can be reached fairly easily with books, resulting in the chunk being unable
to save to the world. Worse off, is that nothing printed when this occured, and silently
performed a chunk rollback on next load.
This leads to security risk with duplication and is being actively exploited.
This patch catches the too large scenario, falls back and moves any large Entity
or Tile Entity into a new compound, and this compound is saved into a different file.
On Chunk Load, we check for oversized status, and if so, we load the extra file and
merge the Entities and Tile Entities from the oversized chunk back into the level to
then be loaded as normal.
Once a chunk is returned back to normal size, the oversized flag will clear, and no
extra data file will exist.
This fix maintains compatability with all existing Anvil Region Format tools as it
does not alter the save format. They will just not know about the extra entities.
This fix also maintains compatability if someone switches server jars to one without
this fix, as the data will remain in the oversized file. Once the server returns
to a jar with this fix, the data will be restored.
diff --git a/src/main/java/net/minecraft/world/level/chunk/storage/RegionFile.java b/src/main/java/net/minecraft/world/level/chunk/storage/RegionFile.java
2022-03-01 05:43:03 +00:00
index 038e2177182c94baa4af24f9111cf155ec342dfe..330fb8e6565a5c0490af0c5ca0e7355d81a82e58 100644
2021-06-11 12:02:28 +00:00
--- a/src/main/java/net/minecraft/world/level/chunk/storage/RegionFile.java
+++ b/src/main/java/net/minecraft/world/level/chunk/storage/RegionFile.java
2022-03-01 05:43:03 +00:00
@@ -18,8 +18,12 @@ import java.nio.file.LinkOption;
2021-06-11 12:02:28 +00:00
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
+import java.util.zip.InflaterInputStream; // Paper
+
import javax.annotation.Nullable;
import net.minecraft.Util;
+import net.minecraft.nbt.CompoundTag;
+import net.minecraft.nbt.NbtIo;
import net.minecraft.world.level.ChunkPos;
2022-03-01 05:43:03 +00:00
import org.slf4j.Logger;
2021-11-24 04:25:34 +00:00
@@ -45,6 +49,7 @@ public class RegionFile implements AutoCloseable {
2021-06-11 12:02:28 +00:00
@VisibleForTesting
protected final RegionBitmap usedSectors;
2021-06-16 06:25:38 +00:00
public final java.util.concurrent.locks.ReentrantLock fileLock = new java.util.concurrent.locks.ReentrantLock(true); // Paper
2021-11-24 04:25:34 +00:00
+ public final Path regionFile; // Paper
2021-06-11 12:02:28 +00:00
public RegionFile(Path file, Path directory, boolean dsync) throws IOException {
this(file, directory, RegionFileVersion.VERSION_DEFLATE, dsync);
2021-11-24 04:25:34 +00:00
@@ -52,6 +57,8 @@ public class RegionFile implements AutoCloseable {
2021-06-11 12:02:28 +00:00
public RegionFile(Path file, Path directory, RegionFileVersion outputChunkStreamVersion, boolean dsync) throws IOException {
this.header = ByteBuffer.allocateDirect(8192);
2021-11-24 04:25:34 +00:00
+ this.regionFile = file; // Paper
2021-06-11 12:02:28 +00:00
+ initOversizedState(); // Paper
this.usedSectors = new RegionBitmap();
this.version = outputChunkStreamVersion;
if (!Files.isDirectory(directory, new LinkOption[0])) {
2021-11-24 04:25:34 +00:00
@@ -430,6 +437,74 @@ public class RegionFile implements AutoCloseable {
2021-06-16 06:25:38 +00:00
2021-06-11 12:02:28 +00:00
}
+ // Paper start
+ private final byte[] oversized = new byte[1024];
+ private int oversizedCount = 0;
+
+ private synchronized void initOversizedState() throws IOException {
2021-11-24 04:25:34 +00:00
+ Path metaFile = getOversizedMetaFile();
+ if (Files.exists(metaFile)) {
+ final byte[] read = java.nio.file.Files.readAllBytes(metaFile);
2021-06-11 12:02:28 +00:00
+ System.arraycopy(read, 0, oversized, 0, oversized.length);
+ for (byte temp : oversized) {
+ oversizedCount += temp;
+ }
+ }
+ }
+
+ private static int getChunkIndex(int x, int z) {
+ return (x & 31) + (z & 31) * 32;
+ }
+ synchronized boolean isOversized(int x, int z) {
+ return this.oversized[getChunkIndex(x, z)] == 1;
+ }
+ synchronized void setOversized(int x, int z, boolean oversized) throws IOException {
+ final int offset = getChunkIndex(x, z);
+ boolean previous = this.oversized[offset] == 1;
+ this.oversized[offset] = (byte) (oversized ? 1 : 0);
+ if (!previous && oversized) {
+ oversizedCount++;
+ } else if (!oversized && previous) {
+ oversizedCount--;
+ }
+ if (previous && !oversized) {
2021-11-24 04:25:34 +00:00
+ Path oversizedFile = getOversizedFile(x, z);
+ if (Files.exists(oversizedFile)) {
+ Files.delete(oversizedFile);
2021-06-11 12:02:28 +00:00
+ }
+ }
+ if (oversizedCount > 0) {
+ if (previous != oversized) {
+ writeOversizedMeta();
+ }
+ } else if (previous) {
2021-11-24 04:25:34 +00:00
+ Path oversizedMetaFile = getOversizedMetaFile();
+ if (Files.exists(oversizedMetaFile)) {
+ Files.delete(oversizedMetaFile);
2021-06-11 12:02:28 +00:00
+ }
+ }
+ }
+
+ private void writeOversizedMeta() throws IOException {
2021-11-24 04:25:34 +00:00
+ java.nio.file.Files.write(getOversizedMetaFile(), oversized);
2021-06-11 12:02:28 +00:00
+ }
+
2021-11-24 04:25:34 +00:00
+ private Path getOversizedMetaFile() {
+ return this.regionFile.getParent().resolve(this.regionFile.getFileName().toString().replaceAll("\\.mca$", "") + ".oversized.nbt");
2021-06-11 12:02:28 +00:00
+ }
+
2021-11-24 04:25:34 +00:00
+ private Path getOversizedFile(int x, int z) {
+ return this.regionFile.getParent().resolve(this.regionFile.getFileName().toString().replaceAll("\\.mca$", "") + "_oversized_" + x + "_" + z + ".nbt");
2021-06-11 12:02:28 +00:00
+ }
+
+ synchronized CompoundTag getOversizedData(int x, int z) throws IOException {
2021-11-24 04:25:34 +00:00
+ Path file = getOversizedFile(x, z);
+ try (DataInputStream out = new DataInputStream(new java.io.BufferedInputStream(new InflaterInputStream(Files.newInputStream(file))))) {
2021-06-16 06:25:38 +00:00
+ return NbtIo.read((java.io.DataInput) out);
2021-06-11 12:02:28 +00:00
+ }
+
+ }
+ // Paper end
2021-06-16 06:25:38 +00:00
private class ChunkBuffer extends ByteArrayOutputStream {
2021-06-11 12:02:28 +00:00
private final ChunkPos pos;
diff --git a/src/main/java/net/minecraft/world/level/chunk/storage/RegionFileStorage.java b/src/main/java/net/minecraft/world/level/chunk/storage/RegionFileStorage.java
Rewrite chunk system (#8177) Patch documentation to come Issues with the old system that are fixed now: - World generation does not scale with cpu cores effectively. - Relies on the main thread for scheduling and maintaining chunk state, dropping chunk load/generate rates at lower tps. - Unreliable prioritisation of chunk gen/load calls that block the main thread. - Shutdown logic is utterly unreliable, as it has to wait for all chunks to unload - is it guaranteed that the chunk system is in a state on shutdown that it can reliably do this? Watchdog shutdown also typically failed due to thread checks, which is now resolved. - Saving of data is not unified (i.e can save chunk data without saving entity data, poses problems for desync if shutdown is really abnormal. - Entities are not loaded with chunks. This caused quite a bit of headache for Chunk#getEntities API, but now the new chunk system loads entities with chunks so that they are ready whenever the chunk loads in. Effectively brings the behavior back to 1.16 era, but still storing entities in their own separate regionfiles. The above list is not complete. The patch documentation will complete it. New chunk system hard relies on starlight and dataconverter, and most importantly the new concurrent utilities in ConcurrentUtil. Some of the old async chunk i/o interface (i.e the old file io thread reroutes _some_ calls to the new file io thread) is kept for plugin compat reasons. It will be removed in the next major version of minecraft. The old legacy chunk system patches have been moved to the removed folder in case we need them again.
2022-09-26 08:02:51 +00:00
index 9a4f9251d655b86af5a410cfab8df285098e01cc..5a25664a15643ff148db47caad4f53376b55168e 100644
2021-06-11 12:02:28 +00:00
--- a/src/main/java/net/minecraft/world/level/chunk/storage/RegionFileStorage.java
+++ b/src/main/java/net/minecraft/world/level/chunk/storage/RegionFileStorage.java
2021-11-24 04:25:34 +00:00
@@ -11,8 +11,10 @@ import java.nio.file.Files;
import java.nio.file.Path;
2021-06-11 12:02:28 +00:00
import javax.annotation.Nullable;
import net.minecraft.nbt.CompoundTag;
+import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtIo;
2021-11-24 04:25:34 +00:00
import net.minecraft.nbt.StreamTagVisitor;
2021-06-11 12:02:28 +00:00
+import net.minecraft.nbt.Tag;
import net.minecraft.util.ExceptionCollector;
import net.minecraft.world.level.ChunkPos;
2021-11-24 04:25:34 +00:00
2021-11-27 15:07:45 +00:00
@@ -79,6 +81,71 @@ public class RegionFileStorage implements AutoCloseable {
2021-06-11 12:02:28 +00:00
}
}
+ // Paper start
2021-11-24 04:25:34 +00:00
+ private static void printOversizedLog(String msg, Path file, int x, int z) {
2021-06-11 12:02:28 +00:00
+ org.apache.logging.log4j.LogManager.getLogger().fatal(msg + " (" + file.toString().replaceAll(".+[\\\\/]", "") + " - " + x + "," + z + ") Go clean it up to remove this message. /minecraft:tp " + (x<<4)+" 128 "+(z<<4) + " - DO NOT REPORT THIS TO PAPER - You may ask for help on Discord, but do not file an issue. These error messages can not be removed.");
+ }
+
+ private static final int DEFAULT_SIZE_THRESHOLD = 1024 * 8;
+ private static final int OVERZEALOUS_TOTAL_THRESHOLD = 1024 * 64;
+ private static final int OVERZEALOUS_THRESHOLD = 1024;
+ private static int SIZE_THRESHOLD = DEFAULT_SIZE_THRESHOLD;
+ private static void resetFilterThresholds() {
+ SIZE_THRESHOLD = Math.max(1024 * 4, Integer.getInteger("Paper.FilterThreshhold", DEFAULT_SIZE_THRESHOLD));
+ }
+ static {
+ resetFilterThresholds();
+ }
+
+ static boolean isOverzealous() {
+ return SIZE_THRESHOLD == OVERZEALOUS_THRESHOLD;
+ }
+
+
+ private static CompoundTag readOversizedChunk(RegionFile regionfile, ChunkPos chunkCoordinate) throws IOException {
+ synchronized (regionfile) {
2021-06-17 21:39:36 +00:00
+ try (DataInputStream datainputstream = regionfile.getChunkDataInputStream(chunkCoordinate)) {
2021-06-11 12:02:28 +00:00
+ CompoundTag oversizedData = regionfile.getOversizedData(chunkCoordinate.x, chunkCoordinate.z);
2021-06-16 06:25:38 +00:00
+ CompoundTag chunk = NbtIo.read((DataInput) datainputstream);
2021-06-11 12:02:28 +00:00
+ if (oversizedData == null) {
+ return chunk;
+ }
+ CompoundTag oversizedLevel = oversizedData.getCompound("Level");
+
+ mergeChunkList(chunk.getCompound("Level"), oversizedLevel, "Entities", "Entities");
+ mergeChunkList(chunk.getCompound("Level"), oversizedLevel, "TileEntities", "TileEntities");
2021-06-11 12:02:28 +00:00
+
+ return chunk;
+ } catch (Throwable throwable) {
+ throwable.printStackTrace();
+ throw throwable;
+ }
+ }
+ }
+
2021-11-27 15:07:45 +00:00
+ private static void mergeChunkList(CompoundTag level, CompoundTag oversizedLevel, String key, String oversizedKey) {
2021-06-11 12:02:28 +00:00
+ ListTag levelList = level.getList(key, 10);
2021-11-27 15:07:45 +00:00
+ ListTag oversizedList = oversizedLevel.getList(oversizedKey, 10);
2021-06-11 12:02:28 +00:00
+
+ if (!oversizedList.isEmpty()) {
+ levelList.addAll(oversizedList);
+ level.put(key, levelList);
+ }
+ }
+
+ private static int getNBTSize(Tag nbtBase) {
+ DataOutputStream test = new DataOutputStream(new org.apache.commons.io.output.NullOutputStream());
+ try {
+ nbtBase.write(test);
+ return test.size();
+ } catch (IOException e) {
+ e.printStackTrace();
+ return 0;
+ }
+ }
+
+ // Paper End
+
@Nullable
public CompoundTag read(ChunkPos pos) throws IOException {
// CraftBukkit start - SPIGOT-5680: There's no good reason to preemptively create files on read, save that for writing
2021-11-27 15:07:45 +00:00
@@ -90,6 +157,12 @@ public class RegionFileStorage implements AutoCloseable {
2021-06-16 06:25:38 +00:00
try { // Paper
2021-06-11 12:02:28 +00:00
DataInputStream datainputstream = regionfile.getChunkDataInputStream(pos);
2021-06-16 06:25:38 +00:00
2021-06-11 12:02:28 +00:00
+ // Paper start
+ if (regionfile.isOversized(pos.x, pos.z)) {
2021-06-16 06:25:38 +00:00
+ printOversizedLog("Loading Oversized Chunk!", regionfile.regionFile, pos.x, pos.z);
2021-06-11 12:02:28 +00:00
+ return readOversizedChunk(regionfile, pos);
+ }
+ // Paper end
CompoundTag nbttagcompound;
2021-06-16 06:25:38 +00:00
label43:
{
Rewrite chunk system (#8177) Patch documentation to come Issues with the old system that are fixed now: - World generation does not scale with cpu cores effectively. - Relies on the main thread for scheduling and maintaining chunk state, dropping chunk load/generate rates at lower tps. - Unreliable prioritisation of chunk gen/load calls that block the main thread. - Shutdown logic is utterly unreliable, as it has to wait for all chunks to unload - is it guaranteed that the chunk system is in a state on shutdown that it can reliably do this? Watchdog shutdown also typically failed due to thread checks, which is now resolved. - Saving of data is not unified (i.e can save chunk data without saving entity data, poses problems for desync if shutdown is really abnormal. - Entities are not loaded with chunks. This caused quite a bit of headache for Chunk#getEntities API, but now the new chunk system loads entities with chunks so that they are ready whenever the chunk loads in. Effectively brings the behavior back to 1.16 era, but still storing entities in their own separate regionfiles. The above list is not complete. The patch documentation will complete it. New chunk system hard relies on starlight and dataconverter, and most importantly the new concurrent utilities in ConcurrentUtil. Some of the old async chunk i/o interface (i.e the old file io thread reroutes _some_ calls to the new file io thread) is kept for plugin compat reasons. It will be removed in the next major version of minecraft. The old legacy chunk system patches have been moved to the removed folder in case we need them again.
2022-09-26 08:02:51 +00:00
@@ -176,6 +249,7 @@ public class RegionFileStorage implements AutoCloseable {
2021-06-11 12:02:28 +00:00
2021-06-16 06:25:38 +00:00
try {
NbtIo.write(nbt, (DataOutput) dataoutputstream);
+ regionfile.setOversized(pos.x, pos.z, false); // Paper - We don't do this anymore, mojang stores differently, but clear old meta flag if it exists to get rid of our own meta file once last oversized is gone
} catch (Throwable throwable) {
if (dataoutputstream != null) {
try {