diff --git a/Jenkinsfile b/Jenkinsfile index 526b319..2ad5a65 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -24,7 +24,7 @@ pipeline { echo "repoPassword=$REPO_PASS" >> gradle.properties chmod +x ./gradlew - ./gradlew clean shadowJar + ./gradlew clean shadowJar webDistribution rm -f gradle.properties ''' @@ -36,6 +36,7 @@ pipeline { archiveArtifacts artifacts: 'wcloud-api/build/libs/*.jar', fingerprint: true archiveArtifacts artifacts: 'wcloud-plugin/build/libs/*.jar', fingerprint: true archiveArtifacts artifacts: 'wcloud-launcher/build/libs/*.jar', fingerprint: true + archiveArtifacts artifacts: 'build/distributions/wcloud-web.zip', fingerprint: true archiveArtifacts artifacts: 'wcloud-runnable/**/build/libs/*.jar', fingerprint: true archiveArtifacts artifacts: 'wcloud-modules/**/build/libs/*.jar', fingerprint: true } diff --git a/build.gradle.kts b/build.gradle.kts index 060e1fe..bb25bdb 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -9,6 +9,30 @@ plugins { defaultTasks("build", "test", "shadowJar") +tasks.register("webDistribution") { + group = "distribution" + description = "Packages a self-contained wCloud launcher, master, daemon and default modules." + archiveFileName.set("wcloud-web.zip") + destinationDirectory.set(layout.buildDirectory.dir("distributions")) + + fun includeJar(projectPath: String, jarName: String, target: String) { + dependsOn("$projectPath:shadowJar") + from(project(projectPath).layout.buildDirectory.file("libs/$jarName")) { into(target) } + } + + includeJar(":wcloud-launcher", Files.launcher, "") + includeJar(":wcloud-runnable:wcloud-master", Files.master, "dependency") + includeJar(":wcloud-runnable:wcloud-daemon", Files.daemon, "dependency") + includeJar(":wcloud-api", Files.api, "local/GLOBAL/EVERY/plugins") + includeJar(":wcloud-plugin", Files.plugin, "local/GLOBAL/EVERY/plugins") + includeJar(":wcloud-modules:wmodule-permissions", Files.permissions, "modules") + includeJar(":wcloud-modules:wmodule-signs", Files.signs, "modules") + includeJar(":wcloud-modules:wmodule-npc", Files.npc, "modules") + includeJar(":wcloud-modules:wmodule-syncplayer", Files.syncplayer, "modules") + from("wcloud-launcher/src/main/dist") + from("WEB_SETUP.md") +} + allprojects { version = Versions.wcloud diff --git a/wcloud-driver/build.gradle.kts b/wcloud-driver/build.gradle.kts index c03b972..9f2bea1 100644 --- a/wcloud-driver/build.gradle.kts +++ b/wcloud-driver/build.gradle.kts @@ -14,6 +14,8 @@ dependencies { "implementation"(projects.wcloudNetworking) "implementation"(libs.gson) + "implementation"("org.yaml:snakeyaml:2.7") + "implementation"("com.moandjiezana.toml:toml4j:0.7.2") "implementation"(libs.guava) "implementation"(libs.sqlite) diff --git a/wcloud-driver/src/main/java/de/wcloudservice/driver/Driver.java b/wcloud-driver/src/main/java/de/wcloudservice/driver/Driver.java index ec99739..831dd48 100644 --- a/wcloud-driver/src/main/java/de/wcloudservice/driver/Driver.java +++ b/wcloud-driver/src/main/java/de/wcloudservice/driver/Driver.java @@ -1,6 +1,7 @@ package de.wcloudservice.driver; -import de.wcloudservice.driver.configuration.daemon.DaemonConfig; +import de.wcloudservice.driver.dashboard.DashboardRuntime; +import com.google.gson.JsonObject; import de.wcloudservice.driver.playercache.PlayerCacheDriver; import de.wcloudservice.driver.configuration.ConfigDriver; import de.wcloudservice.driver.event.EventDriver; @@ -24,6 +25,18 @@ public final class Driver { @Setter private boolean ready = false; + @Setter + private volatile DashboardRuntime dashboardRuntime; + + @Setter + private volatile java.util.function.Function dashboardPermissions; + + @Setter + private volatile Runnable dashboardShutdown; + + @Setter + private volatile Runnable dashboardRestart; + private final ConfigDriver configDriver = new ConfigDriver(); private final EventDriver eventDriver = new EventDriver(); private final TerminalDriver terminalDriver = new TerminalDriver(); diff --git a/wcloud-driver/src/main/java/de/wcloudservice/driver/configuration/ConfigDriver.java b/wcloud-driver/src/main/java/de/wcloudservice/driver/configuration/ConfigDriver.java index 2f1ef02..94db2fd 100644 --- a/wcloud-driver/src/main/java/de/wcloudservice/driver/configuration/ConfigDriver.java +++ b/wcloud-driver/src/main/java/de/wcloudservice/driver/configuration/ConfigDriver.java @@ -2,8 +2,15 @@ package de.wcloudservice.driver.configuration; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; import de.weapie.devlok.files.config.DevlokConfig; +import de.weapie.devlok.files.config.annotations.Config; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; @@ -12,6 +19,14 @@ public class ConfigDriver { protected final Gson GSON = (new GsonBuilder()).serializeNulls().setPrettyPrinting().disableHtmlEscaping().create(); public synchronized T read(String path, Class clazz) { + JsonElement raw = referencedConfig(path, clazz); + if (raw != null) { + try { + return GSON.fromJson(ManagedValues.load().resolve(raw), clazz); + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + } return DevlokConfig.builder(clazz).withPath(path).build().read(); } @@ -32,6 +47,16 @@ public class ConfigDriver { public synchronized void saveAndWait(String path, T config) { Class clazz = (Class) config.getClass(); + JsonElement raw = referencedConfig(path, clazz); + if (raw != null) { + try { + JsonElement saved = restoreReferences(raw, GSON.toJsonTree(config)); + ManagedValues.write(configFile(path, clazz), GSON.toJson(saved) + "\n"); + return; + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + } DevlokConfig devlokConfig = DevlokConfig.builder(clazz) .withDefault(() -> { @@ -51,4 +76,38 @@ public class ConfigDriver { return GSON.toJson(t); } + private static Path configFile(String directory, Class type) { + Config config = type.getAnnotation(Config.class); + return config == null ? null : Path.of(directory).resolve(config.id() + ".json"); + } + + private static JsonElement referencedConfig(String directory, Class type) { + Path file = configFile(directory, type); + if (file == null || !Files.isRegularFile(file)) return null; + try { + String raw = Files.readString(file); + return ManagedValues.hasReferences(raw) ? JsonParser.parseString(raw) : null; + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + } + + private static JsonElement restoreReferences(JsonElement raw, JsonElement current) { + if (raw.isJsonObject() && current.isJsonObject()) { + var result = current.getAsJsonObject(); + raw.getAsJsonObject().asMap().forEach((key, value) -> { + if (result.has(key)) result.add(key, restoreReferences(value, result.get(key))); + }); + } else if (raw.isJsonArray() && current.isJsonArray()) { + var result = current.getAsJsonArray(); + for (int i = 0; i < Math.min(raw.getAsJsonArray().size(), result.size()); i++) { + result.set(i, restoreReferences(raw.getAsJsonArray().get(i), result.get(i))); + } + } else if (raw.isJsonPrimitive() && raw.getAsJsonPrimitive().isString() && ManagedValues.hasReferences(raw.getAsString()) + && current.isJsonPrimitive()) { + return raw; + } + return current; + } + } diff --git a/wcloud-driver/src/main/java/de/wcloudservice/driver/configuration/group/GroupStorage.java b/wcloud-driver/src/main/java/de/wcloudservice/driver/configuration/group/GroupStorage.java index bdc566f..d438c22 100644 --- a/wcloud-driver/src/main/java/de/wcloudservice/driver/configuration/group/GroupStorage.java +++ b/wcloud-driver/src/main/java/de/wcloudservice/driver/configuration/group/GroupStorage.java @@ -17,5 +17,15 @@ public class GroupStorage { private String javaEnvironment; private String runningDaemon; private String startArguments; + private String platform; + private String platformVersion; + private boolean forgeEulaAccepted; + private int initialMemory; + private int startPort; + private String cover; + + public GroupStorage(String template, String javaEnvironment, String runningDaemon, String startArguments) { + this(template, javaEnvironment, runningDaemon, startArguments, null, null, false, 0, 0, null); + } } diff --git a/wcloud-driver/src/main/java/de/wcloudservice/driver/group/GroupDriver.java b/wcloud-driver/src/main/java/de/wcloudservice/driver/group/GroupDriver.java index beab661..37b657e 100644 --- a/wcloud-driver/src/main/java/de/wcloudservice/driver/group/GroupDriver.java +++ b/wcloud-driver/src/main/java/de/wcloudservice/driver/group/GroupDriver.java @@ -32,7 +32,7 @@ public class GroupDriver { return this.getAll().stream().anyMatch(group -> group.name().equalsIgnoreCase(name)); } - public void create(Group group) { + public synchronized void create(Group group) { if (!this.find(group.name())) { GroupConfig groupConfig = new GroupConfig(new ArrayList<>()); if(Driver.instance().configDriver().exists("./local/groups/", GroupConfig.class)) { @@ -40,20 +40,20 @@ public class GroupDriver { } groupConfig.groups().add(group); - if (group.storage().runningDaemon().equals("local")) { + if (group.storage().runningDaemon().equals("local") && group.storage().platform() == null) { boolean proxy = group.type().equalsIgnoreCase("PROXY"); boolean isStatic = group.runStatic(); Driver.instance().templateDriver().create(group.storage().template(), proxy, isStatic); } + Driver.instance().configDriver().saveAndWait("./local/groups/", groupConfig); Driver.instance().eventDriver().executeEvent(new CloudGroupCreateEvent(group)); if (NettyDriver.instance() != null) { NettyDriver.instance().server().sendPacket(new PacketOutGroupCreate(group)); } - Driver.instance().configDriver().saveAndWait("./local/groups/", groupConfig); Driver.instance().terminalDriver().log(Type.SUCCESS, Driver.instance().languageDriver().translate("group-create", group.name())); } } @@ -114,18 +114,19 @@ public class GroupDriver { } @SneakyThrows - public void update(String name, Group group) { + public synchronized void update(String name, Group group) { if (this.find(name)) { - Driver.instance().eventDriver().executeEvent(new CloudGroupUpdateEditEvent(group)); - NettyDriver.instance().server().sendPacket(new PacketOutGroupUpdate(group)); - GroupConfig groupConfig = new GroupConfig(new ArrayList<>()); if(Driver.instance().configDriver().exists("./local/groups/", GroupConfig.class)) { groupConfig = Driver.instance().configDriver().read("./local/groups/", GroupConfig.class); } groupConfig.groups().removeIf(group1 -> group1.name().equalsIgnoreCase(name)); groupConfig.groups().add(group); - Driver.instance().configDriver().save("./local/groups/", groupConfig); + Driver.instance().configDriver().saveAndWait("./local/groups/", groupConfig); + Driver.instance().eventDriver().executeEvent(new CloudGroupUpdateEditEvent(group)); + if (NettyDriver.instance() != null) { + NettyDriver.instance().server().sendPacket(new PacketOutGroupUpdate(group)); + } } } diff --git a/wcloud-driver/src/main/java/de/wcloudservice/driver/group/TemplateDriver.java b/wcloud-driver/src/main/java/de/wcloudservice/driver/group/TemplateDriver.java index a59189e..a19c671 100644 --- a/wcloud-driver/src/main/java/de/wcloudservice/driver/group/TemplateDriver.java +++ b/wcloud-driver/src/main/java/de/wcloudservice/driver/group/TemplateDriver.java @@ -52,7 +52,7 @@ public class TemplateDriver { MasterConfig config = Driver.instance().configDriver().read("./", MasterConfig.class); Driver.instance().groupDriver().getAll().forEach(group -> { - if(!group.platformUpdate()) return; + if (!group.platformUpdate() || group.storage().platform() != null) return; if (new File("./local/templates/" + group.storage().template() + "/server.jar").exists()) { new File("./local/templates/" + group.storage().template() + "/server.jar").delete(); @@ -86,7 +86,7 @@ public class TemplateDriver { }); } else if(Driver.instance().daemonSafe() != null) { Driver.instance().daemonSafe().groups().forEach(group -> { - if(!group.platformUpdate()) return; + if (!group.platformUpdate() || group.storage().platform() != null) return; if (new File("./local/templates/" + group.storage().template() + "/server.jar").exists()) { new File("./local/templates/" + group.storage().template() + "/server.jar").delete(); diff --git a/wcloud-driver/src/main/java/de/wcloudservice/driver/module/ModuleDriver.java b/wcloud-driver/src/main/java/de/wcloudservice/driver/module/ModuleDriver.java index 8499916..c671054 100644 --- a/wcloud-driver/src/main/java/de/wcloudservice/driver/module/ModuleDriver.java +++ b/wcloud-driver/src/main/java/de/wcloudservice/driver/module/ModuleDriver.java @@ -1,16 +1,21 @@ package de.wcloudservice.driver.module; import de.wcloudservice.driver.Driver; +import de.wcloudservice.driver.configuration.group.Group; import de.wcloudservice.driver.module.loader.ModuleLoader; import de.wcloudservice.driver.network.out.main.PacketOutMainModule; import de.wcloudservice.driver.terminal.enums.Type; import de.wcloudservice.networking.NettyDriver; +import de.wcloudservice.utils.io.FileUtil; import lombok.Getter; import lombok.experimental.Accessors; import java.io.File; +import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; -import java.util.Objects; +import java.util.Properties; +import java.util.jar.JarFile; @Getter @Accessors(fluent = true) @@ -60,17 +65,41 @@ public class ModuleDriver { NettyDriver.instance().server().sendPacket(new PacketOutMainModule()); } + public void copyForGroup(Group group, Path plugins) throws IOException { + boolean proxy = "PROXY".equalsIgnoreCase(group.type()); + for (String name : getModules()) { + Path jar = Path.of("modules", name + ".jar"); + var properties = new Properties(); + try (var archive = new JarFile(jar.toFile())) { + var entry = archive.getJarEntry("module.properties"); + if (entry == null) continue; + try (var input = archive.getInputStream(entry)) { + properties.load(input); + } + } catch (IOException invalid) { + Driver.instance().terminalDriver().log(Type.WARN, "Modul " + name + " konnte nicht gelesen werden."); + continue; + } + boolean copy = switch (properties.getProperty("copy", "").toUpperCase(java.util.Locale.ROOT)) { + case "ALL" -> true; + case "LOBBY" -> "LOBBY".equalsIgnoreCase(group.type()); + case "PROXY" -> proxy; + case "SERVER" -> !proxy; + default -> false; + }; + if (copy) FileUtil.copy(jar, plugins.resolve(jar.getFileName())); + } + } + private ArrayList getModules() { File file = new File("./modules/"); File[] files = file.listFiles(); ArrayList modules = new ArrayList<>(); - for (int i = 0; i != Objects.requireNonNull(files).length; i++) { - String firstFilter = files[i].getName(); - if (firstFilter.contains(".jar")) { - String group = firstFilter.split(".jar")[0]; - modules.add(group); - } + if (files == null) return modules; + for (File candidate : files) { + String filename = candidate.getName(); + if (candidate.isFile() && filename.endsWith(".jar")) modules.add(filename.substring(0, filename.length() - 4)); } return modules; diff --git a/wcloud-driver/src/main/java/de/wcloudservice/driver/playercache/PlayerCacheDriver.java b/wcloud-driver/src/main/java/de/wcloudservice/driver/playercache/PlayerCacheDriver.java index b3a023c..64cf45d 100644 --- a/wcloud-driver/src/main/java/de/wcloudservice/driver/playercache/PlayerCacheDriver.java +++ b/wcloud-driver/src/main/java/de/wcloudservice/driver/playercache/PlayerCacheDriver.java @@ -15,6 +15,10 @@ public class PlayerCacheDriver { return playerList; } + public List snapshot() { + return repository.findAll(); + } + public void save(PlayerCache player) { repository.save(player); NettyDriver.instance().server().sendPacket(new PacketOutPlayerCache(List.of(player))); diff --git a/wcloud-driver/src/main/java/de/wcloudservice/driver/process/ServiceProcess.java b/wcloud-driver/src/main/java/de/wcloudservice/driver/process/ServiceProcess.java index 0b01ec8..d3b367b 100644 --- a/wcloud-driver/src/main/java/de/wcloudservice/driver/process/ServiceProcess.java +++ b/wcloud-driver/src/main/java/de/wcloudservice/driver/process/ServiceProcess.java @@ -2,6 +2,7 @@ package de.wcloudservice.driver.process; import de.wcloudservice.driver.Driver; import de.wcloudservice.driver.configuration.daemon.DaemonConfig; +import de.wcloudservice.driver.configuration.ManagedValues; import de.wcloudservice.driver.configuration.group.Group; import de.wcloudservice.driver.configuration.master.MasterConfig; import de.wcloudservice.driver.configuration.service.ServiceConfig; @@ -9,6 +10,7 @@ import de.wcloudservice.driver.network.in.daemon.PacketInSendConsole; import de.wcloudservice.driver.scheduler.CloudScheduler; import de.wcloudservice.driver.scheduler.SchedulerUtil; import de.wcloudservice.driver.storage.service.ServiceStorage; +import de.wcloudservice.driver.storage.versions.GroupPlatform; import de.wcloudservice.driver.terminal.enums.Type; import de.wcloudservice.networking.NettyDriver; import de.wcloudservice.utils.io.FileUtil; @@ -19,6 +21,8 @@ import lombok.experimental.Accessors; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; import java.util.*; import java.util.concurrent.TimeUnit; @@ -32,12 +36,14 @@ public final class ServiceProcess { private final boolean useProtocol; private final LinkedList consoleStorage = new LinkedList<>(); + private final Map managedDocuments = new java.util.concurrent.ConcurrentHashMap<>(); private boolean useCustomTemplate = false; private String customTemplate = ""; private boolean useConsole = false; private BufferedReader reader; private Process process; + private volatile boolean serverReady; public ServiceProcess(Group group, String serviceName, int port, boolean useProtocol) { this.group = group; @@ -59,7 +65,7 @@ public final class ServiceProcess { new File(customTemplate).deleteOnExit(); new File(customTemplate).mkdirs(); - FileUtil.copyDirectory(Path.of("./live/" + group.name() + "/" + serviceName + "/"), Path.of(customTemplate)); + copyToTemplate(Path.of(customTemplate)); return; } @@ -71,7 +77,7 @@ public final class ServiceProcess { new File("./local/templates/" + group.storage().template() +"/").delete(); new File("./local/templates/" + group.storage().template()+"/").mkdirs(); - FileUtil.copyDirectory(Path.of("./live/" + group.name() + "/" + serviceName + "/"), Path.of("./local/templates/" + group.storage().template() + "/")); + copyToTemplate(Path.of("./local/templates/" + group.storage().template() + "/")); return; } @@ -81,53 +87,42 @@ public final class ServiceProcess { new File("./local/templates/" + group.storage().template()+"/" + serviceName + "/").mkdirs(); - FileUtil.copyDirectory(Path.of("./live/" + group.name() + "/" + serviceName + "/"), Path.of("./local/templates/" + group.storage().template() + "/" + serviceName + "/")); - FileUtil.copyDirectory(Path.of("./live/" + group.name() + "/" + serviceName + "/plugins/"), Path.of("./local/templates/" + group.storage().template() + "/" + serviceName + "/plugins/")); + copyToTemplate(Path.of("./local/templates/" + group.storage().template() + "/" + serviceName + "/")); } }, 5, SchedulerUtil.MILLISECONDS); } public void console() { - if(this.useConsole) { - this.useConsole = false; - return; + synchronized (consoleStorage) { + this.useConsole = !this.useConsole; + if (this.useConsole) consoleStorage.forEach(this::printConsole); } - - this.useConsole = true; - - new Thread(() -> { - String line; - - this.consoleStorage.forEach(s -> { - if (Driver.instance().configDriver().exists("./", MasterConfig.class)) { - Driver.instance().terminalDriver().log(this.serviceName(), s); - } else { - NettyDriver.instance().client().sendPacket(new PacketInSendConsole(serviceName, s)); - } - }); - - try { - while ((line = this.reader.readLine()) != null && this.useConsole) { - this.consoleStorage.add(line); - - if (Driver.instance().configDriver().exists("./", MasterConfig.class)) { - Driver.instance().terminalDriver().log(this.serviceName(), line); - } else { - NettyDriver.instance().client().sendPacket(new PacketInSendConsole(serviceName, line)); - } - } - } catch (Exception exception) { - Driver.instance().terminalDriver().serviceScreen(false); - } - }).start(); } + public java.util.List dashboardConsole() { + synchronized (consoleStorage) { + return consoleStorage.stream().map(line -> line.length() > 4096 ? line.substring(0, 4096) : line).toList(); + } + } + + public synchronized void sendCommand(String line) throws IOException { + if (process == null || !process.isAlive()) throw new IOException("Die Instanz läuft gerade nicht."); + var output = process.getOutputStream(); + output.write((line + "\n").getBytes(StandardCharsets.UTF_8)); + output.flush(); + } + + @SneakyThrows public void launch() { if (this.process != null || this.port == 0 || this.serviceName == null || this.group == null) { return; } - if (!Driver.instance().templateDriver().get().contains(this.group.storage().template())) { + boolean managedPlatform = this.group.storage().platform() != null; + int initialMemory = this.group.storage().initialMemory() > 0 + ? Math.min(this.group.storage().initialMemory(), this.group.usedMemory()) : this.group.usedMemory(); + boolean forge = "forge".equals(this.group.storage().platform()); + if (!managedPlatform && !Driver.instance().templateDriver().get().contains(this.group.storage().template())) { Driver.instance().templateDriver().create(this.group.storage().template(), this.group.type().equalsIgnoreCase("PROXY"), this.group.runStatic()); } @@ -138,31 +133,15 @@ public final class ServiceProcess { } else if (!this.group.runStatic()) { Driver.instance().templateDriver().copy(this.group.storage().template(), "./live/" + this.group.name() + "/" + this.serviceName + "/"); } else { - if (new File("./local/templates/" + this.group.name() + "/" + this.serviceName + "/").exists()) { - FileUtil.copyDirectory(Path.of("./local/templates/" + this.group.name() + "/" + this.serviceName + "/"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/")); + if (new File("./local/templates/" + this.group.storage().template() + "/" + this.serviceName + "/").exists()) { + FileUtil.copyDirectory(Path.of("./local/templates/" + this.group.storage().template() + "/" + this.serviceName + "/"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/")); } else { - FileUtil.copyDirectory(Path.of("./local/templates/" + this.group.name() + "/default/"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/")); + FileUtil.copyDirectory(Path.of("./local/templates/" + this.group.storage().template() + "/default/"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/")); } } - if (!Driver.instance().moduleDriver().loadedModules().isEmpty()) { - Driver.instance().moduleDriver().loadedModules().forEach(moduleLoader -> { - if (moduleLoader.configuration().copy().equalsIgnoreCase("ALL")) { - FileUtil.copy(Path.of("./modules/" + moduleLoader.moduleName() + ".jar"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/plugins/" + moduleLoader.moduleName() + ".jar")); - } else if (moduleLoader.configuration().copy().equalsIgnoreCase("LOBBY")) { - if (this.group.type().equalsIgnoreCase("LOBBY")){ - FileUtil.copy(Path.of("./modules/" + moduleLoader.moduleName() + ".jar"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/plugins/" + moduleLoader.moduleName() + ".jar")); - } - } else if (moduleLoader.configuration().copy().equalsIgnoreCase("PROXY")) { - if (this.group.type().equalsIgnoreCase("PROXY")){ - FileUtil.copy(Path.of("./modules/" + moduleLoader.moduleName() + ".jar"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/plugins/" + moduleLoader.moduleName() + ".jar")); - } - } else if (moduleLoader.configuration().copy().equalsIgnoreCase("SERVER")) { - if (!this.group.type().equalsIgnoreCase("PROXY")){ - FileUtil.copy(Path.of("./modules/" + moduleLoader.moduleName() + ".jar"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/plugins/" + moduleLoader.moduleName() + ".jar")); - } - } - }); + if (!forge) { + Driver.instance().moduleDriver().copyForGroup(group, Path.of("live", group.name(), serviceName, "plugins")); } ServiceConfig serviceConfig = new ServiceConfig(); @@ -188,13 +167,26 @@ public final class ServiceProcess { javaCommand = config.javaCommand(); } - Driver.instance().configDriver().save("./live/" + this.group.name() + "/" + this.serviceName + "/", serviceConfig); + Driver.instance().configDriver().saveAndWait("./live/" + this.group.name() + "/" + this.serviceName + "/", serviceConfig); FileUtil.copyDirectory(Path.of("./local/GLOBAL/EVERY/"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/")); - FileUtil.copy(Path.of("./connection.key"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/connection.key")); + if (Files.isRegularFile(Path.of("connection.key"))) { + FileUtil.copy(Path.of("./connection.key"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/connection.key")); + } ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.directory(new File("./live/" + group.name() + "/" + serviceName + "/")); + processBuilder.redirectErrorStream(true); + Path directory = processBuilder.directory().toPath().toAbsolutePath().normalize(); + javaCommand = GroupPlatform.javaCommand(group, javaCommand); + if (managedPlatform) { + Path platform = GroupPlatform.prepare(group, javaCommand); + if (forge) FileUtil.copyDirectory(platform, directory, + path -> !Set.of("installer.jar", "installer.jar.log", "install.log", ".installed", "user_jvm_args.txt").contains(path.getFileName().toString())); + else Files.copy(platform, directory.resolve("server.jar"), StandardCopyOption.REPLACE_EXISTING); + } + Path extensions = GroupPlatform.extensions(group); + FileUtil.copyDirectory(extensions, directory.resolve(extensions.getFileName())); if (!this.group.storage().javaEnvironment().isEmpty()){ processBuilder.environment().put("JAVA_HOME", group.storage().javaEnvironment()); @@ -210,7 +202,7 @@ public final class ServiceProcess { "-Dio.netty.recycler.maxCapacity.default=0", "-Djline.terminal=jline.UnsupportedTerminal", "-Xmx" + this.group.usedMemory() + "M", - "-Xms" + this.group.usedMemory() + "M", + "-Xms" + initialMemory + "M", "-jar", "server.jar", this.group.storage().startArguments() @@ -229,6 +221,13 @@ public final class ServiceProcess { e.printStackTrace(); } } + if (managedPlatform) { + Path velocity = directory.resolve("velocity.toml"); + String settings = Files.readString(velocity) + .replaceFirst("(?m)^bind\\s*=.*$", "bind = \"0.0.0.0:" + port + "\"") + .replaceFirst("(?m)^show-max-players\\s*=.*$", "show-max-players = " + group.maxPlayers()); + Files.writeString(velocity, settings); + } int leftLimit = 97; int rightLimit = 122; @@ -253,13 +252,6 @@ public final class ServiceProcess { processBuilder.command(command); - try { - this.process = processBuilder.start(); - } catch (IOException e) { - e.printStackTrace(); - } - - this.reader = new BufferedReader(new InputStreamReader(this.process.getInputStream())); } else { FileUtil.copyDirectory(Path.of("./local/GLOBAL/EVERY_SERVER/"), Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/")); @@ -292,7 +284,7 @@ public final class ServiceProcess { "-Dio.netty.recycler.maxCapacity.default=0", "-Djline.terminal=jline.UnsupportedTerminal", "-Dusing.aikars.flags=https://mcflags.emc.gs", - "-Xms" + this.group.usedMemory() + "M", + "-Xms" + initialMemory + "M", "-Xmx" + this.group.usedMemory() + "M", "-jar", "server.jar", @@ -314,6 +306,7 @@ public final class ServiceProcess { } else { this.updateProperty(configFile, "server-port", "" + this.port); } + if (managedPlatform) this.updateProperty(configFile, "max-players", String.valueOf(group.maxPlayers())); if (!new File(System.getProperty("user.dir") + "/live/" + this.group.name() + "/" + this.serviceName + "/bukkit.yml").exists()) { File configFile2 = new File(System.getProperty("user.dir") + "/live/" + this.group.name() + "/" + this.serviceName + "/", "bukkit.yml"); @@ -340,14 +333,66 @@ public final class ServiceProcess { } processBuilder.command(command); - - try { - this.process = processBuilder.start(); - } catch (IOException e) { - e.printStackTrace(); + if (forge) { + if (group.storage().forgeEulaAccepted()) { + Files.writeString(directory.resolve("eula.txt"), "# Minecraft EULA: https://aka.ms/MinecraftEULA\neula=true\n"); + } + var forgeCommand = new ArrayList<>(List.of(javaCommand, "-Xms" + initialMemory + "M", + "-Xmx" + group.usedMemory() + "M")); + if (Files.isRegularFile(directory.resolve("user_jvm_args.txt"))) forgeCommand.add("@user_jvm_args.txt"); + forgeCommand.add("@" + GroupPlatform.forgeArguments(group.storage().platformVersion())); + forgeCommand.add("nogui"); + forgeCommand.add(group.storage().startArguments()); + processBuilder.command(forgeCommand); } + } + ManagedValues values = ManagedValues.forService(); + processBuilder.environment().putAll(values.environment()); + try { + values.materialize(directory, managedDocuments); + processBuilder.command(new ArrayList<>(processBuilder.command().stream().filter(argument -> !argument.isBlank()).toList())); + this.process = processBuilder.start(); this.reader = new BufferedReader(new InputStreamReader(this.process.getInputStream())); + Thread.startVirtualThread(this::readConsole); + } catch (IOException failure) { + for (var entry : managedDocuments.entrySet()) ManagedValues.write(entry.getKey(), entry.getValue()); + throw failure; + } + } + + private void readConsole() { + try (var input = reader) { + String line; + while ((line = input.readLine()) != null) { + if (line.contains("Done (") && line.contains("For help, type")) serverReady = true; + synchronized (consoleStorage) { + if (consoleStorage.size() >= 250) consoleStorage.removeFirst(); + consoleStorage.addLast(line); + if (useConsole) printConsole(line); + } + } + } catch (IOException closed) { + // The process closes its output on shutdown. + } + } + + private void printConsole(String line) { + if (Driver.instance().configDriver().exists("./", MasterConfig.class)) { + Driver.instance().terminalDriver().log(this.serviceName(), line); + } else { + NettyDriver.instance().client().sendPacket(new PacketInSendConsole(serviceName, line)); + } + } + + @SneakyThrows + private void copyToTemplate(Path target) { + Path source = Path.of("./live/" + group.name() + "/" + serviceName + "/").toAbsolutePath().normalize(); + FileUtil.copyDirectory(source, target, path -> !managedDocuments.containsKey(path) + && !Set.of("connection.key", "service.json", "forwarding.secret").contains(path.getFileName().toString())); + for (var entry : managedDocuments.entrySet()) { + Path destination = target.resolve(source.relativize(entry.getKey())); + if (!Files.exists(destination)) ManagedValues.write(destination, entry.getValue()); } } @@ -355,7 +400,7 @@ public final class ServiceProcess { public void shutdown(boolean savedSuccessful) { this.useConsole = false; boolean wasAlive = this.process != null && this.process.isAlive(); - boolean graceful = stopProcess(this.process, this.group.type().equalsIgnoreCase("PROXY")); + boolean graceful = stopProcess(this.process, this.group.type().equalsIgnoreCase("PROXY"), false); savedSuccessful = savedSuccessful && graceful; if (wasAlive && !graceful) { Driver.instance().terminalDriver().log(Type.WARN, @@ -399,10 +444,9 @@ public final class ServiceProcess { file.delete(); } } else { - new File("./local/templates/" + this.group.name() + "/" + this.serviceName + "/").delete(); - new File("./local/templates/" + this.group.name() + "/" + this.serviceName + "/").mkdirs(); - - FileUtil.copyDirectory(Path.of("./live/" + this.group.name() + "/" + this.serviceName + "/"), Path.of("./local/templates/" + this.group.name() + "/" + this.serviceName + "/")); + Path target = Path.of("./local/templates/" + this.group.storage().template() + "/" + this.serviceName + "/"); + Files.createDirectories(target); + copyToTemplate(target); Thread.sleep(200); if(savedSuccessful) { @@ -425,9 +469,15 @@ public final class ServiceProcess { } static boolean stopProcess(Process process, boolean proxy) throws IOException, InterruptedException { + return stopProcess(process, proxy, true); + } + + private static boolean stopProcess(Process process, boolean proxy, boolean drain) throws IOException, InterruptedException { if (process == null || !process.isAlive()) return false; - drainShutdownOutput(process.getInputStream()); - drainShutdownOutput(process.getErrorStream()); + if (drain) { + drainShutdownOutput(process.getInputStream()); + drainShutdownOutput(process.getErrorStream()); + } try { process.getOutputStream().write(((proxy ? "shutdown" : "stop") + "\n").getBytes(StandardCharsets.UTF_8)); process.getOutputStream().flush(); diff --git a/wcloud-driver/src/main/java/de/wcloudservice/driver/storage/versions/Downloader.java b/wcloud-driver/src/main/java/de/wcloudservice/driver/storage/versions/Downloader.java index e523d79..8044a19 100644 --- a/wcloud-driver/src/main/java/de/wcloudservice/driver/storage/versions/Downloader.java +++ b/wcloud-driver/src/main/java/de/wcloudservice/driver/storage/versions/Downloader.java @@ -29,7 +29,10 @@ public final class Downloader { private static final String PAPER_MANIFEST_URL = "https://wcloudservice.weapie.de/files/paper_versions.json"; public static List fetchRemoteManifest() throws IOException { - try (InputStream in = new URL(MANIFEST_URL).openStream(); + var connection = new URL(MANIFEST_URL).openConnection(); + connection.setConnectTimeout(5000); + connection.setReadTimeout(7000); + try (InputStream in = connection.getInputStream(); InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) { Type listType = new TypeToken>() {}.getType(); diff --git a/wcloud-driver/src/main/java/de/wcloudservice/driver/storage/versions/PaperMcDownloads.java b/wcloud-driver/src/main/java/de/wcloudservice/driver/storage/versions/PaperMcDownloads.java index ae72de3..b868519 100644 --- a/wcloud-driver/src/main/java/de/wcloudservice/driver/storage/versions/PaperMcDownloads.java +++ b/wcloud-driver/src/main/java/de/wcloudservice/driver/storage/versions/PaperMcDownloads.java @@ -30,6 +30,7 @@ import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.LinkedHashSet; +import java.util.List; final class PaperMcDownloads { @@ -55,6 +56,14 @@ final class PaperMcDownloads { throw new IOException("Kein stabiler PaperMC-Build für " + project + " " + version + " verfügbar"); } + for (String candidate : versions(project)) { + Download download = latestStableBuild(project, candidate); + if (download != null) return download; + } + throw new IOException("Keine stabile PaperMC-Version für " + project + " verfügbar"); + } + + List versions(String project) throws IOException, InterruptedException { JsonObject response = object(fetch(segment(project)), "Projekt"); JsonObject groups = object(response.get("versions"), "Versionsgruppen"); var versions = new LinkedHashSet(); @@ -66,11 +75,7 @@ final class PaperMcDownloads { if (candidate.matches("\\d+(?:\\.\\d+)*")) versions.add(candidate); } } - for (String candidate : versions) { - Download download = latestStableBuild(project, candidate); - if (download != null) return download; - } - throw new IOException("Keine stabile PaperMC-Version für " + project + " verfügbar"); + return List.copyOf(versions); } private Download latestStableBuild(String project, String version) throws IOException, InterruptedException { diff --git a/wcloud-driver/src/main/java/de/wcloudservice/driver/terminal/TerminalDriver.java b/wcloud-driver/src/main/java/de/wcloudservice/driver/terminal/TerminalDriver.java index ad2cf30..f213d9f 100644 --- a/wcloud-driver/src/main/java/de/wcloudservice/driver/terminal/TerminalDriver.java +++ b/wcloud-driver/src/main/java/de/wcloudservice/driver/terminal/TerminalDriver.java @@ -219,6 +219,7 @@ public class TerminalDriver { if (this.serviceScreen) { for (String message : messages) { this.mainScreenStorage.add(new TerminalStorage(type, message)); + this.simpleLatestLog.log(this.clearString("[" + type.name() + "] " + message)); } return; } @@ -266,6 +267,7 @@ public class TerminalDriver { if (this.serviceScreen) { this.mainScreenStorage.add(new TerminalStorage(type, message)); + this.simpleLatestLog.log(this.clearString("[" + type.name() + "] " + message)); return; } diff --git a/wcloud-launcher/src/main/java/de/wcloudservice/launcher/CloudBoot.java b/wcloud-launcher/src/main/java/de/wcloudservice/launcher/CloudBoot.java index 2ae6c13..5bd1676 100644 --- a/wcloud-launcher/src/main/java/de/wcloudservice/launcher/CloudBoot.java +++ b/wcloud-launcher/src/main/java/de/wcloudservice/launcher/CloudBoot.java @@ -8,6 +8,7 @@ import de.wcloudservice.driver.terminal.enums.Type; import de.wcloudservice.driver.terminal.setup.SetupType; import de.wcloudservice.launcher.loader.InstanceLoader; import de.wcloudservice.launcher.patcher.AutoPatcher; +import de.wcloudservice.launcher.web.DashboardServer; import lombok.SneakyThrows; import java.io.File; @@ -22,8 +23,12 @@ import java.util.TimerTask; public class CloudBoot { private static InstanceLoader instanceLoader; + private static DashboardServer dashboard; + private static final java.util.concurrent.atomic.AtomicBoolean restarting = new java.util.concurrent.atomic.AtomicBoolean(); public static void main(String[] args) { + String waitFor = System.getProperty("wcloud.restart.wait"); + if (waitFor != null && !awaitPrevious(waitFor)) return; String version = System.getProperty("java.version"); int majorVersion = Integer.parseInt(version.split("\\.")[0]); if (majorVersion < 25) { @@ -34,6 +39,7 @@ public class CloudBoot { instanceLoader = new InstanceLoader(); new Driver(); + Driver.instance().dashboardRestart(() -> restart(args)); Driver.instance().startTerminal(); Driver.instance().startLanguage(); @@ -44,8 +50,6 @@ public class CloudBoot { Driver.instance().languageDriver().selectedLocale(Locale.forLanguageTag(config.language())); } else if(Driver.instance().configDriver().exists("./", DaemonConfig.class)) { Driver.instance().languageDriver().selectedLocale(Locale.forLanguageTag(Driver.instance().configDriver().read("./", DaemonConfig.class).language())); - } else { - Downloader.downloadCloudFiles(); } Driver.instance().terminalDriver().clearScreen(); @@ -57,24 +61,36 @@ public class CloudBoot { Driver.instance().terminalDriver().log(Type.INFO, Driver.instance().languageDriver().translate("setup-check-if-setup-has-finished")); - if(!Driver.instance().configDriver().exists("./", MasterConfig.class) && !Driver.instance().configDriver().exists("./", DaemonConfig.class)) { - Driver.instance().terminalDriver().log(Type.INFO, Driver.instance().languageDriver().translate("setup-first-starting-cloud")); - + boolean fresh = !Driver.instance().configDriver().exists("./", MasterConfig.class) + && !Driver.instance().configDriver().exists("./", DaemonConfig.class); + boolean consoleSetup = java.util.Arrays.asList(args).contains("--console-setup"); + boolean bundled = Files.isRegularFile(Path.of(".wcloud-web-bundle")); + boolean allowPatcher = !bundled || Boolean.parseBoolean(System.getenv("WCLOUD_WEB_AUTO_PATCH")); + if (!consoleSetup) { try { - Thread.sleep(2000); - } catch (InterruptedException ignored) {} - - Driver.instance().terminalDriver().startSetup(SetupType.GENERAL); - waitForFinishSetup(); + dashboard = new DashboardServer(CloudBoot::runClient); + dashboard.start(); + } catch (Exception failure) { + Driver.instance().terminalDriver().log(Type.ERROR, "wCloud Web konnte nicht starten: " + failure.getMessage()); + if (fresh) System.exit(1); + } + } + if (fresh) { + Driver.instance().terminalDriver().log(Type.INFO, Driver.instance().languageDriver().translate("setup-first-starting-cloud")); + if (consoleSetup) { + if (!bundled) Downloader.downloadCloudFiles(); + Driver.instance().terminalDriver().startSetup(SetupType.GENERAL); + waitForFinishSetup(); + } } else { - if(Driver.instance().configDriver().exists("./", MasterConfig.class)) { + if(allowPatcher && Driver.instance().configDriver().exists("./", MasterConfig.class)) { if(Driver.instance().configDriver().read("./", MasterConfig.class).patcher()) { Driver.instance().terminalDriver().log(Type.PATCHER, Driver.instance().languageDriver().translate("patcher-starting")); AutoPatcher.perform(); } } - if(Driver.instance().configDriver().exists("./", DaemonConfig.class)) { + if(allowPatcher && Driver.instance().configDriver().exists("./", DaemonConfig.class)) { if(Driver.instance().configDriver().read("./", DaemonConfig.class).patcher()) { Driver.instance().terminalDriver().log(Type.PATCHER, Driver.instance().languageDriver().translate("patcher-starting")); AutoPatcher.perform(); @@ -92,6 +108,44 @@ public class CloudBoot { return username.equalsIgnoreCase("root"); } + private static boolean awaitPrevious(String previous) { + try { + var process = ProcessHandle.of(Long.parseLong(previous)); + if (process.isPresent()) process.get().onExit().get(120, java.util.concurrent.TimeUnit.SECONDS); + return true; + } catch (Exception waitFailed) { + System.err.println("wCloud wartet noch auf das Ende des vorherigen Prozesses."); + return false; + } + } + + private static void restart(String[] args) { + var shutdown = Driver.instance().dashboardShutdown(); + if (shutdown == null) throw new IllegalStateException("wCloud ist noch nicht bereit für einen Neustart."); + if (!restarting.compareAndSet(false, true)) throw new IllegalStateException("Ein Neustart ist bereits eingeplant."); + try { + Path launcher = Path.of(CloudBoot.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + if (!Files.isRegularFile(launcher)) throw new IllegalStateException("Für den Web-Neustart muss wCloud aus der Launcher-JAR laufen."); + var command = new java.util.ArrayList(); + command.add(ProcessHandle.current().info().command().orElse("java")); + java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().stream() + .filter(argument -> !argument.startsWith("-Dwcloud.restart.wait=")).forEach(command::add); + command.add("-Dwcloud.restart.wait=" + ProcessHandle.current().pid()); + command.add("-jar"); + command.add(launcher.toString()); + command.addAll(java.util.Arrays.asList(args)); + new ProcessBuilder(command).inheritIO().start(); + Thread.ofPlatform().name("wcloud-web-restart").start(() -> { + try { Thread.sleep(250); } + catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); } + shutdown.run(); + }); + } catch (Exception failure) { + restarting.set(false); + throw new IllegalStateException("Der neue wCloud-Prozess konnte nicht gestartet werden.", failure); + } + } + @SneakyThrows public static void runClient() { if (Driver.instance().configDriver().exists("./", MasterConfig.class)) { @@ -131,7 +185,9 @@ public class CloudBoot { if (!new File("./dependency/").exists()) { Path folder = Paths.get("./dependency/"); Files.createDirectory(folder); - Files.setAttribute(folder, "dos:hidden", true, LinkOption.NOFOLLOW_LINKS); + if (Files.getFileStore(folder).supportsFileAttributeView("dos")) { + Files.setAttribute(folder, "dos:hidden", true, LinkOption.NOFOLLOW_LINKS); + } } if (!new File("./modules/").exists()) { @@ -148,6 +204,7 @@ public class CloudBoot { Driver.instance().terminalDriver().log(Type.ERROR, Driver.instance().languageDriver().translate("setup-no-config-found")); System.exit(0); } + if (dashboard != null) dashboard.announce(); } public static void waitForFinishSetup() { diff --git a/wcloud-modules/wmodule-permissions/build.gradle.kts b/wcloud-modules/wmodule-permissions/build.gradle.kts index 04724aa..ea03501 100644 --- a/wcloud-modules/wmodule-permissions/build.gradle.kts +++ b/wcloud-modules/wmodule-permissions/build.gradle.kts @@ -16,6 +16,7 @@ dependencies { "compileOnly"(projects.wcloudUtils) "compileOnly"(projects.wcloudNetworking) "compileOnly"(libs.devlokFiles) + "compileOnly"(libs.gson) "compileOnly"(libs.bundles.proxyPlatform) testImplementation(projects.wcloudApi) diff --git a/wcloud-modules/wmodule-permissions/src/main/java/de/wcloudservice/permissions/PermissionsModule.java b/wcloud-modules/wmodule-permissions/src/main/java/de/wcloudservice/permissions/PermissionsModule.java index 4a4400e..d06f69c 100644 --- a/wcloud-modules/wmodule-permissions/src/main/java/de/wcloudservice/permissions/PermissionsModule.java +++ b/wcloud-modules/wmodule-permissions/src/main/java/de/wcloudservice/permissions/PermissionsModule.java @@ -5,6 +5,7 @@ import de.wcloudservice.driver.module.extention.CloudModule; import de.wcloudservice.networking.NettyDriver; import de.wcloudservice.permissions.api.CloudPermissionAPI; import de.wcloudservice.permissions.module.commands.PermissionCommand; +import de.wcloudservice.permissions.module.PermissionsDashboard; import de.wcloudservice.permissions.module.config.Configuration; import de.wcloudservice.permissions.module.config.IncludedAble; import de.wcloudservice.permissions.module.config.PermissionAble; @@ -33,6 +34,7 @@ public class PermissionsModule implements CloudModule { this.create(); new CloudPermissionAPI(); + Driver.instance().dashboardPermissions(new PermissionsDashboard()::handle); Driver.instance().terminalDriver().commandDriver().registerCommand(new PermissionCommand()); Driver.instance().eventDriver().registerListener(new CloudEvents()); @@ -43,7 +45,7 @@ public class PermissionsModule implements CloudModule { @Override public void unload() { - + Driver.instance().dashboardPermissions(null); } @Override @@ -56,7 +58,7 @@ public class PermissionsModule implements CloudModule { private void create() { if(!Driver.instance().configDriver().exists("./modules/permissions/", Configuration.class)) { - Driver.instance().configDriver().save("./modules/permissions/", new Configuration( + Driver.instance().configDriver().saveAndWait("./modules/permissions/", new Configuration( new ArrayList<>() {{ add( new PermissionGroup( diff --git a/wcloud-modules/wmodule-permissions/src/main/java/de/wcloudservice/permissions/api/CloudPermissionAPI.java b/wcloud-modules/wmodule-permissions/src/main/java/de/wcloudservice/permissions/api/CloudPermissionAPI.java index fa991bb..6ec96a1 100644 --- a/wcloud-modules/wmodule-permissions/src/main/java/de/wcloudservice/permissions/api/CloudPermissionAPI.java +++ b/wcloud-modules/wmodule-permissions/src/main/java/de/wcloudservice/permissions/api/CloudPermissionAPI.java @@ -44,7 +44,7 @@ public class CloudPermissionAPI { public void updateConfig(@NotNull Configuration config) { if (PermissionsModule.instance() != null) { - Driver.instance().configDriver().save("./modules/permissions/", config); + Driver.instance().configDriver().saveAndWait("./modules/permissions/", config); NettyDriver.instance().server().sendPacket(new PacketOutModulePermissions(config)); } else { CloudAPI.instance().sendPacket(new PacketInModulePermissionsUpdate(config)); diff --git a/wcloud-plugin/src/main/java/de/wcloudservice/plugin/bukkit/BukkitBootstrap.java b/wcloud-plugin/src/main/java/de/wcloudservice/plugin/bukkit/BukkitBootstrap.java index abba484..471e645 100644 --- a/wcloud-plugin/src/main/java/de/wcloudservice/plugin/bukkit/BukkitBootstrap.java +++ b/wcloud-plugin/src/main/java/de/wcloudservice/plugin/bukkit/BukkitBootstrap.java @@ -28,6 +28,7 @@ public class BukkitBootstrap extends JavaPlugin { private static BukkitBootstrap instance; private PlayerResolverBukkit playerResolver; + private SidebarScoreboard sidebar; @Override public void onEnable() { @@ -38,6 +39,22 @@ public class BukkitBootstrap extends JavaPlugin { this.registerListeners(); this.registerCommands(); this.scheduleNettyClientCheck(); + this.sidebar = SidebarScoreboard.start(this); + Bukkit.getScheduler().runTaskTimer(this, () -> { + var api = de.wcloudservice.api.CloudAPI.instance(); + if (api == null || NettyDriver.instance().client().channel() == null || !NettyDriver.instance().client().channel().isActive()) return; + var plugins = java.util.Arrays.stream(Bukkit.getPluginManager().getPlugins()) + .filter(org.bukkit.plugin.Plugin::isEnabled).limit(1000) + .map(plugin -> new de.wcloudservice.driver.dashboard.DashboardRuntime.Plugin( + plugin.getName(), plugin.getDescription().getVersion())) + .toArray(de.wcloudservice.driver.dashboard.DashboardRuntime.Plugin[]::new); + api.sendPacket(new de.wcloudservice.driver.network.in.service.PacketInServicePlugins(plugins)); + }, 20L, 300L); + } + + @Override + public void onDisable() { + if (sidebar != null) sidebar.stop(); } private void initServices() { diff --git a/wcloud-plugin/src/main/java/de/wcloudservice/plugin/velocity/VelocityBootstrap.java b/wcloud-plugin/src/main/java/de/wcloudservice/plugin/velocity/VelocityBootstrap.java index 4b4d85a..734ba29 100644 --- a/wcloud-plugin/src/main/java/de/wcloudservice/plugin/velocity/VelocityBootstrap.java +++ b/wcloud-plugin/src/main/java/de/wcloudservice/plugin/velocity/VelocityBootstrap.java @@ -66,6 +66,16 @@ public class VelocityBootstrap { PluginDriver.instance().register(new PlayerCommand()); this.proxyServer.getEventManager().register(this, new CloudConnectListener()); + proxyServer.getScheduler().buildTask(this, () -> { + var api = CloudAPI.instance(); + if (api == null || NettyDriver.instance().client().channel() == null || !NettyDriver.instance().client().channel().isActive()) return; + var plugins = proxyServer.getPluginManager().getPlugins().stream().filter(plugin -> plugin.getInstance().isPresent()).limit(1000) + .map(plugin -> new de.wcloudservice.driver.dashboard.DashboardRuntime.Plugin( + plugin.getDescription().getName().orElse(plugin.getDescription().getId()), + plugin.getDescription().getVersion().orElse(""))) + .toArray(de.wcloudservice.driver.dashboard.DashboardRuntime.Plugin[]::new); + api.sendPacket(new de.wcloudservice.driver.network.in.service.PacketInServicePlugins(plugins)); + }).delay(java.time.Duration.ofSeconds(1)).repeat(java.time.Duration.ofSeconds(15)).schedule(); new CloudScheduler().schedule(new TimerTask() { @Override diff --git a/wcloud-runnable/wcloud-daemon/src/main/java/de/wcloudservice/daemon/Bootstrap.java b/wcloud-runnable/wcloud-daemon/src/main/java/de/wcloudservice/daemon/Bootstrap.java index f7a8e19..d82c6f0 100644 --- a/wcloud-runnable/wcloud-daemon/src/main/java/de/wcloudservice/daemon/Bootstrap.java +++ b/wcloud-runnable/wcloud-daemon/src/main/java/de/wcloudservice/daemon/Bootstrap.java @@ -5,6 +5,8 @@ import de.wcloudservice.daemon.commands.StopCommand; import de.wcloudservice.daemon.networking.*; import de.wcloudservice.daemon.service.ServiceDriver; import de.wcloudservice.driver.Driver; +import de.wcloudservice.driver.dashboard.DashboardRpc; +import de.wcloudservice.driver.dashboard.HostDashboard; import de.wcloudservice.driver.configuration.daemon.DaemonConfig; import de.wcloudservice.driver.network.in.daemon.PacketInAuth; import de.wcloudservice.driver.network.in.daemon.PacketInShutdownDaemon; @@ -78,6 +80,7 @@ public class Bootstrap implements CloudRunnable { Driver.instance().terminalDriver().commandDriver().registerCommand(new StopCommand()); Driver.instance().terminalDriver().log(Type.INFO, Driver.instance().languageDriver().translate("commands-loaded")); Driver.instance().terminalDriver().log(Type.INFO, Driver.instance().languageDriver().translate("cloud-started")); + Driver.instance().dashboardShutdown(this::shutdownHook); NettyDriver.instance().client().sendPacket(new PacketInAuth(this.config.connectionKey())); } @@ -127,6 +130,9 @@ public class Bootstrap implements CloudRunnable { NettyDriver.instance().packetDriver().listen(new PacketOutShutdownDaemon().packetUid(), PacketOutShutdownDaemon.class, new HandlePacketOutShutdownDaemon()); NettyDriver.instance().packetDriver().listen(new PacketOutStopService().packetUid(), PacketOutStopService.class, new HandlePacketOutStopService()); NettyDriver.instance().packetDriver().listen(new PacketOutSyncService().packetUid(), PacketOutSyncService.class, new HandlePacketOutSyncService()); + DashboardRpc.registerDaemon(new HostDashboard(name -> Driver.instance().daemonSafe().groups().stream() + .filter(group -> group.name().equals(name)).findFirst().orElse(null), + name -> serviceDriver.processes().stream().filter(process -> process.serviceName().equals(name)).findFirst().orElse(null))); } } diff --git a/wcloud-runnable/wcloud-daemon/src/main/java/de/wcloudservice/daemon/service/ServiceDriver.java b/wcloud-runnable/wcloud-daemon/src/main/java/de/wcloudservice/daemon/service/ServiceDriver.java index 715a8c7..32cfd5f 100644 --- a/wcloud-runnable/wcloud-daemon/src/main/java/de/wcloudservice/daemon/service/ServiceDriver.java +++ b/wcloud-runnable/wcloud-daemon/src/main/java/de/wcloudservice/daemon/service/ServiceDriver.java @@ -5,31 +5,35 @@ import de.wcloudservice.daemon.service.entry.QueueEntry; import de.wcloudservice.driver.Driver; import de.wcloudservice.driver.configuration.group.Group; import de.wcloudservice.driver.network.in.daemon.PacketInActionSuccess; +import de.wcloudservice.driver.network.in.daemon.PacketInDaemonServiceReady; import de.wcloudservice.driver.process.ServiceProcess; import de.wcloudservice.driver.scheduler.CloudScheduler; import de.wcloudservice.driver.scheduler.SchedulerUtil; +import de.wcloudservice.driver.terminal.enums.Type; import de.wcloudservice.networking.NettyDriver; import de.wcloudservice.utils.resource.CpuUsageResolver; import lombok.Getter; import lombok.SneakyThrows; import lombok.experimental.Accessors; -import java.util.ArrayList; -import java.util.LinkedList; import java.util.List; +import java.util.HashSet; import java.util.TimerTask; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.IntStream; @Getter @Accessors(fluent = true) public class ServiceDriver { - private final LinkedList queue; + private final ConcurrentLinkedDeque queue; private final List processes; + private final HashSet reportedReady = new HashSet<>(); public ServiceDriver() { - this.queue = new LinkedList<>(); - this.processes = new ArrayList<>(); + this.queue = new ConcurrentLinkedDeque<>(); + this.processes = new CopyOnWriteArrayList<>(); this.handle(); } @@ -76,40 +80,68 @@ public class ServiceDriver { new CloudScheduler().schedule(new TimerTask() { @Override public void run() { - if (CpuUsageResolver.systemCpuLoad() <= Bootstrap.instance().config().processorUsage()) { - if(queue.isEmpty()) return; - - QueueEntry queueEntry = queue.removeFirst(); - if(queueEntry.run()) { - String service = queueEntry.service(); - - if(processes.stream().noneMatch(serviceProcess -> serviceProcess.serviceName().equalsIgnoreCase(queueEntry.service()))) { - int port = freePort(queueEntry.group().type().equalsIgnoreCase("PROXY")); - processes.add(new ServiceProcess(queueEntry.group(), service, port, queueEntry.useProtocol())); - processes.stream().filter(serviceProcess -> serviceProcess.serviceName().equalsIgnoreCase(service)).findFirst().get().launch(); - NettyDriver.instance().client().sendPacket(new PacketInActionSuccess(true, service, Driver.instance().daemonSafe().daemonName(), port)); - } - } else { - String service = queueEntry.service(); - if(processes.stream().anyMatch(serviceProcess -> serviceProcess.serviceName().equalsIgnoreCase(service))) { - processes.stream().filter(serviceProcess -> serviceProcess.serviceName().equalsIgnoreCase(service)).findFirst().get().shutdown(true); - - try { - Thread.sleep(1000); - } catch (InterruptedException ignored) {} - - processes.removeIf(serviceProcess -> serviceProcess.serviceName().equalsIgnoreCase(service)); - NettyDriver.instance().client().sendPacket(new PacketInActionSuccess(false, service, Driver.instance().daemonSafe().daemonName(), 0)); - } + if (Driver.instance().daemonSafe() == null || Bootstrap.instance().shutdown()) return; + QueueEntry shutdown = queue.stream().filter(entry -> !entry.run()).findFirst().orElse(null); + if (shutdown != null && queue.remove(shutdown)) { + queue.removeIf(entry -> entry.run() && entry.service().equalsIgnoreCase(shutdown.service())); + stop(shutdown.service()); + return; + } + for (ServiceProcess process : processes) { + if (!process.process().isAlive()) { + stop(process.serviceName()); + continue; + } + if ("forge".equals(process.group().storage().platform()) && process.serverReady() + && reportedReady.add(process.serviceName())) { + NettyDriver.instance().client().sendPacket(new PacketInDaemonServiceReady(process.serviceName(), + Driver.instance().daemonSafe().daemonName())); } } + if (queue.isEmpty() || CpuUsageResolver.systemCpuLoad() > Bootstrap.instance().config().processorUsage()) return; + QueueEntry next = queue.pollFirst(); + if (next == null) return; + if (next.run()) start(next); + else stop(next.service()); } }, 1, 1, SchedulerUtil.SECONDS); } - private Integer freePort(boolean proxy) { - List ports = processes.stream().map(ServiceProcess::port).toList(); - return IntStream.range(proxy ? Driver.instance().daemonSafe().proxyPort() : Driver.instance().daemonSafe().servicePort(), Integer.MAX_VALUE).filter(p -> !ports.contains(p)).findFirst().orElse(0); + private void start(QueueEntry entry) { + String name = entry.service(); + if (processes.stream().anyMatch(process -> process.serviceName().equalsIgnoreCase(name))) return; + try { + int port = freePort(entry.group()); + if (port == 0) throw new IllegalStateException("Kein freier Serverport verfügbar."); + ServiceProcess service = new ServiceProcess(entry.group(), name, port, entry.useProtocol()); + service.launch(); + processes.add(service); + NettyDriver.instance().client().sendPacket(new PacketInActionSuccess(true, name, Driver.instance().daemonSafe().daemonName(), port)); + } catch (Exception failure) { + Driver.instance().terminalDriver().log(Type.ERROR, "Service " + name + " konnte nicht starten: " + failure.getMessage()); + NettyDriver.instance().client().sendPacket(new PacketInActionSuccess(false, name, Driver.instance().daemonSafe().daemonName(), 0)); + } + } + + private void stop(String name) { + var service = processes.stream().filter(process -> process.serviceName().equalsIgnoreCase(name)).findFirst().orElse(null); + try { + if (service != null) service.shutdown(true); + processes.remove(service); + reportedReady.remove(name); + NettyDriver.instance().client().sendPacket(new PacketInActionSuccess(false, name, Driver.instance().daemonSafe().daemonName(), 0)); + } catch (Exception failure) { + Driver.instance().terminalDriver().log(Type.ERROR, "Service " + name + " konnte nicht gestoppt werden: " + failure.getMessage()); + queue.add(new QueueEntry(name)); + } + } + + private int freePort(Group group) { + boolean proxy = group.type().equalsIgnoreCase("PROXY"); + int first = proxy && group.storage().startPort() > 0 ? group.storage().startPort() : + proxy ? Driver.instance().daemonSafe().proxyPort() : Driver.instance().daemonSafe().servicePort(); + var ports = processes.stream().map(ServiceProcess::port).collect(java.util.stream.Collectors.toSet()); + return IntStream.rangeClosed(first, 65535).filter(port -> !ports.contains(port)).findFirst().orElse(0); } } diff --git a/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/Bootstrap.java b/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/Bootstrap.java index a826938..a6adc64 100644 --- a/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/Bootstrap.java +++ b/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/Bootstrap.java @@ -3,6 +3,9 @@ package de.wcloudservice.master; import de.wcloudservice.driver.Driver; import de.wcloudservice.driver.configuration.master.MasterConfig; import de.wcloudservice.driver.configuration.message.MessageConfig; +import de.wcloudservice.driver.dashboard.DashboardRuntime; +import de.wcloudservice.driver.dashboard.DashboardRpc; +import de.wcloudservice.driver.dashboard.HostDashboard; import de.wcloudservice.driver.network.in.daemon.*; import de.wcloudservice.driver.network.in.group.PacketInGroupStop; import de.wcloudservice.driver.network.in.main.PacketInMainExecuteCommand; @@ -41,6 +44,7 @@ import lombok.experimental.Accessors; import java.io.File; import java.util.HashMap; +import java.util.ArrayList; import java.util.concurrent.CopyOnWriteArrayList; @Getter @@ -58,6 +62,7 @@ public class Bootstrap implements CloudRunnable { private final QueueDriver queueDriver = new QueueDriver(); private final ServiceDriver serviceDriver = new ServiceDriver(); + private final DashboardRpc dashboardRpc = new DashboardRpc(); @Override public void run() { @@ -133,6 +138,55 @@ public class Bootstrap implements CloudRunnable { Driver.instance().terminalDriver().log(Type.INFO, Driver.instance().languageDriver().translate("cloud-started")); this.serviceDriver.initialize(); + Driver.instance().dashboardShutdown(this::shutdownHook); + var dashboard = new HostDashboard(Driver.instance().groupDriver()::load, name -> { + var task = serviceDriver.service(name); + return task == null ? null : task.process(); + }); + java.util.function.BiFunction host = + (node, input) -> node.equals("local") ? dashboard.handle(input) : dashboardRpc.request(node, input); + DashboardMonitor monitor; + try { + monitor = new DashboardMonitor(); + } catch (java.sql.SQLException unavailable) { + monitor = null; + Driver.instance().terminalDriver().log(Type.WARN, "Der Monitoring-Verlauf konnte nicht initialisiert werden."); + } + var history = monitor; + Driver.instance().dashboardRuntime(new DashboardRuntime(this::dashboardStatus, + group -> this.serviceDriver.startOne(group), service -> { + if (this.serviceDriver.service(service) == null) throw new IllegalArgumentException("Service nicht gefunden."); + this.serviceDriver.unregister(service); + }, serviceDriver::restart, serviceDriver::restartGroup, host, this::dashboardPlayers, service -> { + var task = serviceDriver.service(service); + return task == null ? null : task.dashboardPlugins(); + }, (group, minutes) -> history == null ? java.util.List.of() : history.history(group, minutes))); + if (monitor != null) monitor.start(this::dashboardStatus, + () -> Driver.instance().groupDriver().getAll().stream().map(group -> group.name()).toList(), + () -> store.onlineCloudPlayers().size(), host); + } + + private java.util.List dashboardPlayers() { + var players = new java.util.LinkedHashMap(); + Driver.instance().playerCacheDriver().snapshot().forEach(player -> players.put(player.uniqueId(), + new DashboardRuntime.Player(player.name(), player.uniqueId(), false, player.lastProxy(), player.lastService(), player.lastConnected()))); + store.onlineCloudPlayers().forEach(player -> players.put(player.uniqueId(), new DashboardRuntime.Player( + player.name(), player.uniqueId(), true, player.proxyService(), player.service(), System.currentTimeMillis()))); + return java.util.List.copyOf(players.values()); + } + + private DashboardRuntime.Status dashboardStatus() { + var services = this.serviceDriver.services().stream().map(task -> { + var entry = task.entry(); + return new DashboardRuntime.Service(entry.serviceName(), entry.groupName(), entry.daemon(), + task.stopping() || queueDriver.queueShutdown().contains(entry.serviceName()) ? "STOPPING" : entry.status().name(), + entry.currentPlayers(), entry.usedPort(), task.launchedAt(), entry.uniqueId()); + }).toList(); + var nodes = new ArrayList(); + nodes.add(new DashboardRuntime.Node("local", this.config.address(), true)); + this.config.daemons().forEach(daemon -> nodes.add(new DashboardRuntime.Node(daemon.name(), daemon.address(), + NettyDriver.instance().server().isChannelFound(daemon.name())))); + return new DashboardRuntime.Status(services, nodes, this.store.memory()); } public void initializeNetty() { @@ -161,6 +215,7 @@ public class Bootstrap implements CloudRunnable { NettyDriver.instance().packetDriver().listen(new PacketInServiceExecuteCommand().packetUid(), PacketInServiceExecuteCommand.class, new HandlePacketInServiceExecuteCommand()); NettyDriver.instance().packetDriver().listen(new PacketInServiceReaction().packetUid(), PacketInServiceReaction.class, new HandlePacketInServiceReaction()); NettyDriver.instance().packetDriver().listen(new PacketInServiceStop().packetUid(), PacketInServiceStop.class, new HandlePacketInServiceStop()); + NettyDriver.instance().packetDriver().listen(new PacketInServicePlugins().packetUid(), PacketInServicePlugins.class, new HandlePacketInServicePlugins()); //NettyDriver.instance().packetDriver().listen(new PacketInPlayerCache().packetUid(), PacketInPlayerCache.class, null); NettyDriver.instance().packetDriver().listen(new PacketInPlayerConnect().packetUid(), PacketInPlayerConnect.class, new HandlePacketInPlayerConnect()); @@ -176,6 +231,8 @@ public class Bootstrap implements CloudRunnable { NettyDriver.instance().packetDriver().listen(new PacketInAuth().packetUid(), PacketInAuth.class, new HandlePacketInAuth()); NettyDriver.instance().packetDriver().listen(new PacketInActionSuccess().packetUid(), PacketInActionSuccess.class, new HandlePacketInActionSuccess()); + NettyDriver.instance().packetDriver().listen(new PacketInDaemonServiceReady().packetUid(), PacketInDaemonServiceReady.class, new HandlePacketInActionSuccess()); + dashboardRpc.registerMaster(); NettyDriver.instance().packetDriver().listen(new PacketInSendConsole().packetUid(), PacketInSendConsole.class, new HandlePacketInSendConsole()); NettyDriver.instance().packetDriver().listen(new PacketInSendConsoleFromDaemon().packetUid(), PacketInSendConsoleFromDaemon.class, new HandlePacketInSendConsoleFromDaemon()); NettyDriver.instance().packetDriver().listen(new PacketInShutdownDaemon().packetUid(), PacketInShutdownDaemon.class, new HandlePacketInShutdownDaemon()); diff --git a/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/commands/ServiceCommand.java b/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/commands/ServiceCommand.java index ab2a311..9a21cb0 100644 --- a/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/commands/ServiceCommand.java +++ b/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/commands/ServiceCommand.java @@ -5,7 +5,6 @@ import de.wcloudservice.driver.configuration.group.Group; import de.wcloudservice.driver.minimessage.CloudMessage; import de.wcloudservice.driver.network.out.main.PacketOutMainWhitelist; import de.wcloudservice.driver.network.out.player.based.PacketOutPlayerBasedKick; -import de.wcloudservice.driver.process.ServiceState; import de.wcloudservice.driver.storage.players.SimpleCloudPlayer; import de.wcloudservice.driver.storage.service.RunningService; import de.wcloudservice.driver.terminal.command.CommandAdapter; @@ -94,14 +93,13 @@ public class ServiceCommand extends CommandAdapter { } } - for (int i = 0; i != Integer.parseInt(args[2]); i++) { - String id = Bootstrap.instance().config().uniqueId().equals("INT") ? String.valueOf(Bootstrap.instance().serviceDriver().freeId(gdata.name())) : Bootstrap.instance().serviceDriver().freeUniqueId(); - String entryName = gdata.name() + Bootstrap.instance().config().splitter() + id; - int freePort = Bootstrap.instance().serviceDriver().freePort(gdata.type().equalsIgnoreCase("PROXY")); - int memoryAfter = Bootstrap.instance().store().memory() - gdata.usedMemory(); - - Bootstrap.instance().serviceDriver().register(new RunningService(0, 0, 0, freePort, ServiceState.QUEUED, System.currentTimeMillis(), gdata.name(), entryName, gdata.storage().runningDaemon(), Integer.parseInt(id), Bootstrap.instance().config().useProtocol())); - Bootstrap.instance().store().memory(memoryAfter); + for (int i = 0; i < Integer.parseInt(args[2]); i++) { + try { + Bootstrap.instance().serviceDriver().startOne(gdata.name()); + } catch (IllegalArgumentException unavailable) { + Driver.instance().terminalDriver().log(Type.COMMAND, unavailable.getMessage()); + break; + } } } else { Driver.instance().terminalDriver().log(Type.COMMAND, Driver.instance().languageDriver().translate("command-service-only-number")); diff --git a/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/networking/daemon/HandlePacketInActionSuccess.java b/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/networking/daemon/HandlePacketInActionSuccess.java index 0265f55..a982f3b 100644 --- a/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/networking/daemon/HandlePacketInActionSuccess.java +++ b/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/networking/daemon/HandlePacketInActionSuccess.java @@ -2,8 +2,11 @@ package de.wcloudservice.master.networking.daemon; import de.wcloudservice.driver.Driver; import de.wcloudservice.driver.network.in.daemon.PacketInActionSuccess; +import de.wcloudservice.driver.network.in.daemon.PacketInDaemonServiceReady; import de.wcloudservice.driver.terminal.enums.Type; import de.wcloudservice.master.Bootstrap; +import de.wcloudservice.master.service.entry.TaskedService; +import de.wcloudservice.networking.NettyDriver; import de.wcloudservice.networking.packet.NettyAdapter; import de.wcloudservice.networking.packet.Packet; import io.netty.channel.Channel; @@ -12,15 +15,27 @@ public class HandlePacketInActionSuccess implements NettyAdapter { @Override public

void handle(Channel channel, P handlePacket) { - if(handlePacket instanceof PacketInActionSuccess packet) { - if(!packet.launched()) { - Bootstrap.instance().serviceDriver().unregister(packet.service()); + if (handlePacket instanceof PacketInActionSuccess packet) { + var task = find(channel, packet.service(), packet.daemon()); + if (task == null) return; + if (!packet.launched()) { + Bootstrap.instance().serviceDriver().unregistered(packet.service()); return; } - - Driver.instance().terminalDriver().log(Type.INFO, Driver.instance().languageDriver().translate("network-daemon-start-service", packet.daemon(), packet.service(), "" + packet.port())); - Bootstrap.instance().serviceDriver().service(packet.service()).entry().usedPort(packet.port()); + if (packet.port() < 1 || packet.port() > 65535) return; + task.entry().usedPort(packet.port()); + Driver.instance().terminalDriver().log(Type.NETWORK, Driver.instance().languageDriver().translate( + "network-daemon-start-service", packet.daemon(), packet.service(), String.valueOf(packet.port()))); + } else if (handlePacket instanceof PacketInDaemonServiceReady packet) { + var task = find(channel, packet.service(), packet.daemon()); + if (task != null && "forge".equals(task.entry().group().storage().platform())) task.handleForgeReady(); } } -} \ No newline at end of file + private TaskedService find(Channel channel, String service, String daemon) { + var task = Bootstrap.instance().serviceDriver().service(service); + if (task == null || !task.entry().daemon().equals(daemon) + || NettyDriver.instance().server().channels().get(daemon) != channel) return null; + return task; + } +} diff --git a/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/service/ServiceDriver.java b/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/service/ServiceDriver.java index 51ea539..ffdd513 100644 --- a/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/service/ServiceDriver.java +++ b/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/service/ServiceDriver.java @@ -36,18 +36,107 @@ public class ServiceDriver { private final ConcurrentLinkedDeque services = new ConcurrentLinkedDeque<>(); private final ArrayDeque delete = new ArrayDeque<>(); private final NetworkEntry entry = new NetworkEntry(0, 0, new HashMap<>()); + private final Map reservedMemory = new HashMap<>(); + private final Map restarts = new java.util.concurrent.ConcurrentHashMap<>(); + private record Restart(String group, int id, boolean manual) {} public void initialize() { this.handleServices(); } + public synchronized void startOne(String name) { + startOne(name, true); + } + + public void startReplacement(String name) { + startOne(name, false); + } + + private synchronized void startOne(String name, boolean manual) { + Group group = Driver.instance().groupDriver().load(name); + if (group == null) throw new IllegalArgumentException("Gruppe nicht gefunden."); + if (restarts.values().stream().anyMatch(item -> item.group().equalsIgnoreCase(group.name()))) { + throw new IllegalArgumentException("Für die Gruppe ist ein Neustart eingeplant."); + } + var bootstrap = Bootstrap.instance(); + String daemon = group.storage().runningDaemon(); + boolean local = "local".equalsIgnoreCase(daemon); + if (!local && !NettyDriver.instance().server().isChannelFound(daemon)) { + throw new IllegalArgumentException("Der Daemon ist offline."); + } + int max = group.maximalOnline(); + if (max != -1 && servicesByGroup(group.name()).size() >= max) { + throw new IllegalArgumentException("Die maximale Anzahl an Instanzen ist erreicht."); + } + if (local && bootstrap.store().memory() < group.usedMemory()) { + throw new IllegalArgumentException("Auf dem Master ist zu wenig RAM verfügbar."); + } + int id = freeId(group.name()); + String suffix = bootstrap.config().uniqueId().equals("INT") ? String.valueOf(id) : freeUniqueId(); + String service = group.name() + bootstrap.config().splitter() + suffix; + enqueue(group, id, service, manual); + } + + private void enqueue(Group group, int id, String service, boolean manual) { + var bootstrap = Bootstrap.instance(); + String daemon = group.storage().runningDaemon(); + boolean local = "local".equalsIgnoreCase(daemon); + boolean proxy = group.type().equalsIgnoreCase("PROXY"); + int preferred = proxy ? group.storage().startPort() : 0; + int port = local ? freePort(proxy, preferred) : -1; + if (port == 0) throw new IllegalStateException("Kein freier Serverport verfügbar."); + var task = register(new RunningService(0, 0, 0, port, ServiceState.QUEUED, System.currentTimeMillis(), + group.name(), service, daemon, id, bootstrap.config().useProtocol())); + task.manuallyStarted(manual); + if (local) { + reservedMemory.put(service, group.usedMemory()); + bootstrap.store().memory(bootstrap.store().memory() - group.usedMemory()); + } + } + + public synchronized void restart(String service) { + TaskedService task = this.service(service); + if (task == null || task.entry().status() == ServiceState.QUEUED || task.stopping()) { + throw new IllegalStateException("Diese Instanz kann gerade nicht neu gestartet werden."); + } + if (restarts.putIfAbsent(service, new Restart(task.entry().groupName(), task.entry().usedId(), task.manuallyStarted())) != null) { + throw new IllegalStateException("Der Neustart läuft bereits."); + } + unregister(service); + } + + public synchronized void restartGroup(String group) { + var active = servicesByGroup(group).stream().filter(task -> + task.entry().status() != ServiceState.QUEUED && !task.stopping()).toList(); + if (active.isEmpty()) throw new IllegalStateException("In der Gruppe läuft keine Instanz."); + active.forEach(task -> restart(task.entry().serviceName())); + } + + private synchronized void enqueueRestarts() { + for (var item : restarts.entrySet()) { + if (service(item.getKey()) != null) continue; + Restart restart = item.getValue(); + Group group = Driver.instance().groupDriver().load(restart.group()); + if (group == null) { + restarts.remove(item.getKey(), restart); + continue; + } + String host = group.storage().runningDaemon(); + if (host.equalsIgnoreCase("local") ? Bootstrap.instance().store().memory() < group.usedMemory() : + !NettyDriver.instance().server().isChannelFound(host)) continue; + try { + enqueue(group, restart.id(), item.getKey(), restart.manual()); + } catch (IllegalStateException unavailable) { + continue; + } + restarts.remove(item.getKey(), restart); + } + } + public TaskedService register(RunningService entry) { if (this.service(entry.serviceName()) != null) { - if (!entry.serviceName().endsWith("0")) { - return this.service(entry.serviceName()); - } - return null; - } else if (entry.serviceName().endsWith("0")) { + return this.service(entry.serviceName()); + } else if (entry.usedId() < 1) { return null; } else { if (!this.entry.groupPlayerPotency().containsKey(entry.groupName())) { @@ -74,7 +163,7 @@ public class ServiceDriver { Bootstrap.instance().queueDriver().addQueuedObjectToShutdown(service); } - public void unregistered(String service) { + public synchronized void unregistered(String service) { TaskedService tasked = this.service(service); if (tasked == null) return; if (NettyDriver.instance().server().isChannelFound(service)) { @@ -82,13 +171,18 @@ public class ServiceDriver { } if (this.services.remove(tasked) && "local".equalsIgnoreCase(tasked.entry().daemon())) { - int memory = Driver.instance().groupDriver().load(tasked.entry().groupName()).usedMemory(); + Integer reserved = reservedMemory.remove(service); + Group group = Driver.instance().groupDriver().load(tasked.entry().groupName()); + int memory = reserved != null ? reserved : group == null ? 0 : group.usedMemory(); Bootstrap.instance().store().memory(Bootstrap.instance().store().memory() + memory); } } public Integer freeId(String group) { - return Optional.ofNullable(Driver.instance().groupDriver().load(group)).map(gs -> IntStream.range(1, gs.maximalOnline() == -1 ? Integer.MAX_VALUE : gs.maximalOnline() + 1).filter(i -> !this.servicesByGroup(group).stream().map(s -> Integer.parseInt(s.entry().serviceName().replace(group, "").replace(Bootstrap.instance().config().splitter(), ""))).toList().contains(i)).findFirst().orElse(0)).orElse(0); + var usedIds = servicesByGroup(group).stream().map(task -> task.entry().usedId()).collect(Collectors.toSet()); + restarts.values().stream().filter(restart -> restart.group().equalsIgnoreCase(group)) + .map(Restart::id).forEach(usedIds::add); + return IntStream.range(1, Integer.MAX_VALUE).filter(id -> !usedIds.contains(id)).findFirst().orElseThrow(); } public String freeUniqueId() { @@ -104,9 +198,16 @@ public class ServiceDriver { } public Integer freePort(boolean proxy) { - return IntStream.range(proxy ? Bootstrap.instance().config().proxyPort() : Bootstrap.instance().config().servicePort(), Integer.MAX_VALUE).filter(p -> !this.services().stream().map(TaskedService::entry).map(RunningService::usedPort).toList().contains(p)).findFirst().orElse(0); + return freePort(proxy, 0); } + private int freePort(boolean proxy, int preferred) { + int first = preferred > 0 ? preferred : proxy ? Bootstrap.instance().config().proxyPort() : Bootstrap.instance().config().servicePort(); + var ports = services.stream().filter(task -> task.entry().daemon().equalsIgnoreCase("local")) + .map(task -> task.entry().usedPort()).collect(Collectors.toSet()); + return IntStream.rangeClosed(first, 65535).filter(port -> !ports.contains(port)).findFirst().orElse(0); + } + public void shutdown(ArrayList tasks) { this.services.stream().filter(service1 -> tasks.contains(service1.entry().serviceName())).toList().forEach(TaskedService::handleQuit); tasks.forEach(this::unregistered); @@ -123,18 +224,22 @@ public class ServiceDriver { // Stops must remain possible while startup is throttled or the master shuts down. String stopping = queues.queueShutdown().pollFirst(); if (stopping != null) { - queues.queueStartup().remove(stopping); + boolean pendingStart = queues.queueStartup().remove(stopping); TaskedService tasked = service(stopping); if (tasked != null) { boolean local = "local".equalsIgnoreCase(tasked.entry().daemon()); - if (local ? tasked.process() != null : NettyDriver.instance().server().isChannelFound(tasked.entry().daemon())) { + if (!local && !pendingStart && NettyDriver.instance().server().isChannelFound(tasked.entry().daemon())) { + // Keep the service name reserved until the daemon confirms cleanup. tasked.handleQuit(); + } else { + if (local && tasked.process() != null) tasked.handleQuit(); + unregistered(stopping); } - unregistered(stopping); } } if (bootstrap.shutdown() || CpuUsageResolver.systemCpuLoad() > bootstrap.config().processorUsage()) return; + if (!restarts.isEmpty()) enqueueRestarts(); long starting = services.stream().filter(tasked -> tasked.entry().status() == ServiceState.STARTED).count(); if (starting >= bootstrap.config().serviceStartupCount()) return; @@ -154,7 +259,13 @@ public class ServiceDriver { ? new CloudProxyLaunchEvent(name, tasked.entry().groupName(), daemon) : new CloudServiceLaunchEvent(name, tasked.entry().groupName(), daemon)); tasked.handleStatusChange(ServiceState.STARTED); - tasked.handleLaunch(); + try { + tasked.handleLaunch(); + } catch (Exception failure) { + Driver.instance().terminalDriver().log(de.wcloudservice.driver.terminal.enums.Type.ERROR, + "Service " + name + " konnte nicht starten: " + failure.getMessage()); + unregistered(name); + } } // Preserve the queue's pacing: launch at most one service per tick. break; @@ -223,6 +334,7 @@ public class ServiceDriver { if (!Bootstrap.instance().shutdown()) { List services = services().stream() .filter(taskedService -> taskedService.entry().status() == ServiceState.LOBBY) + .filter(ServiceDriver.this::canScaleDown) .filter(taskedService -> taskedService.entry().currentPlayers() == 0) .filter(taskedService -> Integer.parseInt(String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - taskedService.entry().time()))) >= 120) .toList(); @@ -248,6 +360,7 @@ public class ServiceDriver { .toList(); servicess.forEach(taskedService -> { + if (!canScaleDown(taskedService) || taskedService.entry().currentPlayers() > 0) return; Group group = Driver.instance().groupDriver().load(taskedService.entry().groupName()); int minonline = (!entry.groupPlayerPotency().containsKey(group.name())) ? group.minimalOnline() : (entry.groupPlayerPotency().get(group.name()) == 0 && entry.globalPlayerPotency() == 0) ? group.minimalOnline() @@ -312,18 +425,11 @@ public class ServiceDriver { int online = (!entry.groupPlayerPotency().containsKey(group.name())) ? group.minimalOnline() : (entry.groupPlayerPotency().get(group.name()) == 0 && entry.globalPlayerPotency() == 0) ? group.minimalOnline() : (entry.globalPlayerPotency() != 0) ? group.over100AtNetwork() * entry.globalPlayerPotency() : group.over100AtGroup() * entry.groupPlayerPotency().get(group.name()); if (!delete.contains(group.name())) { int minimal = online - activeServices(group.name()); - for (int i = 0; i != minimal; i++) { - String id = Bootstrap.instance().config().uniqueId().equals("INT") ? String.valueOf(freeId(group.name())) : freeUniqueId(); - String entryName = group.name() + Bootstrap.instance().config().splitter() + id; - String daemon = group.storage().runningDaemon(); - int freePort = freePort(group.type().equalsIgnoreCase("PROXY")); - int memoryAfter = Bootstrap.instance().store().memory() - group.usedMemory(); - - if(daemon.equals("local") && memoryAfter >= 0) { - register(new RunningService(0, 0, 0, freePort, ServiceState.QUEUED, System.currentTimeMillis(), group.name(), entryName, daemon, Integer.parseInt(id), Bootstrap.instance().config().useProtocol())); - Bootstrap.instance().store().memory(memoryAfter); - } else { - register(new RunningService(0, 0, 0, -1, ServiceState.QUEUED, System.currentTimeMillis(), group.name(), entryName, daemon, Integer.parseInt(id), Bootstrap.instance().config().useProtocol())); + for (int i = 0; i < minimal; i++) { + try { + startOne(group.name(), false); + } catch (IllegalArgumentException unavailable) { + break; } } } @@ -338,7 +444,7 @@ public class ServiceDriver { @Override public void run() { if (!Bootstrap.instance().shutdown()) { - services().parallelStream().filter(taskedService -> taskedService.entry().status() != ServiceState.QUEUED && taskedService.entry().status() == ServiceState.STARTED).toList().forEach(taskedService -> { + services().stream().filter(taskedService -> taskedService.entry().status() != ServiceState.QUEUED).toList().forEach(taskedService -> { if (taskedService.process() != null && taskedService.process().process() != null &&!taskedService.process().process().isAlive()) { unregister(taskedService.entry().serviceName()); if (Driver.instance().groupDriver().load(taskedService.entry().groupName()).type().equalsIgnoreCase("PROXY")) { @@ -380,6 +486,11 @@ public class ServiceDriver { Objects.requireNonNull(this.services.stream().filter(service1 -> service1.entry().serviceName().equals(service)).findFirst().orElse(null)).handleCloudPlayerConnection(connect); } + private boolean canScaleDown(TaskedService task) { + Group group = task.entry().group(); + return group != null && !task.manuallyStarted() && !group.runStatic() && !"forge".equals(group.storage().platform()); + } + public TaskedService service(String service) { return this.services.stream().noneMatch(service1 -> service1.entry().serviceName().equals(service)) ? null : this.services.stream().filter(service1 -> service1.entry().serviceName().equals(service)).findFirst().orElse(null); } diff --git a/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/service/entry/TaskedService.java b/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/service/entry/TaskedService.java index 87cb353..1065fa6 100644 --- a/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/service/entry/TaskedService.java +++ b/wcloud-runnable/wcloud-master/src/main/java/de/wcloudservice/master/service/entry/TaskedService.java @@ -9,6 +9,7 @@ import de.wcloudservice.driver.network.out.daemon.*; import de.wcloudservice.driver.network.out.service.PacketOutServiceChangeState; import de.wcloudservice.driver.network.out.service.PacketOutServiceDisconnected; import de.wcloudservice.driver.network.out.service.PacketOutServiceLaunch; +import de.wcloudservice.driver.network.out.service.PacketOutServiceConnected; import de.wcloudservice.driver.network.out.service.PacketOutServicePrepared; import de.wcloudservice.driver.process.ServiceProcess; import de.wcloudservice.driver.process.ServiceState; @@ -27,11 +28,16 @@ import java.util.TimerTask; @Getter @Accessors(fluent = true) public class TaskedService { + @Setter + private volatile java.util.List dashboardPlugins; + private volatile long launchedAt; private RunningService entry; private ServiceProcess process; @Setter private boolean started = false; + @Setter + private volatile boolean manuallyStarted; private volatile boolean stopping = false; private Timer base = new Timer(); @@ -90,8 +96,23 @@ public class TaskedService { this.process = new ServiceProcess(Driver.instance().groupDriver().load(this.entry.groupName()), this.entry.serviceName(), this.entry.usedPort(), this.entry.useProtocol()); this.process.launch(); + if ("forge".equals(this.entry.group().storage().platform())) { + Thread.startVirtualThread(() -> { + while (this.process.process().isAlive() && !this.stopping && !this.process.serverReady()) { + try { Thread.sleep(500); } + catch (InterruptedException cancelled) { Thread.currentThread().interrupt(); return; } + } + if (this.process.serverReady() && this.process.process().isAlive() && !this.stopping) handleForgeReady(); + }); + } } + public synchronized void handleForgeReady() { + if (this.stopping || this.entry.status() != ServiceState.STARTED) return; + handleStatusChange(ServiceState.LOBBY); + NettyDriver.instance().server().sendPacket(new PacketOutServiceConnected(this.entry)); + } + public void handleScreen() { if(!this.entry.daemon().equalsIgnoreCase("local")) { if (Driver.instance().terminalDriver().serviceScreen()) { @@ -198,6 +219,7 @@ public class TaskedService { } public void handleStatusChange(ServiceState status) { + if (status == ServiceState.STARTED && launchedAt == 0) launchedAt = System.currentTimeMillis(); this.entry.status(status); if (Driver.instance().groupDriver().load(this.entry.groupName()).type().equals("PROXY")) { @@ -208,59 +230,15 @@ public class TaskedService { NettyDriver.instance().server().sendPacket(new PacketOutServiceChangeState(this.entry.serviceName(), false, status, this.entry.daemon())); } - if (status == ServiceState.INGAME) { - this.started = true; - - if(this.entry.daemon().equalsIgnoreCase("local")) { - int freeMemory = Bootstrap.instance().store().memory(); - int memoryAfter = freeMemory - Driver.instance().groupDriver().load(this.entry.groupName()).usedMemory(); - - if (memoryAfter >= 0) { - int id = Bootstrap.instance().serviceDriver().freeId(this.entry.groupName()); - - TaskedService taskedService = Bootstrap.instance().serviceDriver().register( - new RunningService( - 0, - 0, - 0, - Bootstrap.instance().serviceDriver().freePort(Driver.instance().groupDriver().load(this.entry.groupName()).type().equalsIgnoreCase("PROXY")), - ServiceState.QUEUED, - System.currentTimeMillis(), - this.entry.groupName(), - this.entry.groupName() + Bootstrap.instance().config().splitter() + id, - this.entry.daemon(), - id, - this.entry.useProtocol() - ) - ); - - Bootstrap.instance().store().memory(Bootstrap.instance().store().memory() - Driver.instance().groupDriver().load(this.entry.groupName()).usedMemory()); - taskedService.handleLaunch(); - } - } else { - int id = Bootstrap.instance().serviceDriver().freeId(this.entry.groupName()); - - TaskedService taskedService = Bootstrap.instance().serviceDriver().register( - new RunningService( - 0, - 0, - 0, - Bootstrap.instance().serviceDriver().freePort(Driver.instance().groupDriver().load(this.entry.groupName()).type().equalsIgnoreCase("PROXY")), - ServiceState.QUEUED, - System.currentTimeMillis(), - this.entry.groupName(), - this.entry.groupName() + Bootstrap.instance().config().splitter() + id, - this.entry.daemon(), - id, - this.entry.useProtocol() - ) - ); - - Bootstrap.instance().store().memory(Bootstrap.instance().store().memory() - Driver.instance().groupDriver().load(this.entry.groupName()).usedMemory()); - taskedService.handleLaunch(); + if (status == ServiceState.INGAME) { + this.started = true; + try { + Bootstrap.instance().serviceDriver().startReplacement(this.entry.groupName()); + } catch (IllegalArgumentException unavailable) { + // The group's capacity or its host prevent starting another instance. } - } - } + } + } public void handleCloudPlayerConnection(boolean connect) { if (connect) { diff --git a/wcloud-runnable/wcloud-master/src/test/java/de/wcloudservice/master/service/ServiceQueueTest.java b/wcloud-runnable/wcloud-master/src/test/java/de/wcloudservice/master/service/ServiceQueueTest.java index 4918f9d..dda7dce 100644 --- a/wcloud-runnable/wcloud-master/src/test/java/de/wcloudservice/master/service/ServiceQueueTest.java +++ b/wcloud-runnable/wcloud-master/src/test/java/de/wcloudservice/master/service/ServiceQueueTest.java @@ -204,6 +204,22 @@ class ServiceQueueTest { assertTrue(queues.queueStartup().isEmpty()); } + @Test + void stoppingRemoteServiceReservesItsNameUntilDaemonConfirmsCleanup() { + TaskedService task = queued("Remote", "daemon-a"); + queues.queueStartup().remove("Remote-1"); + when(networking.server().isChannelFound("daemon-a")).thenReturn(true); + queues.queueShutdown().add("Remote-1"); + + services.processQueues(); + + verify(task).handleQuit(); + assertSame(task, services.service("Remote-1")); + + services.unregistered("Remote-1"); + assertNull(services.service("Remote-1")); + } + @Test void masterShutdownPreventsNewStarts() { TaskedService task = queued("Proxy", "local");