2021-06-11 14:02:28 +02:00
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Spottedleaf <Spottedleaf@users.noreply.github.com>
Date: Thu, 20 May 2021 07:02:22 -0700
Subject: [PATCH] Fix and optimise world force upgrading
The WorldUpgrader class was incorrectly modified by
CB. It will store an IChunkLoader instance for all
dimension types in the world, but obviously with how
CB shifts around worlds only one dimension type exists
per world. But this would be OK if CB did this
change correctly. All IChunkLoader instances
will point to the same regionfiles. And all
IChunkLoader instances are going to be read from.
This problem hasn't really been reported because
it relies on the persistent legacy data to be converted
as well to cause corruption. Why? Because the legacy
data is also shared, it will result in different
outputs from conversion (as once conversion for legacy
persistent data takes place, it is REMOVED - so the next
convert will _not_ have the data). Which means different
sizes on disk. Which means different regionfile sector
allocations. Which means there are 3 different possible
regionfile sector allocations in memory, and none of them
are going to be correct.
I've fixed this by writing a world upgrader suited to
CB's changes to world folder format. It was brain dead
easy to add threading, so I did.
diff --git a/src/main/java/io/papermc/paper/world/ThreadedWorldUpgrader.java b/src/main/java/io/papermc/paper/world/ThreadedWorldUpgrader.java
new file mode 100644
2021-06-26 03:56:12 +02:00
index 0000000000000000000000000000000000000000..389faf099ff64bb2845222600552c8fc2c83485f
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/world/ThreadedWorldUpgrader.java
2021-06-26 03:56:12 +02:00
@@ -0,0 +1,202 @@
2021-06-11 14:02:28 +02:00
+package io.papermc.paper.world;
+
+import com.mojang.datafixers.DataFixer;
+import net.minecraft.SharedConstants;
+import net.minecraft.nbt.CompoundTag;
+import net.minecraft.resources.ResourceKey;
+import net.minecraft.util.worldupdate.WorldUpgrader;
+import net.minecraft.world.level.ChunkPos;
+import net.minecraft.world.level.chunk.storage.ChunkStorage;
+import net.minecraft.world.level.chunk.storage.RegionFileStorage;
+import net.minecraft.world.level.dimension.DimensionType;
+import net.minecraft.world.level.dimension.LevelStem;
+import net.minecraft.world.level.storage.DimensionDataStorage;
+import net.minecraft.world.level.storage.LevelStorageSource;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import java.io.File;
+import java.io.IOException;
+import java.text.DecimalFormat;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Supplier;
+
+public class ThreadedWorldUpgrader {
+
+ private static final Logger LOGGER = LogManager.getLogger();
+
+ private final ResourceKey<LevelStem> dimensionType;
+ private final ResourceKey<DimensionType> worldKey;
+ private final String worldName;
2021-06-26 03:56:12 +02:00
+ private final File worldDir;
2021-06-11 14:02:28 +02:00
+ private final ExecutorService threadPool;
+ private final DataFixer dataFixer;
+ private final boolean removeCaches;
+
2021-06-26 03:56:12 +02:00
+ public ThreadedWorldUpgrader(final ResourceKey<LevelStem> dimensionType, final ResourceKey<DimensionType> worldKey, final String worldName, final File worldDir, final int threads,
2021-06-11 14:02:28 +02:00
+ final DataFixer dataFixer, final boolean removeCaches) {
+ this.dimensionType = dimensionType;
+ this.worldKey = worldKey;
+ this.worldName = worldName;
2021-06-26 03:56:12 +02:00
+ this.worldDir = worldDir;
2021-06-11 14:02:28 +02:00
+ this.threadPool = Executors.newFixedThreadPool(Math.max(1, threads), new ThreadFactory() {
+ private final AtomicInteger threadCounter = new AtomicInteger();
+
+ @Override
+ public Thread newThread(final Runnable run) {
+ final Thread ret = new Thread(run);
+
+ ret.setName("World upgrader thread for world " + ThreadedWorldUpgrader.this.worldName + " #" + this.threadCounter.getAndIncrement());
+ ret.setUncaughtExceptionHandler((thread, throwable) -> {
+ LOGGER.fatal("Error upgrading world", throwable);
+ });
+
+ return ret;
+ }
+ });
+ this.dataFixer = dataFixer;
+ this.removeCaches = removeCaches;
+ }
+
+ public void convert() {
2021-06-26 03:56:12 +02:00
+ final File worldFolder = LevelStorageSource.getFolder(this.worldDir, this.dimensionType);
2021-06-11 14:02:28 +02:00
+ final DimensionDataStorage worldPersistentData = new DimensionDataStorage(new File(worldFolder, "data"), this.dataFixer);
+
+ final File regionFolder = new File(worldFolder, "region");
+
+ LOGGER.info("Force upgrading " + this.worldName);
+ LOGGER.info("Counting regionfiles for " + this.worldName);
+ final File[] regionFiles = regionFolder.listFiles((final File dir, final String name) -> {
2021-06-15 04:59:31 +02:00
+ return WorldUpgrader.REGEX.matcher(name).matches();
2021-06-11 14:02:28 +02:00
+ });
+ if (regionFiles == null) {
+ LOGGER.info("Found no regionfiles to convert for world " + this.worldName);
+ return;
+ }
+ LOGGER.info("Found " + regionFiles.length + " regionfiles to convert");
+ LOGGER.info("Starting conversion now for world " + this.worldName);
+
+ final WorldInfo info = new WorldInfo(() -> worldPersistentData,
+ new ChunkStorage(regionFolder, this.dataFixer, false), this.removeCaches, this.worldKey);
+
+ long expectedChunks = (long)regionFiles.length * (32L * 32L);
+
+ for (final File regionFile : regionFiles) {
+ final ChunkPos regionPos = RegionFileStorage.getRegionFileCoordinates(regionFile);
+ if (regionPos == null) {
+ expectedChunks -= (32L * 32L);
+ continue;
+ }
+
+ this.threadPool.execute(new ConvertTask(info, regionPos.x >> 5, regionPos.z >> 5));
+ }
+ this.threadPool.shutdown();
+
+ final DecimalFormat format = new DecimalFormat("#0.00");
+
+ final long start = System.nanoTime();
+
+ while (!this.threadPool.isTerminated()) {
+ final long current = info.convertedChunks.get();
+
+ LOGGER.info("{}% completed ({} / {} chunks)...", format.format((double)current / (double)expectedChunks * 100.0), current, expectedChunks);
+
+ try {
+ Thread.sleep(1000L);
+ } catch (final InterruptedException ignore) {}
+ }
+
+ final long end = System.nanoTime();
+
+ try {
+ info.loader.close();
+ } catch (final IOException ex) {
+ LOGGER.fatal("Failed to close chunk loader", ex);
+ }
+ LOGGER.info("Completed conversion. Took {}s, {} out of {} chunks needed to be converted/modified ({}%)",
+ (int)Math.ceil((end - start) * 1.0e-9), info.modifiedChunks.get(), expectedChunks, format.format((double)info.modifiedChunks.get() / (double)expectedChunks * 100.0));
+ }
+
+ private static final class WorldInfo {
+
+ public final Supplier<DimensionDataStorage> persistentDataSupplier;
+ public final ChunkStorage loader;
+ public final boolean removeCaches;
+ public final ResourceKey<DimensionType> worldKey;
+ public final AtomicLong convertedChunks = new AtomicLong();
+ public final AtomicLong modifiedChunks = new AtomicLong();
+
+ private WorldInfo(final Supplier<DimensionDataStorage> persistentDataSupplier, final ChunkStorage loader, final boolean removeCaches,
+ final ResourceKey<DimensionType> worldKey) {
+ this.persistentDataSupplier = persistentDataSupplier;
+ this.loader = loader;
+ this.removeCaches = removeCaches;
+ this.worldKey = worldKey;
+ }
+ }
+
+ private static final class ConvertTask implements Runnable {
+
+ private final WorldInfo worldInfo;
+ private final int regionX;
+ private final int regionZ;
+
+ public ConvertTask(final WorldInfo worldInfo, final int regionX, final int regionZ) {
+ this.worldInfo = worldInfo;
+ this.regionX = regionX;
+ this.regionZ = regionZ;
+ }
+
+ @Override
+ public void run() {
+ final int regionCX = this.regionX << 5;
+ final int regionCZ = this.regionZ << 5;
+
+ final Supplier<DimensionDataStorage> persistentDataSupplier = this.worldInfo.persistentDataSupplier;
+ final ChunkStorage loader = this.worldInfo.loader;
+ final boolean removeCaches = this.worldInfo.removeCaches;
+ final ResourceKey<DimensionType> worldKey = this.worldInfo.worldKey;
+
+ for (int cz = regionCZ; cz < (regionCZ + 32); ++cz) {
+ for (int cx = regionCX; cx < (regionCX + 32); ++cx) {
+ final ChunkPos chunkPos = new ChunkPos(cx, cz);
+ try {
+ // no need to check the coordinate of the chunk, the regionfilecache does that for us
+
+ CompoundTag chunkNBT = loader.read(chunkPos);
+
+ if (chunkNBT == null) {
+ continue;
+ }
+
+ final int versionBefore = ChunkStorage.getVersion(chunkNBT);
+
+ chunkNBT = loader.getChunkData(worldKey, persistentDataSupplier, chunkNBT, chunkPos, null);
+
+ boolean modified = versionBefore < SharedConstants.getCurrentVersion().getWorldVersion();
+
+ if (removeCaches) {
+ final CompoundTag level = chunkNBT.getCompound("Level");
+ modified |= level.contains("Heightmaps");
+ level.remove("Heightmaps");
+ modified |= level.contains("isLightOn");
+ level.remove("isLightOn");
+ }
+
+ if (modified) {
+ this.worldInfo.modifiedChunks.getAndIncrement();
+ loader.write(chunkPos, chunkNBT);
+ }
+ } catch (final Exception ex) {
+ LOGGER.error("Error upgrading chunk {}", chunkPos, ex);
+ } finally {
+ this.worldInfo.convertedChunks.getAndIncrement();
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/main/java/net/minecraft/server/Main.java b/src/main/java/net/minecraft/server/Main.java
2021-06-26 03:56:12 +02:00
index cf0a74b8a1c31d4bc493eb09a69ee2bd94cb6485..cfd43069ee2b6f79afb12e10d223f6bf75100034 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/server/Main.java
+++ b/src/main/java/net/minecraft/server/Main.java
@@ -15,6 +15,7 @@ import java.nio.file.Paths;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.BooleanSupplier;
+import io.papermc.paper.world.ThreadedWorldUpgrader;
import joptsimple.NonOptionArgumentSpec;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
2021-06-15 04:59:31 +02:00
@@ -283,6 +284,15 @@ public class Main {
2021-06-11 14:02:28 +02:00
}
// Paper end
+ // Paper start - fix and optimise world upgrading
2021-06-26 03:56:12 +02:00
+ public static void convertWorldButItWorks(ResourceKey<LevelStem> dimensionType, ResourceKey<DimensionType> worldKey, net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess worldSession,
2021-06-11 14:02:28 +02:00
+ DataFixer dataFixer, boolean removeCaches) {
+ int threads = Runtime.getRuntime().availableProcessors() * 3 / 8;
2021-06-26 03:56:12 +02:00
+ final ThreadedWorldUpgrader worldUpgrader = new ThreadedWorldUpgrader(dimensionType, worldKey, worldSession.getLevelId(), worldSession.levelPath.toFile(), threads, dataFixer, removeCaches);
2021-06-11 14:02:28 +02:00
+ worldUpgrader.convert();
+ }
+ // Paper end - fix and optimise world upgrading
+
public static void forceUpgrade(LevelStorageSource.LevelStorageAccess session, DataFixer dataFixer, boolean eraseCache, BooleanSupplier booleansupplier, ImmutableSet<ResourceKey<DimensionType>> worlds) { // CraftBukkit
Main.LOGGER.info("Forcing world upgrade! {}", session.getLevelId()); // CraftBukkit
WorldUpgrader worldupgrader = new WorldUpgrader(session, dataFixer, worlds, eraseCache);
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
2021-07-07 08:52:40 +02:00
index 2399625457421a1c16d0f22a82cabe6e80ef9b43..f5f1b1741b08344a4247d096d60865cc267bd50f 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
2021-07-07 08:52:40 +02:00
@@ -559,13 +559,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
2021-06-11 14:02:28 +02:00
worlddata = new PrimaryLevelData(worldsettings, generatorsettings, Lifecycle.stable());
}
worlddata.checkName(name); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to take the last loaded world as respawn (in this case the end)
2021-06-15 04:59:31 +02:00
- if (this.options.has("forceUpgrade")) {
- net.minecraft.server.Main.forceUpgrade(worldSession, DataFixers.getDataFixer(), this.options.has("eraseCache"), () -> {
2021-06-11 14:02:28 +02:00
- return true;
- }, worlddata.worldGenSettings().dimensions().entrySet().stream().map((entry1) -> {
- return ResourceKey.create(Registry.DIMENSION_TYPE_REGISTRY, ((ResourceKey) entry1.getKey()).location());
- }).collect(ImmutableSet.toImmutableSet()));
- }
+ // Paper - move down
ServerLevelData iworlddataserver = worlddata;
WorldGenSettings generatorsettings = worlddata.worldGenSettings();
2021-07-07 08:52:40 +02:00
@@ -585,6 +579,14 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
2021-06-11 14:02:28 +02:00
chunkgenerator = worlddimension.generator();
}
+ // Paper start - fix and optimise world upgrading
+ if (options.has("forceUpgrade")) {
+ net.minecraft.server.Main.convertWorldButItWorks(
2021-06-26 03:56:12 +02:00
+ dimensionKey, Level.getDimensionKey(dimensionmanager), worldSession, DataFixers.getDataFixer(), options.has("eraseCache")
2021-06-11 14:02:28 +02:00
+ );
+ }
+ // Paper end - fix and optimise world upgrading
+
ResourceKey<Level> worldKey = ResourceKey.create(Registry.DIMENSION_REGISTRY, dimensionKey.location());
if (dimensionKey == LevelStem.OVERWORLD) {
diff --git a/src/main/java/net/minecraft/world/level/Level.java b/src/main/java/net/minecraft/world/level/Level.java
2021-07-07 08:52:40 +02:00
index e095f699a1e79e89fa87cb1d7096316450274495..b85d0222bb151ff3c7377e444a431212e262c95f 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/world/level/Level.java
+++ b/src/main/java/net/minecraft/world/level/Level.java
2021-07-07 08:52:40 +02:00
@@ -175,6 +175,15 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
2021-06-15 15:20:52 +02:00
public final Map<Explosion.CacheKey, Float> explosionDensityCache = new HashMap<>(); // Paper - Optimize explosions
public java.util.ArrayDeque<net.minecraft.world.level.block.RedstoneTorchBlock.Toggle> redstoneUpdateInfos; // Paper - Move from Map in BlockRedstoneTorch to here
2021-06-11 14:02:28 +02:00
+ // Paper start - fix and optimise world upgrading
+ // copied from below
+ public static ResourceKey<DimensionType> getDimensionKey(DimensionType manager) {
2021-06-15 04:59:31 +02:00
+ return ((org.bukkit.craftbukkit.CraftServer)org.bukkit.Bukkit.getServer()).getHandle().getServer().registryHolder.ownedRegistryOrThrow(net.minecraft.core.Registry.DIMENSION_TYPE_REGISTRY).getResourceKey(manager).orElseThrow(() -> {
2021-06-11 14:02:28 +02:00
+ return new IllegalStateException("Unregistered dimension type: " + manager);
+ });
+ }
+ // Paper end - fix and optimise world upgrading
2021-06-15 15:20:52 +02:00
+
public CraftWorld getWorld() {
return this.world;
}
2021-06-11 14:02:28 +02:00
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
2021-06-18 07:51:04 +02:00
index 43510774d489bfdd30f10d521e424fa1363b8919..6496108953effae82391b5c1ea6fdec8482731cd 100644
2021-06-11 14:02:28 +02: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-06-16 08:25:38 +02:00
@@ -31,6 +31,28 @@ public class RegionFileStorage implements AutoCloseable {
2021-06-15 04:59:31 +02:00
}
2021-06-11 14:02:28 +02:00
// Paper start
+ public static ChunkPos getRegionFileCoordinates(File file) {
+ String fileName = file.getName();
+ if (!fileName.startsWith("r.") || !fileName.endsWith(".mca")) {
+ return null;
+ }
+
+ String[] split = fileName.split("\\.");
+
+ if (split.length != 4) {
+ return null;
+ }
+
+ try {
+ int x = Integer.parseInt(split[1]);
+ int z = Integer.parseInt(split[2]);
+
+ return new ChunkPos(x << 5, z << 5);
+ } catch (NumberFormatException ex) {
+ return null;
+ }
+ }
+
2021-06-15 04:59:31 +02:00
public synchronized RegionFile getRegionFileIfLoaded(ChunkPos chunkcoordintpair) {
2021-06-11 14:02:28 +02:00
return this.regionCache.getAndMoveToFirst(ChunkPos.asLong(chunkcoordintpair.getRegionX(), chunkcoordintpair.getRegionZ()));
}
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
2021-07-18 09:41:53 +02:00
index 69489893e648e72e95d8522a5990f27535fc3c0d..dd435909ad16a7f732fd0a2056f986dd9b24c0d5 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
2021-06-20 21:25:59 +02:00
@@ -1138,14 +1138,7 @@ public final class CraftServer implements Server {
2021-06-11 14:02:28 +02:00
}
worlddata.checkName(name);
2021-06-15 04:59:31 +02:00
worlddata.setModdedInfo(this.console.getServerModName(), this.console.getModdedStatus().isPresent());
2021-06-11 14:02:28 +02:00
-
- if (console.options.has("forceUpgrade")) {
- net.minecraft.server.Main.forceUpgrade(worldSession, DataFixers.getDataFixer(), console.options.has("eraseCache"), () -> {
- return true;
- }, worlddata.worldGenSettings().dimensions().entrySet().stream().map((entry) -> {
- return ResourceKey.create(Registry.DIMENSION_TYPE_REGISTRY, ((ResourceKey) entry.getKey()).location());
- }).collect(ImmutableSet.toImmutableSet()));
- }
+ // Paper - move down
long j = BiomeManager.obfuscateSeed(creator.seed());
List<CustomSpawner> list = ImmutableList.of(new PhantomSpawner(), new PatrolSpawner(), new CatSpawner(), new VillageSiege(), new WanderingTraderSpawner(worlddata));
2021-06-20 21:25:59 +02:00
@@ -1162,6 +1155,14 @@ public final class CraftServer implements Server {
2021-06-11 14:02:28 +02:00
chunkgenerator = worlddimension.generator();
}
+ // Paper start - fix and optimise world upgrading
+ if (console.options.has("forceUpgrade")) {
+ net.minecraft.server.Main.convertWorldButItWorks(
2021-06-26 03:56:12 +02:00
+ actualDimension, net.minecraft.world.level.Level.getDimensionKey(dimensionmanager), worldSession, DataFixers.getDataFixer(), console.options.has("eraseCache")
2021-06-11 14:02:28 +02:00
+ );
+ }
+ // Paper end - fix and optimise world upgrading
+
ResourceKey<net.minecraft.world.level.Level> worldKey;
String levelName = this.getServer().getProperties().levelName;
if (name.equals(levelName + "_nether")) {