| 1 | package net.minecraft.server;
|
| 2 |
|
| 3 | import com.mojang.authlib.services.MinecraftServicesDiscoveryService;
|
| 4 | import com.mojang.datafixers.DataFixer;
|
| 5 | import com.mojang.logging.LogUtils;
|
| 6 | import com.mojang.serialization.Dynamic;
|
| 7 | import com.mojang.serialization.Lifecycle;
|
| 8 | import java.awt.GraphicsEnvironment;
|
| 9 | import java.io.File;
|
| 10 | import java.io.IOException;
|
| 11 | import java.io.UncheckedIOException;
|
| 12 | import java.net.Proxy;
|
| 13 | import java.nio.file.Files;
|
| 14 | import java.nio.file.Path;
|
| 15 | import java.nio.file.Paths;
|
| 16 | import java.util.Optional;
|
| 17 | import java.util.function.BooleanSupplier;
|
| 18 | import joptsimple.OptionParser;
|
| 19 | import joptsimple.OptionSet;
|
| 20 | import joptsimple.OptionSpec;
|
| 21 | import joptsimple.util.PathConverter;
|
| 22 | import net.minecraft.CrashReport;
|
| 23 | import net.minecraft.DefaultUncaughtExceptionHandler;
|
| 24 | import net.minecraft.SharedConstants;
|
| 25 | import net.minecraft.SuppressForbidden;
|
| 26 | import net.minecraft.commands.Commands;
|
| 27 | import net.minecraft.core.Registry;
|
| 28 | import net.minecraft.core.RegistryAccess;
|
| 29 | import net.minecraft.core.registries.Registries;
|
| 30 | import net.minecraft.nbt.NbtException;
|
| 31 | import net.minecraft.nbt.ReportedNbtException;
|
| 32 | import net.minecraft.network.chat.Component;
|
| 33 | import net.minecraft.server.dedicated.DedicatedServer;
|
| 34 | import net.minecraft.server.dedicated.DedicatedServerProperties;
|
| 35 | import net.minecraft.server.dedicated.DedicatedServerSettings;
|
| 36 | import net.minecraft.server.jsonrpc.JsonRpc;
|
| 37 | import net.minecraft.server.jsonrpc.ManagementServer;
|
| 38 | import net.minecraft.server.notifications.NotificationManager;
|
| 39 | import net.minecraft.server.packs.repository.PackRepository;
|
| 40 | import net.minecraft.server.packs.repository.ServerPacksSource;
|
| 41 | import net.minecraft.util.Mth;
|
| 42 | import net.minecraft.util.Util;
|
| 43 | import net.minecraft.util.datafix.DataFixers;
|
| 44 | import net.minecraft.util.profiling.jfr.Environment;
|
| 45 | import net.minecraft.util.profiling.jfr.JvmProfiler;
|
| 46 | import net.minecraft.util.worldupdate.UpgradeProgress;
|
| 47 | import net.minecraft.util.worldupdate.WorldUpgrader;
|
| 48 | import net.minecraft.world.flag.FeatureFlags;
|
| 49 | import net.minecraft.world.level.LevelSettings;
|
| 50 | import net.minecraft.world.level.WorldDataConfiguration;
|
| 51 | import net.minecraft.world.level.chunk.storage.RegionFileVersion;
|
| 52 | import net.minecraft.world.level.dimension.LevelStem;
|
| 53 | import net.minecraft.world.level.levelgen.WorldDimensions;
|
| 54 | import net.minecraft.world.level.levelgen.WorldGenSettings;
|
| 55 | import net.minecraft.world.level.levelgen.WorldOptions;
|
| 56 | import net.minecraft.world.level.levelgen.presets.WorldPresets;
|
| 57 | import net.minecraft.world.level.storage.LevelDataAndDimensions;
|
| 58 | import net.minecraft.world.level.storage.LevelStorageSource;
|
| 59 | import net.minecraft.world.level.storage.LevelSummary;
|
| 60 | import net.minecraft.world.level.storage.PrimaryLevelData;
|
| 61 | import net.minecraft.world.level.storage.WorldData;
|
| 62 | import org.jspecify.annotations.Nullable;
|
| 63 | import org.slf4j.Logger;
|
| 64 |
|
| 65 | public class Main {
|
| 66 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 67 |
|
| 68 | @SuppressForbidden(reason = "System.out needed before bootstrap")
|
| 69 | public static void main(final String[] args) {
|
| 70 | SharedConstants.tryDetectVersion();
|
| 71 | OptionParser parser = new OptionParser();
|
| 72 | OptionSpec<Void> nogui = parser.accepts("nogui");
|
| 73 | OptionSpec<Void> initSettings = parser.accepts("initSettings", "Initializes 'server.properties' and 'eula.txt', then quits");
|
| 74 | OptionSpec<Void> demo = parser.accepts("demo");
|
| 75 | OptionSpec<Void> bonusChest = parser.accepts("bonusChest");
|
| 76 | OptionSpec<Void> forceUpgrade = parser.accepts("forceUpgrade");
|
| 77 | OptionSpec<Void> eraseCache = parser.accepts("eraseCache");
|
| 78 | OptionSpec<Void> recreateRegionFiles = parser.accepts("recreateRegionFiles");
|
| 79 | OptionSpec<Void> safeMode = parser.accepts("safeMode", "Loads level with vanilla datapack only");
|
| 80 | OptionSpec<Void> help = parser.accepts("help").forHelp();
|
| 81 | OptionSpec<String> universe = parser.accepts("universe").withRequiredArg().defaultsTo(".");
|
| 82 | OptionSpec<String> worldName = parser.accepts("world").withRequiredArg();
|
| 83 | OptionSpec<Integer> port = parser.accepts("port").withRequiredArg().ofType(Integer.class).defaultsTo(-1);
|
| 84 | OptionSpec<String> serverId = parser.accepts("serverId").withRequiredArg();
|
| 85 | OptionSpec<Void> jfrProfilingOption = parser.accepts("jfrProfile");
|
| 86 | OptionSpec<Path> pidFile = parser.accepts("pidFile").withRequiredArg().withValuesConvertedBy(new PathConverter());
|
| 87 | OptionSpec<String> nonOptions = parser.nonOptions();
|
| 88 |
|
| 89 | try {
|
| 90 | OptionSet options = parser.parse(args);
|
| 91 | if (options.has(help)) {
|
| 92 | parser.printHelpOn(System.err);
|
| 93 | return;
|
| 94 | }
|
| 95 |
|
| 96 | Path pidFilePath = options.valueOf(pidFile);
|
| 97 | if (pidFilePath != null) {
|
| 98 | writePidFile(pidFilePath);
|
| 99 | }
|
| 100 |
|
| 101 | CrashReport.preload();
|
| 102 | if (options.has(jfrProfilingOption)) {
|
| 103 | JvmProfiler.INSTANCE.start(Environment.SERVER);
|
| 104 | }
|
| 105 |
|
| 106 | Bootstrap.bootStrap();
|
| 107 | Bootstrap.validate();
|
| 108 | Util.startTimerHackThread();
|
| 109 | Path settingsFile = Paths.get("server.properties");
|
| 110 | DedicatedServerSettings settings = new DedicatedServerSettings(settingsFile);
|
| 111 | settings.forceSave();
|
| 112 | RegionFileVersion.configure(settings.getProperties().regionFileComression);
|
| 113 | Path eulaFile = Paths.get("eula.txt");
|
| 114 | Eula eula = new Eula(eulaFile);
|
| 115 | if (options.has(initSettings)) {
|
| 116 | LOGGER.info("Initialized '{}' and '{}'", settingsFile.toAbsolutePath(), eulaFile.toAbsolutePath());
|
| 117 | return;
|
| 118 | }
|
| 119 |
|
| 120 | if (!eula.hasAgreedToEULA()) {
|
| 121 | LOGGER.info("You need to agree to the EULA in order to run the server. Go to eula.txt for more info.");
|
| 122 | return;
|
| 123 | }
|
| 124 |
|
| 125 | File universePath = new File(options.valueOf(universe));
|
| 126 | Services services = Services.create(MinecraftServicesDiscoveryService.create(Proxy.NO_PROXY), universePath);
|
| 127 | NotificationManager notificationManager = new NotificationManager();
|
| 128 | ManagementServer jsonRpcServer = JsonRpc.create(settings, notificationManager);
|
| 129 | String levelName = Optional.ofNullable(options.valueOf(worldName)).orElse(settings.getProperties().levelName);
|
| 130 | LevelStorageSource levelStorageSource = LevelStorageSource.createDefault(universePath.toPath());
|
| 131 | LevelStorageSource.LevelStorageAccess access = levelStorageSource.validateAndCreateAccess(levelName);
|
| 132 | Dynamic<?> levelDataTag;
|
| 133 | if (access.hasWorldData()) {
|
| 134 | Dynamic<?> levelDataUnfixed;
|
| 135 | try {
|
| 136 | levelDataUnfixed = access.getUnfixedDataTagWithFallback();
|
| 137 | } catch (IOException | NbtException | ReportedNbtException ex) {
|
| 138 | LOGGER.error("Failed to load world data. World files may be corrupted. Shutting down.", ex);
|
| 139 | return;
|
| 140 | }
|
| 141 |
|
| 142 | LevelSummary summary = access.fixAndGetSummaryFromTag(levelDataUnfixed);
|
| 143 | if (summary.requiresManualConversion()) {
|
| 144 | LOGGER.info("This world must be opened in an older version (like 1.6.4) to be safely converted");
|
| 145 | return;
|
| 146 | }
|
| 147 |
|
| 148 | if (!summary.isCompatible()) {
|
| 149 | LOGGER.info("This world was created by an incompatible version.");
|
| 150 | return;
|
| 151 | }
|
| 152 |
|
| 153 | levelDataTag = DataFixers.getFileFixer().fix(access, levelDataUnfixed, new UpgradeProgress(notificationManager));
|
| 154 | } else {
|
| 155 | levelDataTag = null;
|
| 156 | }
|
| 157 |
|
| 158 | boolean safeModeEnabled = options.has(safeMode);
|
| 159 | if (safeModeEnabled) {
|
| 160 | LOGGER.warn("Safe mode active, only vanilla datapack will be loaded");
|
| 161 | }
|
| 162 |
|
| 163 | PackRepository packRepository = ServerPacksSource.createPackRepository(access);
|
| 164 |
|
| 165 | WorldStem worldStem;
|
| 166 | try {
|
| 167 | WorldLoader.InitConfig worldLoadConfig = loadOrCreateConfig(settings.getProperties(), levelDataTag, safeModeEnabled, packRepository);
|
| 168 | worldStem = Util.<WorldStem>blockUntilDone(
|
| 169 | executor -> WorldLoader.load(
|
| 170 | worldLoadConfig,
|
| 171 | context -> {
|
| 172 | Registry<LevelStem> datapackDimensions = context.datapackDimensions().lookupOrThrow(Registries.LEVEL_STEM);
|
| 173 | if (levelDataTag != null) {
|
| 174 | LevelDataAndDimensions worldData = LevelStorageSource.getLevelDataAndDimensions(
|
| 175 | access, levelDataTag, context.dataConfiguration(), datapackDimensions, context.datapackWorldRegistries()
|
| 176 | );
|
| 177 | return new WorldLoader.DataLoadOutput<>(worldData.worldDataAndGenSettings(), worldData.dimensions().dimensionsRegistryAccess());
|
| 178 | } else {
|
| 179 | LOGGER.info("No existing world data, creating new world");
|
| 180 | return createNewWorldData(settings, context, datapackDimensions, options.has(demo), options.has(bonusChest));
|
| 181 | }
|
| 182 | },
|
| 183 | WorldStem::new,
|
| 184 | Util.backgroundExecutor(),
|
| 185 | executor
|
| 186 | )
|
| 187 | )
|
| 188 | .get();
|
| 189 | } catch (Exception e) {
|
| 190 | LOGGER.warn("Failed to load datapacks, can't proceed with server load. You can either fix your datapacks or reset to vanilla with --safeMode", e);
|
| 191 | return;
|
| 192 | }
|
| 193 |
|
| 194 | RegistryAccess.Frozen registryHolder = worldStem.registries().compositeAccess();
|
| 195 | WorldData data = worldStem.worldDataAndGenSettings().data();
|
| 196 | boolean recreateRegionFilesValue = options.has(recreateRegionFiles);
|
| 197 | if (options.has(forceUpgrade) || recreateRegionFilesValue) {
|
| 198 | forceUpgrade(access, DataFixers.getDataFixer(), options.has(eraseCache), () -> true, registryHolder, recreateRegionFilesValue);
|
| 199 | }
|
| 200 |
|
| 201 | access.saveDataTag(data);
|
| 202 | final DedicatedServer dedicatedServer = MinecraftServer.spin(
|
| 203 | thread -> {
|
| 204 | DedicatedServer server = new DedicatedServer(
|
| 205 | thread, access, packRepository, worldStem, Optional.empty(), settings, DataFixers.getDataFixer(), services, jsonRpcServer, notificationManager
|
| 206 | );
|
| 207 | notificationManager.setServer(server);
|
| 208 | server.setPort(options.valueOf(port));
|
| 209 | server.setDemo(options.has(demo));
|
| 210 | server.setId(options.valueOf(serverId));
|
| 211 | boolean gui = !options.has(nogui) && !options.valuesOf(nonOptions).contains("nogui");
|
| 212 | if (gui && !GraphicsEnvironment.isHeadless()) {
|
| 213 | server.showGui();
|
| 214 | }
|
| 215 |
|
| 216 | return server;
|
| 217 | }
|
| 218 | );
|
| 219 | Thread shutdownThread = new Thread("Server Shutdown Thread") {
|
| 220 | @Override
|
| 221 | public void run() {
|
| 222 | dedicatedServer.halt(true);
|
| 223 | }
|
| 224 | };
|
| 225 | shutdownThread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER));
|
| 226 | Runtime.getRuntime().addShutdownHook(shutdownThread);
|
| 227 | } catch (Throwable t) {
|
| 228 | LOGGER.error(LogUtils.FATAL_MARKER, "Failed to start the minecraft server", t);
|
| 229 | }
|
| 230 | }
|
| 231 |
|
| 232 | private static WorldLoader.DataLoadOutput<LevelDataAndDimensions.WorldDataAndGenSettings> createNewWorldData(
|
| 233 | final DedicatedServerSettings settings,
|
| 234 | final WorldLoader.DataLoadContext context,
|
| 235 | final Registry<LevelStem> datapackDimensions,
|
| 236 | final boolean demoMode,
|
| 237 | final boolean bonusChest
|
| 238 | ) {
|
| 239 | LevelSettings createLevelSettings;
|
| 240 | WorldOptions worldOptions;
|
| 241 | WorldDimensions dimensions;
|
| 242 | if (demoMode) {
|
| 243 | createLevelSettings = MinecraftServer.DEMO_SETTINGS;
|
| 244 | worldOptions = WorldOptions.DEMO_OPTIONS;
|
| 245 | dimensions = WorldPresets.createNormalWorldDimensions(context.datapackWorldRegistries());
|
| 246 | } else {
|
| 247 | DedicatedServerProperties properties = settings.getProperties();
|
| 248 | createLevelSettings = new LevelSettings(
|
| 249 | properties.levelName,
|
| 250 | properties.gameMode.get(),
|
| 251 | new LevelSettings.DifficultySettings(properties.difficulty.get(), properties.hardcore, false),
|
| 252 | false,
|
| 253 | context.dataConfiguration()
|
| 254 | );
|
| 255 | worldOptions = bonusChest ? properties.worldOptions.withBonusChest(true) : properties.worldOptions;
|
| 256 | dimensions = properties.createDimensions(context.datapackWorldRegistries());
|
| 257 | }
|
| 258 |
|
| 259 | WorldDimensions.Complete finalDimensions = dimensions.bake(datapackDimensions);
|
| 260 | Lifecycle lifecycle = finalDimensions.lifecycle().add(context.datapackWorldRegistries().allRegistriesLifecycle());
|
| 261 | PrimaryLevelData primaryLevelData = new PrimaryLevelData(createLevelSettings, finalDimensions.specialWorldProperty(), lifecycle);
|
| 262 | return new WorldLoader.DataLoadOutput<>(
|
| 263 | new LevelDataAndDimensions.WorldDataAndGenSettings(primaryLevelData, new WorldGenSettings(worldOptions, dimensions)),
|
| 264 | finalDimensions.dimensionsRegistryAccess()
|
| 265 | );
|
| 266 | }
|
| 267 |
|
| 268 | private static void writePidFile(final Path path) {
|
| 269 | try {
|
| 270 | long pid = ProcessHandle.current().pid();
|
| 271 | Files.writeString(path, Long.toString(pid));
|
| 272 | } catch (IOException e) {
|
| 273 | throw new UncheckedIOException(e);
|
| 274 | }
|
| 275 | }
|
| 276 |
|
| 277 | private static WorldLoader.InitConfig loadOrCreateConfig(
|
| 278 | final DedicatedServerProperties properties, final @Nullable Dynamic<?> levelDataTag, final boolean safeModeEnabled, final PackRepository packRepository
|
| 279 | ) {
|
| 280 | boolean initMode;
|
| 281 | WorldDataConfiguration dataConfigToUse;
|
| 282 | if (levelDataTag != null) {
|
| 283 | WorldDataConfiguration storedConfiguration = LevelStorageSource.readDataConfig(levelDataTag);
|
| 284 | initMode = false;
|
| 285 | dataConfigToUse = storedConfiguration;
|
| 286 | } else {
|
| 287 | initMode = true;
|
| 288 | dataConfigToUse = new WorldDataConfiguration(properties.initialDataPackConfiguration, FeatureFlags.DEFAULT_FLAGS);
|
| 289 | }
|
| 290 |
|
| 291 | WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packRepository, dataConfigToUse, safeModeEnabled, initMode);
|
| 292 | return new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, properties.functionPermissions);
|
| 293 | }
|
| 294 |
|
| 295 | private static void forceUpgrade(
|
| 296 | final LevelStorageSource.LevelStorageAccess storageSource,
|
| 297 | final DataFixer fixerUpper,
|
| 298 | final boolean eraseCache,
|
| 299 | final BooleanSupplier isRunning,
|
| 300 | final RegistryAccess registryAccess,
|
| 301 | final boolean recreateRegionFiles
|
| 302 | ) {
|
| 303 | LOGGER.info("Forcing world upgrade!");
|
| 304 |
|
| 305 | try (WorldUpgrader upgrader = new WorldUpgrader(storageSource, fixerUpper, registryAccess, eraseCache, recreateRegionFiles)) {
|
| 306 | Component lastStatus = null;
|
| 307 |
|
| 308 | while (!upgrader.isFinished()) {
|
| 309 | Component status = upgrader.getStatus();
|
| 310 | if (lastStatus != status) {
|
| 311 | lastStatus = status;
|
| 312 | LOGGER.info("{}", upgrader.getStatus().getString());
|
| 313 | }
|
| 314 |
|
| 315 | int totalChunks = upgrader.getTotalChunks();
|
| 316 | if (totalChunks > 0) {
|
| 317 | int done = upgrader.getConverted() + upgrader.getSkipped();
|
| 318 | LOGGER.info("{}% completed ({} / {} chunks)...", Mth.floor((float)done / totalChunks * 100.0F), done, totalChunks);
|
| 319 | }
|
| 320 |
|
| 321 | if (!isRunning.getAsBoolean()) {
|
| 322 | upgrader.cancel();
|
| 323 | } else {
|
| 324 | try {
|
| 325 | Thread.sleep(1000L);
|
| 326 | } catch (InterruptedException var12) {
|
| 327 | }
|
| 328 | }
|
| 329 | }
|
| 330 | }
|
| 331 | }
|
| 332 | }
|
| 333 |
|