Update to 1.16, code changes

This commit is contained in:
Jinks 2021-05-04 17:58:22 +02:00
parent 37c9c2f28b
commit a3507498c3
5 changed files with 143 additions and 138 deletions

View file

@ -4,18 +4,11 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Map;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.PlayerList; import net.minecraft.world.server.ServerWorld;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.WorldServer;
import net.minecraft.world.storage.ThreadedFileIOBase;
public enum BackupHandler { public enum BackupHandler {
INSTANCE; INSTANCE;
@ -24,11 +17,10 @@ public enum BackupHandler {
public int doingBackup = 0; public int doingBackup = 0;
public boolean hadPlayersOnline = false; public boolean hadPlayersOnline = false;
private boolean youHaveBeenWarned = false; private boolean youHaveBeenWarned = false;
public void init() { public void init() {
doingBackup = 0; doingBackup = 0;
nextBackup = System.currentTimeMillis() + ExtBackupConfig.general.time(); nextBackup = System.currentTimeMillis() + ConfigHandler.COMMON.time();
File script = ExtBackupConfig.general.getScript(); File script = ConfigHandler.COMMON.getScript();
if (!script.exists()) { if (!script.exists()) {
script.getParentFile().mkdirs(); script.getParentFile().mkdirs();
@ -38,17 +30,16 @@ public enum BackupHandler {
} catch (IOException e) { } catch (IOException e) {
ExtBackup.logger.error("Backup script does not exist and cannot be created!"); ExtBackup.logger.error("Backup script does not exist and cannot be created!");
ExtBackup.logger.error("Disabling ExtBackup!"); ExtBackup.logger.error("Disabling ExtBackup!");
ExtBackupConfig.general.enabled = false; ConfigHandler.COMMON.enabled.set(false);
} }
} }
ExtBackup.logger.info("Starting "+ExtBackup.NAME+" v"+ExtBackup.VERSION);
ExtBackup.logger.info("Active script: " + script.getAbsolutePath()); ExtBackup.logger.info("Active script: " + script.getAbsolutePath());
ExtBackup.logger.info("Next Backup at: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(nextBackup))); ExtBackup.logger.info("Next Backup at: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(nextBackup)));
} }
public boolean run(MinecraftServer server) { public boolean run(MinecraftServer server) {
if (doingBackup != 0 || !ExtBackupConfig.general.enabled) { if (doingBackup != 0 || !ConfigHandler.COMMON.enabled.get()) {
return false; return false;
} }
if (doingBackup != 0) { if (doingBackup != 0) {
@ -56,7 +47,7 @@ public enum BackupHandler {
return false; return false;
} }
File script = ExtBackupConfig.general.getScript(); File script = ConfigHandler.COMMON.getScript();
if (!script.exists() || !script.canExecute()) { if (!script.exists() || !script.canExecute()) {
ExtBackup.logger.error("Cannot access or execute backup script. Bailing out!"); ExtBackup.logger.error("Cannot access or execute backup script. Bailing out!");
return false; return false;
@ -66,14 +57,13 @@ public enum BackupHandler {
try { try {
if (server.getPlayerList() != null) { if (server.getPlayerList() != null) {
server.getPlayerList().saveAllPlayerData(); server.getPlayerList().saveAll();
} }
for (WorldServer world : server.worlds) { for (ServerWorld world : server.getAllLevels()) {
if (world != null) { if (world != null) {
world.saveAllChunks(true, null); //world.save(null, true, false);
world.flushToDisk(); world.noSave = true;
world.disableLevelSaving = true;
} }
} }
} catch (Exception ex) { } catch (Exception ex) {
@ -83,7 +73,7 @@ public enum BackupHandler {
return false; return false;
} }
ThreadedFileIOBase.getThreadedIOInstance().queueIO(() -> { new Thread(() -> {
try { try {
doBackup(server, script); doBackup(server, script);
} catch (Exception ex) { } catch (Exception ex) {
@ -91,20 +81,19 @@ public enum BackupHandler {
} }
doingBackup = 2; doingBackup = 2;
return false; }).start();
});
nextBackup = System.currentTimeMillis() + ExtBackupConfig.general.time(); nextBackup = System.currentTimeMillis() + ConfigHandler.COMMON.time();
return true; return true;
} }
private void doBackup(MinecraftServer server, File script) { private int doBackup(MinecraftServer server, File script) {
ExtBackup.logger.info("Starting backup."); if (ConfigHandler.COMMON.silent.get()) {ExtBackup.logger.info("Starting backup.");}
ExtBackupUtil.broadcast(server, "Starting Backup!"); ExtBackupUtil.broadcast(server, "Starting Backup!");
ProcessBuilder pb = new ProcessBuilder(script.getAbsolutePath()); ProcessBuilder pb = new ProcessBuilder(script.getAbsolutePath());
int returnValue = -1; int returnValue = -1;
Map<String, String> env = pb.environment(); //Map<String, String> env = pb.environment();
pb.redirectErrorStream(true); pb.redirectErrorStream(true);
try { try {
Process backup = pb.start(); Process backup = pb.start();
@ -117,14 +106,16 @@ public enum BackupHandler {
} }
enableSaving(server); enableSaving(server);
youHaveBeenWarned = false; youHaveBeenWarned = false;
ExtBackup.logger.info("Backup done."); if (ConfigHandler.COMMON.silent.get()) {ExtBackup.logger.info("Backup done.");}
ExtBackupUtil.broadcast(server, "Backup done!"); ExtBackupUtil.broadcast(server, "Backup done!");
ExtBackup.logger.info("Next Backup at: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(nextBackup)));
return returnValue;
} }
private void enableSaving(MinecraftServer server) { private void enableSaving(MinecraftServer server) {
for (WorldServer world : server.worlds) { for (ServerWorld world : server.getAllLevels()) {
if (world != null) { if (world != null) {
world.disableLevelSaving = false; world.noSave = false;
} }
} }
} }
@ -132,7 +123,7 @@ public enum BackupHandler {
public void tick(MinecraftServer server, long now) { public void tick(MinecraftServer server, long now) {
if (nextBackup > 0L && nextBackup <= now) { if (nextBackup > 0L && nextBackup <= now) {
//ExtBackup.logger.info("Backup time!"); //ExtBackup.logger.info("Backup time!");
if (!ExtBackupConfig.general.only_if_players_online || hadPlayersOnline || !server.getPlayerList().getPlayers().isEmpty()) { if (!ConfigHandler.COMMON.only_if_players_online.get() || hadPlayersOnline || !server.getPlayerList().getPlayers().isEmpty()) {
hadPlayersOnline = false; hadPlayersOnline = false;
run(server); run(server);
} }
@ -147,4 +138,4 @@ public enum BackupHandler {
} }
} }
} }
} }

View file

@ -0,0 +1,76 @@
package com.github.jinks.extbackup;
import java.io.File;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.fml.loading.FMLPaths;
public final class ConfigHandler {
public static class Common {
public final ForgeConfigSpec.BooleanValue enabled;
private final ForgeConfigSpec.IntValue backup_timer;
public final ForgeConfigSpec.BooleanValue silent;
public final ForgeConfigSpec.BooleanValue only_if_players_online;
public final ForgeConfigSpec.BooleanValue force_on_shutdown;
public final ForgeConfigSpec.ConfigValue<String> script;
public Common(ForgeConfigSpec.Builder builder) {
enabled = builder
.comment("backups are enabled")
.define("enabled", true);
backup_timer = builder
.comment("interval in minutes to run the backup script")
.defineInRange("backup_timer", 10, 1 , 3600);
silent = builder
.comment("be silent, do not post backups in chat")
.define("silent", false);
only_if_players_online = builder
.comment("run only if players are online")
.define("only_if_players_online", true);
force_on_shutdown = builder
.comment("run backup on server shutdown")
.define("force_on_shutdown", true);
script = builder
.comment("script location - this script is run on each interval")
.define("script", "local/extbackup/runbackup.sh");
}
public long time() {
return (long) (ConfigHandler.COMMON.backup_timer.get() * 60000L);
}
private static File cachedScript;
public File getScript() {
String scr = ConfigHandler.COMMON.script.get();
if (scr == null) {
ExtBackup.logger.warn("Script is NULL!");
return null;
}
if (cachedScript == null) {
cachedScript = scr.trim().isEmpty() ? new File(FMLPaths.GAMEDIR.get() + "local/extbackup/runbackup.sh") : new File(scr.trim());
}
return cachedScript;
}
}
public static final Common COMMON;
public static final ForgeConfigSpec COMMON_SPEC;
static {
final Pair<Common, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(Common::new);
COMMON_SPEC = specPair.getRight();
COMMON = specPair.getLeft();
}
public static void onConfigLoad() {
//BackupHandler.INSTANCE.nextBackup = System.currentTimeMillis() + ConfigHandler.COMMON.time();
//ExtBackup.logger.info("Config Changed, next backup at: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(BackupHandler.INSTANCE.nextBackup)));
}
}

View file

@ -1,49 +1,58 @@
package com.github.jinks.extbackup; package com.github.jinks.extbackup;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import net.minecraft.init.Blocks;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.LogicalSidedProvider;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.event.server.FMLServerStartedEvent;
import net.minecraftforge.fml.common.event.FMLServerStartedEvent; import net.minecraftforge.fml.event.server.FMLServerStoppingEvent;
import net.minecraftforge.fml.common.event.FMLServerStoppingEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
@Mod(modid = ExtBackup.MODID, name = ExtBackup.NAME, version = ExtBackup.VERSION, acceptableRemoteVersions = "*") @Mod(ExtBackup.MOD_ID)
@Mod.EventBusSubscriber @Mod.EventBusSubscriber(modid = ExtBackup.MOD_ID)
public class ExtBackup { public class ExtBackup {
public static final String MODID = "extbackup"; public static final String MOD_ID = "extbackup";
public static final String NAME = "ExtBackup";
public static final String VERSION = "1.0";
public static Logger logger; public static final Logger logger = LogManager.getLogger("ExtBackup");
@Mod.EventHandler public ExtBackup() {
public void preInit(FMLPreInitializationEvent event) { ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, ConfigHandler.COMMON_SPEC);
logger = event.getModLog(); IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
modBus.addListener(this::setup);
modBus.addListener((ModConfig.Loading e) -> ConfigHandler.onConfigLoad());
modBus.addListener((ModConfig.Reloading e) -> ConfigHandler.onConfigLoad());
// Register ourselves for server and other game events we are interested in
IEventBus forgeBus = MinecraftForge.EVENT_BUS;
forgeBus.register(this);
forgeBus.addListener(this::serverAboutToStart);
forgeBus.addListener(this::serverStopping);
} }
@Mod.EventHandler private void setup(final FMLCommonSetupEvent event) {
public void init(FMLInitializationEvent event) { ConfigHandler.onConfigLoad();
// some example code
//logger.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName());
} }
@Mod.EventHandler public void serverAboutToStart(FMLServerStartedEvent event) {
public void serverStarted(FMLServerStartedEvent event) {
BackupHandler.INSTANCE.init(); BackupHandler.INSTANCE.init();
} }
@Mod.EventHandler @SubscribeEvent
public void serverStopping(FMLServerStoppingEvent event) { public void serverStopping(FMLServerStoppingEvent event) {
if (ExtBackupConfig.general.force_on_shutdown) { if (ConfigHandler.COMMON.force_on_shutdown.get()) {
MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); MinecraftServer server = event.getServer();
if (server != null) { if (server != null) {
BackupHandler.INSTANCE.run(server); BackupHandler.INSTANCE.run(server);
@ -54,7 +63,7 @@ public class ExtBackup {
@SubscribeEvent @SubscribeEvent
public static void serverTick(TickEvent.ServerTickEvent event) { public static void serverTick(TickEvent.ServerTickEvent event) {
if (event.phase != TickEvent.Phase.START) { if (event.phase != TickEvent.Phase.START) {
MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); MinecraftServer server = LogicalSidedProvider.INSTANCE.get(LogicalSide.SERVER);
if (server != null) { if (server != null) {
//logger.debug("Server Tick! " + event.phase); //logger.debug("Server Tick! " + event.phase);

View file

@ -1,73 +0,0 @@
package com.github.jinks.extbackup;
import net.minecraftforge.fml.client.config.ConfigGuiType;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.io.File;
import net.minecraftforge.common.config.Config;
import net.minecraftforge.common.config.ConfigManager;
@EventBusSubscriber(modid = ExtBackup.MODID)
@Config(modid = ExtBackup.MODID, category = "")
public class ExtBackupConfig {
public static final General general = new General();
public static class General {
@Config.Comment("Enables backups.")
public boolean enabled = true;
@Config.RangeInt(min = 1, max = 3600)
@Config.Comment({
"Timer in Minutes.",
" 5 - backups every 5 minutes",
" 60 - backups every hour",
"3600 - backups once a day",
})
public int backup_timer = 10;
@Config.Comment("If set to true, no messages will be displayed in chat/status bar.")
public boolean silent = false;
@Config.Comment("Only create backups when players have been online.")
public boolean only_if_players_online = true;
@Config.Comment("Create a backup when server is stopped.")
public boolean force_on_shutdown = true;
@Config.Comment({
"Path to backup script.",
"Default: 'local/extbackup/runbackup.sh' inside the Minecraft instance."})
public String script = "local/extbackup/runbackup.sh";
public long time() {
return (long) (backup_timer * 60000L);
}
private File cachedScript;
public File getScript() {
if (cachedScript == null) {
cachedScript = ExtBackupConfig.general.script.trim().isEmpty() ? new File(FMLCommonHandler.instance().getMinecraftServerInstance().getDataDirectory(), "local/extbackup/runbackup.sh") : new File(ExtBackupConfig.general.script.trim());
}
return cachedScript;
}
}
public static boolean sync() {
ConfigManager.sync(ExtBackup.MODID, Config.Type.INSTANCE);
general.cachedScript = null;
return true;
}
@SubscribeEvent
public static void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event)
{
if (event.getModID().equals(ExtBackup.MODID)) {
sync();
}
}
}

View file

@ -1,14 +1,16 @@
package com.github.jinks.extbackup; package com.github.jinks.extbackup;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.Util;
import net.minecraft.util.text.ChatType;
import net.minecraft.util.text.StringTextComponent;
public class ExtBackupUtil { public class ExtBackupUtil {
public static void broadcast(MinecraftServer server, String message) { public static void broadcast(MinecraftServer server, String message) {
if (!ExtBackupConfig.general.silent) { if (!ConfigHandler.COMMON.silent.get()) {
TextComponentString bcMessage = new TextComponentString("[§1ExtBackup§r] " + message); StringTextComponent bcMessage = new StringTextComponent("[§1ExtBackup§r] " + message);
server.getPlayerList().sendMessage(bcMessage); server.getPlayerList().broadcastMessage(bcMessage, ChatType.SYSTEM, Util.NIL_UUID);
} }
} }