Add support for custom server jars

This commit is contained in:
Norbi Peti 2019-08-22 16:07:32 +02:00
parent 2dac8eb9f5
commit 8310e0889b
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
11 changed files with 361 additions and 284 deletions

2
.idea/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
# Default ignored files
/workspace.xml

View file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: jline:jline:2.12" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.21" level="project" />
</component>
</module>

4
.idea/encodings.xml Normal file
View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with NO BOM" />
</project>

View file

@ -0,0 +1,11 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="WeakerAccess" enabled="true" level="WARNING" enabled_by_default="true">
<option name="SUGGEST_PACKAGE_LOCAL_FOR_MEMBERS" value="false" />
<option name="SUGGEST_PACKAGE_LOCAL_FOR_TOP_CLASSES" value="false" />
<option name="SUGGEST_PRIVATE_FOR_INNERS" value="false" />
<disabledExtension id="moduleInfo" />
</inspection_tool>
</profile>
</component>

View file

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="Maven: org.yaml:snakeyaml:1.21">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/yaml/snakeyaml/1.21/snakeyaml-1.21.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/yaml/snakeyaml/1.21/snakeyaml-1.21-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/yaml/snakeyaml/1.21/snakeyaml-1.21-sources.jar!/" />
</SOURCES>
</library>
</component>

View file

@ -0,0 +1,3 @@
<component name="MarkdownNavigator.ProfileManager">
<settings default="" pdf-export="" />
</component>

8
.idea/modules.xml Normal file
View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/MCServerRunner.iml" filepath="$PROJECT_DIR$/MCServerRunner.iml" />
</modules>
</component>
</project>

15
MCServerRunner.iml Normal file
View file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: jline:jline:2.12" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.21" level="project" />
</component>
</module>

117
pom.xml
View file

@ -1,59 +1,60 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>ButtonDevTeam</groupId> <groupId>ButtonDevTeam</groupId>
<artifactId>MCServerRunner</artifactId> <artifactId>MCServerRunner</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<build> <build>
<sourceDirectory>src</sourceDirectory> <sourceDirectory>src</sourceDirectory>
<plugins> <finalName>ServerRunner</finalName>
<plugin> <plugins>
<artifactId>maven-compiler-plugin</artifactId> <plugin>
<version>3.5.1</version> <artifactId>maven-compiler-plugin</artifactId>
<configuration> <version>3.5.1</version>
<source>1.8</source> <configuration>
<target>1.8</target> <source>1.8</source>
</configuration> <target>1.8</target>
</plugin> </configuration>
<plugin> </plugin>
<groupId>org.apache.maven.plugins</groupId> <plugin>
<artifactId>maven-jar-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId>
<version>3.1.0</version> <artifactId>maven-jar-plugin</artifactId>
<configuration> <version>3.1.0</version>
<archive> <configuration>
<manifest> <archive>
<addClasspath>true</addClasspath> <manifest>
<mainClass>buttondevteam.serverrunner.ServerRunner</mainClass> <addClasspath>true</addClasspath>
<classpathPrefix>ServerRunner_lib/</classpathPrefix> <mainClass>buttondevteam.serverrunner.ServerRunner</mainClass>
</manifest> <classpathPrefix>ServerRunner_lib/</classpathPrefix>
</archive> </manifest>
</configuration> </archive>
</plugin> </configuration>
<plugin> </plugin>
<artifactId>maven-shade-plugin</artifactId> <plugin>
<version>3.1.1</version> <artifactId>maven-shade-plugin</artifactId>
<executions> <version>3.1.1</version>
<execution> <executions>
<phase>package</phase> <execution>
<goals> <phase>package</phase>
<goal>shade</goal> <goals>
</goals> <goal>shade</goal>
</execution> </goals>
</executions> </execution>
</plugin> </executions>
</plugins> </plugin>
</build> </plugins>
<dependencies> </build>
<dependency> <dependencies>
<groupId>jline</groupId> <dependency>
<artifactId>jline</artifactId> <groupId>jline</groupId>
<version>2.12</version> <artifactId>jline</artifactId>
</dependency> <version>2.12</version>
<!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml --> </dependency>
<dependency> <!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
<groupId>org.yaml</groupId> <dependency>
<artifactId>snakeyaml</artifactId> <groupId>org.yaml</groupId>
<version>1.21</version> <artifactId>snakeyaml</artifactId>
</dependency> <version>1.21</version>
</dependencies> </dependency>
</dependencies>
</project> </project>

View file

@ -4,6 +4,7 @@ public class Config {
public String serverVersion; public String serverVersion;
public String serverParams; public String serverParams;
public int restartAt; public int restartAt;
public String customJar;
public Config(String serverVersion, String serverParams, int restartAt) { public Config(String serverVersion, String serverParams, int restartAt) {
this.serverVersion = serverVersion; this.serverVersion = serverVersion;
@ -14,5 +15,6 @@ public class Config {
this.serverVersion = "1.12.2"; this.serverVersion = "1.12.2";
this.serverParams = "-Djline.terminal=jline.UnixTerminal -Xms4G -Xmx6G"; this.serverParams = "-Djline.terminal=jline.UnixTerminal -Xms4G -Xmx6G";
this.restartAt = 12; this.restartAt = 12;
this.customJar = "";
} }
} }

View file

@ -1,226 +1,229 @@
package buttondevteam.serverrunner; package buttondevteam.serverrunner;
import jline.console.ConsoleReader; import jline.console.ConsoleReader;
import jline.console.CursorBuffer; import jline.console.CursorBuffer;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.Calendar; import java.util.Calendar;
import java.util.Collections; import java.util.Collections;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class ServerRunner { public class ServerRunner {
private static final int RESTART_MESSAGE_COUNT = 60; private static final int RESTART_MESSAGE_COUNT = 60;
private static final int interval = 24; // hours private static final int interval = 24; // hours
private static volatile boolean stop = false; private static volatile boolean stop = false;
private static int restartcounter = RESTART_MESSAGE_COUNT; private static int restartcounter = RESTART_MESSAGE_COUNT;
private static volatile Process serverprocess; private static volatile Process serverprocess;
private static volatile PrintWriter serveroutput; private static volatile PrintWriter serveroutput;
private static volatile Thread rt; private static volatile Thread rt;
private static volatile ConsoleReader reader; private static volatile ConsoleReader reader;
private static volatile PrintWriter runnerout; private static volatile PrintWriter runnerout;
private static volatile boolean customrestartfailed = false; private static volatile boolean customrestartfailed = false;
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
Yaml yaml = new Yaml(); Yaml yaml = new Yaml();
File f=new File("plugins/ServerRunner/config.yml"); File f = new File("plugins/ServerRunner/config.yml");
f.getParentFile().mkdirs(); f.getParentFile().mkdirs();
final Config config; final Config config;
if(!f.exists()) if (!f.exists())
Files.write(f.toPath(), Collections.singleton(yaml.dump(config = new Config()))); Files.write(f.toPath(), Collections.singleton(yaml.dump(config = new Config())));
else else
config=yaml.load(new FileInputStream(f)); config = yaml.load(new FileInputStream(f));
if (!new File("spigot-" + config.serverVersion + ".jar").exists()) { final File serverJar = new File(config.customJar == null || config.customJar.length() == 0
System.out.println("The server JAR for " + config.serverVersion + " cannot be found!"); ? "spigot-" + config.serverVersion + ".jar"
return; : config.customJar);
} if (!serverJar.exists()) {
reader = new ConsoleReader(); System.out.println("The server JAR for " + config.serverVersion + " cannot be found!");
reader.setPrompt("Runner>"); return;
runnerout = new PrintWriter(reader.getOutput()); }
writeToScreen("Starting server..."); reader = new ConsoleReader();
serverprocess = startServer(config); reader.setPrompt("Runner>");
serveroutput = new PrintWriter(serverprocess.getOutputStream()); runnerout = new PrintWriter(reader.getOutput());
rt = Thread.currentThread(); writeToScreen("Starting server...");
final Thread it = new Thread() { serverprocess = startServer(config, serverJar);
@Override serveroutput = new PrintWriter(serverprocess.getOutputStream());
public void run() { rt = Thread.currentThread();
try { final Thread it = new Thread() {
String readLine; @Override
while (!stop) { public void run() {
try { try {
if ((readLine = reader.readLine()) == null) String readLine;
break; while (!stop) {
if (readLine.equalsIgnoreCase("stop")) try {
ServerRunner.stop(); if ((readLine = reader.readLine()) == null)
serveroutput.println(readLine); break;
serveroutput.flush(); if (readLine.equalsIgnoreCase("stop"))
} catch (Exception e) { ServerRunner.stop();
e.printStackTrace(); serveroutput.println(readLine);
Thread.sleep(100); //Sleep a bit and keep going serveroutput.flush();
} } catch (Exception e) {
} e.printStackTrace();
} catch (InterruptedException e) { Thread.sleep(100); //Sleep a bit and keep going
e.printStackTrace(); }
} }
ServerRunner.stop(); } catch (InterruptedException e) {
writeToScreen("Stopped " + Thread.currentThread().getName()); e.printStackTrace();
} }
}; ServerRunner.stop();
it.setName("InputThread"); writeToScreen("Stopped " + Thread.currentThread().getName());
it.start(); }
final Thread ot = new Thread() { };
@Override it.setName("InputThread");
public void run() { it.start();
try { final Thread ot = new Thread() {
BufferedReader serverinput = new BufferedReader( @Override
new InputStreamReader(serverprocess.getInputStream(), StandardCharsets.UTF_8)); public void run() {
String line; try {
while (true) { BufferedReader serverinput = new BufferedReader(
if ((line = serverinput.readLine()) != null) { new InputStreamReader(serverprocess.getInputStream(), StandardCharsets.UTF_8));
writeToScreen(line); String line;
if (line.contains("FAILED TO BIND TO PORT")) { while (true) {
ServerRunner.stop(); if ((line = serverinput.readLine()) != null) {
writeToScreen("A server is already running!"); writeToScreen(line);
} if (line.contains("FAILED TO BIND TO PORT")) {
if (Pattern.matches( ServerRunner.stop();
"\\[\\d\\d:\\d\\d:\\d\\d INFO]: Unknown command. Type \"/help\" for help.\\s+", line)) writeToScreen("A server is already running!");
customrestartfailed = true; }
if (Pattern.matches(
} else if (!stop) { "\\[\\d\\d:\\d\\d:\\d\\d INFO]: Unknown command. Type \"/help\" for help.\\s+", line))
try { customrestartfailed = true;
serverinput.close();
} catch (Exception e) { } else if (!stop) {
e.printStackTrace(); try {
} serverinput.close();
try { } catch (Exception e) {
serveroutput.close(); e.printStackTrace();
} catch (Exception e) { }
e.printStackTrace(); try {
} serveroutput.close();
writeToScreen("Server stopped! Restarting..."); } catch (Exception e) {
serverprocess = startServer(config); e.printStackTrace();
serverinput = new BufferedReader(new InputStreamReader(serverprocess.getInputStream())); }
serveroutput = new PrintWriter(serverprocess.getOutputStream()); writeToScreen("Server stopped! Restarting...");
restartcounter = RESTART_MESSAGE_COUNT; serverprocess = startServer(config, serverJar);
} else serverinput = new BufferedReader(new InputStreamReader(serverprocess.getInputStream()));
break; serveroutput = new PrintWriter(serverprocess.getOutputStream());
} restartcounter = RESTART_MESSAGE_COUNT;
serverinput.close(); } else
} catch (IOException e) { break;
e.printStackTrace(); }
} serverinput.close();
ServerRunner.stop(); } catch (IOException e) {
writeToScreen("Stopped " + Thread.currentThread().getName()); e.printStackTrace();
} }
}; ServerRunner.stop();
ot.setName("OutputThread"); writeToScreen("Stopped " + Thread.currentThread().getName());
ot.start(); }
Thread.currentThread().setName("RestarterThread"); };
long starttime = syncStart(config.restartAt); ot.setName("OutputThread");
System.out.println("Restart scheduled in " + starttime / 3600000f); ot.start();
boolean firstrun = true; Thread.currentThread().setName("RestarterThread");
while (!stop) { long starttime = syncStart(config.restartAt);
try { System.out.println("Restart scheduled in " + starttime / 3600000f);
if (restartcounter >= 0) { boolean firstrun = true;
if (restartcounter == RESTART_MESSAGE_COUNT) { while (!stop) {
if (firstrun) { try {
// writeToScreen("Sleeping for " + starttime); if (restartcounter >= 0) {
Thread.sleep(starttime); if (restartcounter == RESTART_MESSAGE_COUNT) {
firstrun = false; if (firstrun) {
} else // writeToScreen("Sleeping for " + starttime);
Thread.sleep(interval * 3600000); Thread.sleep(starttime);
customrestartfailed = false; firstrun = false;
serveroutput.println("schrestart"); } else
serveroutput.flush(); Thread.sleep(interval * 3600000);
} else if (restartcounter > 0) { customrestartfailed = false;
if (customrestartfailed) { serveroutput.println("schrestart");
if (restartcounter % 10 == 0) serveroutput.flush();
sendMessage(serveroutput, "red", } else if (restartcounter > 0) {
"-- Server restarting in " + restartcounter + " seconds!"); if (customrestartfailed) {
Thread.sleep(1000); if (restartcounter % 10 == 0)
} else { sendMessage(serveroutput, "red",
restartcounter = RESTART_MESSAGE_COUNT; "-- Server restarting in " + restartcounter + " seconds!");
continue; // Don't decrement the counter so it will sleep the full time Thread.sleep(1000);
} } else {
} else { restartcounter = RESTART_MESSAGE_COUNT;
Thread.sleep(500); continue; // Don't decrement the counter so it will sleep the full time
if (customrestartfailed) { }
writeToScreen("Stopping server for restart..."); } else {
serveroutput.println("restart"); Thread.sleep(500);
serveroutput.flush(); if (customrestartfailed) {
customrestartfailed = false; writeToScreen("Stopping server for restart...");
} serveroutput.println("restart");
Thread.sleep(5000); // Don't run needless cycles serveroutput.flush();
} customrestartfailed = false;
restartcounter--; }
} Thread.sleep(5000); // Don't run needless cycles
} catch (InterruptedException e) { // The while checks if stop is true and then stops }
} restartcounter--;
} }
writeToScreen("Stopped " + Thread.currentThread().getName()); } catch (InterruptedException e) { // The while checks if stop is true and then stops
} }
}
private static Process startServer(Config config) throws IOException { writeToScreen("Stopped " + Thread.currentThread().getName());
return Runtime.getRuntime().exec(("java "+config.serverParams+" -jar spigot-" + config.serverVersion + ".jar").split(" ")); }
}
private static Process startServer(Config config, File serverJar) throws IOException {
private static void sendMessage(PrintWriter output, String color, String text) { return Runtime.getRuntime().exec(new String[]{"java", config.serverParams, "-jar", serverJar.getPath()});
output.println("tellraw @a {\"text\":\"" + text + "\",\"color\":\"" + color + "\"}"); }
output.flush();
writeToScreen(text); private static void sendMessage(PrintWriter output, String color, String text) {
} output.println("tellraw @a {\"text\":\"" + text + "\",\"color\":\"" + color + "\"}");
output.flush();
private static void stop() { writeToScreen(text);
stop = true; }
rt.interrupt(); // The restarter thread sleeps for a long time and keeps the program running
} private static void stop() {
stop = true;
private static void writeToScreen(String line) { rt.interrupt(); // The restarter thread sleeps for a long time and keeps the program running
stashLine(); }
runnerout.println(line);
unstashLine(); private static void writeToScreen(String line) {
} stashLine();
runnerout.println(line);
private static CursorBuffer stashed; unstashLine();
}
private static void stashLine() {
stashed = reader.getCursorBuffer().copy(); private static CursorBuffer stashed;
try {
reader.getOutput().write("\u001b[1G\u001b[K"); private static void stashLine() {
reader.flush(); stashed = reader.getCursorBuffer().copy();
} catch (IOException e) { try {
// ignore reader.getOutput().write("\u001b[1G\u001b[K");
} reader.flush();
} } catch (IOException e) {
// ignore
private static void unstashLine() { }
try { }
reader.resetPromptLine(reader.getPrompt(), stashed.toString(), stashed.cursor);
} catch (IOException e) { private static void unstashLine() {
// ignore try {
} reader.resetPromptLine(reader.getPrompt(), stashed.toString(), stashed.cursor);
} } catch (IOException e) {
// ignore
private static double hoursOf(Calendar parsedTime) { }
return parsedTime.get(Calendar.HOUR_OF_DAY) + parsedTime.get(Calendar.MINUTE) / 60. }
+ parsedTime.get(Calendar.SECOND) / 3600.;
} private static double hoursOf(Calendar parsedTime) {
return parsedTime.get(Calendar.HOUR_OF_DAY) + parsedTime.get(Calendar.MINUTE) / 60.
private static long syncStart(double startHour) { // Copied original code from SimpleBackup + parsedTime.get(Calendar.SECOND) / 3600.;
double now = hoursOf(Calendar.getInstance(TimeZone.getTimeZone("GMT"))); }
double diff = now - startHour;
if (diff < 0) { private static long syncStart(double startHour) { // Copied original code from SimpleBackup
diff += 24; double now = hoursOf(Calendar.getInstance(TimeZone.getTimeZone("GMT")));
} double diff = now - startHour;
double intervalPart = diff - Math.floor(diff / interval) * interval; if (diff < 0) {
double remaining = interval - intervalPart; diff += 24;
return (long) (remaining * 3600000); }
} double intervalPart = diff - Math.floor(diff / interval) * interval;
double remaining = interval - intervalPart;
} return (long) (remaining * 3600000);
}
}