mirror of
https://github.com/simon987/Much-Assembly-Required.git
synced 2025-04-19 18:46:43 +00:00
Added functionality to archive list of saves when the game server exits.
The number of saves that will be archived can be modified using max_archive_size in config.properties. Added shutdown hook to Main.java to handle dumping of zip files. Essential functions are in ZipUtils.java.
This commit is contained in:
parent
94c1d4689c
commit
f08b5632cc
@ -1,6 +1,5 @@
|
|||||||
package net.simon987.server;
|
package net.simon987.server;
|
||||||
|
|
||||||
|
|
||||||
import net.simon987.server.event.GameEvent;
|
import net.simon987.server.event.GameEvent;
|
||||||
import net.simon987.server.event.GameEventDispatcher;
|
import net.simon987.server.event.GameEventDispatcher;
|
||||||
import net.simon987.server.event.TickEvent;
|
import net.simon987.server.event.TickEvent;
|
||||||
@ -21,177 +20,195 @@ import java.util.ArrayList;
|
|||||||
|
|
||||||
public class GameServer implements Runnable {
|
public class GameServer implements Runnable {
|
||||||
|
|
||||||
public final static GameServer INSTANCE = new GameServer();
|
public final static GameServer INSTANCE = new GameServer();
|
||||||
|
|
||||||
private GameUniverse gameUniverse;
|
private GameUniverse gameUniverse;
|
||||||
private GameEventDispatcher eventDispatcher;
|
private GameEventDispatcher eventDispatcher;
|
||||||
private PluginManager pluginManager;
|
private PluginManager pluginManager;
|
||||||
|
|
||||||
private ServerConfiguration config;
|
private ServerConfiguration config;
|
||||||
|
|
||||||
private SocketServer socketServer;
|
private SocketServer socketServer;
|
||||||
|
|
||||||
private int maxExecutionTime;
|
private int maxExecutionTime;
|
||||||
|
|
||||||
public GameServer() {
|
public ArrayList<byte[]> saveArchive;
|
||||||
|
|
||||||
this.config = new ServerConfiguration(new File("config.properties"));
|
public int maxArchiveSize;
|
||||||
|
|
||||||
gameUniverse = new GameUniverse(config);
|
public GameServer() {
|
||||||
pluginManager = new PluginManager();
|
|
||||||
|
|
||||||
maxExecutionTime = config.getInt("user_timeout");
|
this.config = new ServerConfiguration(new File("config.properties"));
|
||||||
|
|
||||||
//Load all plugins in plugins folder, if it doesn't exist, create it
|
gameUniverse = new GameUniverse(config);
|
||||||
File pluginDir = new File("plugins/");
|
pluginManager = new PluginManager();
|
||||||
File[] pluginDirListing = pluginDir.listFiles();
|
|
||||||
|
|
||||||
if (pluginDirListing != null) {
|
maxExecutionTime = config.getInt("user_timeout");
|
||||||
for (File pluginFile : pluginDirListing) {
|
|
||||||
|
|
||||||
if (pluginFile.getName().endsWith(".jar")) {
|
// Load all plugins in plugins folder, if it doesn't exist, create it
|
||||||
pluginManager.load(pluginFile);
|
File pluginDir = new File("plugins/");
|
||||||
}
|
File[] pluginDirListing = pluginDir.listFiles();
|
||||||
|
|
||||||
}
|
if (pluginDirListing != null) {
|
||||||
} else {
|
for (File pluginFile : pluginDirListing) {
|
||||||
if (!pluginDir.mkdir()) {
|
|
||||||
LogManager.LOGGER.severe("Couldn't create plugin directory");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
eventDispatcher = new GameEventDispatcher(pluginManager);
|
if (pluginFile.getName().endsWith(".jar")) {
|
||||||
|
pluginManager.load(pluginFile);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
if (!pluginDir.mkdir()) {
|
||||||
|
LogManager.LOGGER.severe("Couldn't create plugin directory");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public GameUniverse getGameUniverse() {
|
eventDispatcher = new GameEventDispatcher(pluginManager);
|
||||||
return gameUniverse;
|
|
||||||
}
|
|
||||||
|
|
||||||
public GameEventDispatcher getEventDispatcher() {
|
saveArchive = new ArrayList<byte[]>();
|
||||||
return eventDispatcher;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
maxArchiveSize = config.getInt("max_archive_size");
|
||||||
public void run() {
|
}
|
||||||
LogManager.LOGGER.info("(G) Started game loop");
|
|
||||||
|
|
||||||
long startTime; //Start time of the loop
|
public GameUniverse getGameUniverse() {
|
||||||
long uTime; //update time
|
return gameUniverse;
|
||||||
long waitTime; //time to wait
|
}
|
||||||
|
|
||||||
boolean running = true;
|
public GameEventDispatcher getEventDispatcher() {
|
||||||
|
return eventDispatcher;
|
||||||
|
}
|
||||||
|
|
||||||
while (running) {
|
@Override
|
||||||
|
public void run() {
|
||||||
|
LogManager.LOGGER.info("(G) Started game loop");
|
||||||
|
|
||||||
startTime = System.currentTimeMillis();
|
long startTime; // Start time of the loop
|
||||||
|
long uTime; // update time
|
||||||
|
long waitTime; // time to wait
|
||||||
|
|
||||||
tick();
|
boolean running = true;
|
||||||
|
|
||||||
uTime = System.currentTimeMillis() - startTime;
|
while (running) {
|
||||||
waitTime = config.getInt("tick_length") - uTime;
|
|
||||||
|
|
||||||
LogManager.LOGGER.info("Wait time : " + waitTime + "ms | Update time: " + uTime + "ms | " + (int) (((double) uTime / waitTime) * 100) + "% load");
|
startTime = System.currentTimeMillis();
|
||||||
|
|
||||||
try {
|
tick();
|
||||||
if (waitTime >= 0) {
|
|
||||||
Thread.sleep(waitTime);
|
|
||||||
}
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
uTime = System.currentTimeMillis() - startTime;
|
||||||
|
waitTime = config.getInt("tick_length") - uTime;
|
||||||
|
|
||||||
|
LogManager.LOGGER.info("Wait time : " + waitTime + "ms | Update time: " + uTime + "ms | "
|
||||||
|
+ (int) (((double) uTime / waitTime) * 100) + "% load");
|
||||||
|
|
||||||
}
|
try {
|
||||||
|
if (waitTime >= 0) {
|
||||||
|
Thread.sleep(waitTime);
|
||||||
|
}
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
private void tick() {
|
}
|
||||||
gameUniverse.incrementTime();
|
|
||||||
|
|
||||||
//Dispatch tick event
|
}
|
||||||
GameEvent event = new TickEvent(gameUniverse.getTime());
|
|
||||||
GameServer.INSTANCE.getEventDispatcher().dispatch(event); //Ignore cancellation
|
|
||||||
|
|
||||||
|
private void tick() {
|
||||||
|
gameUniverse.incrementTime();
|
||||||
|
|
||||||
//Process user code
|
// Dispatch tick event
|
||||||
ArrayList<User> users_ = gameUniverse.getUsers();
|
GameEvent event = new TickEvent(gameUniverse.getTime());
|
||||||
for (User user : users_) {
|
GameServer.INSTANCE.getEventDispatcher().dispatch(event); // Ignore cancellation
|
||||||
|
|
||||||
if (user.getCpu() != null) {
|
// Process user code
|
||||||
try {
|
ArrayList<User> users_ = gameUniverse.getUsers();
|
||||||
|
for (User user : users_) {
|
||||||
|
|
||||||
int timeout = Math.min(user.getControlledUnit().getEnergy(), maxExecutionTime);
|
if (user.getCpu() != null) {
|
||||||
|
try {
|
||||||
|
|
||||||
user.getCpu().reset();
|
int timeout = Math.min(user.getControlledUnit().getEnergy(), maxExecutionTime);
|
||||||
int cost = user.getCpu().execute(timeout);
|
|
||||||
user.getControlledUnit().spendEnergy(cost);
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
user.getCpu().reset();
|
||||||
LogManager.LOGGER.severe("Error executing " + user.getUsername() + "'s code");
|
int cost = user.getCpu().execute(timeout);
|
||||||
e.printStackTrace();
|
user.getControlledUnit().spendEnergy(cost);
|
||||||
}
|
|
||||||
|
|
||||||
}
|
} catch (Exception e) {
|
||||||
}
|
LogManager.LOGGER.severe("Error executing " + user.getUsername() + "'s code");
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
//Process each worlds
|
}
|
||||||
//Avoid concurrent modification
|
}
|
||||||
ArrayList<World> worlds = new ArrayList<>(gameUniverse.getWorlds());
|
|
||||||
for (World world : worlds) {
|
|
||||||
world.update();
|
|
||||||
}
|
|
||||||
|
|
||||||
//Save
|
// Process each worlds
|
||||||
if (gameUniverse.getTime() % config.getInt("save_interval") == 0) {
|
// Avoid concurrent modification
|
||||||
save(new File("save.json"));
|
ArrayList<World> worlds = new ArrayList<>(gameUniverse.getWorlds());
|
||||||
}
|
for (World world : worlds) {
|
||||||
|
world.update();
|
||||||
|
}
|
||||||
|
|
||||||
socketServer.tick();
|
// Save
|
||||||
|
if (gameUniverse.getTime() % config.getInt("save_interval") == 0) {
|
||||||
|
save(new File("save.json"));
|
||||||
|
}
|
||||||
|
|
||||||
LogManager.LOGGER.info("Processed " + gameUniverse.getWorlds().size() + " worlds");
|
socketServer.tick();
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
LogManager.LOGGER.info("Processed " + gameUniverse.getWorlds().size() + " worlds");
|
||||||
* Save game universe to file in JSON format
|
}
|
||||||
*
|
|
||||||
* @param file JSON file to save
|
|
||||||
*/
|
|
||||||
public void save(File file) {
|
|
||||||
|
|
||||||
try {
|
/**
|
||||||
FileWriter fileWriter = new FileWriter(file);
|
* Save game universe to file in JSON format
|
||||||
|
*
|
||||||
|
* @param file
|
||||||
|
* JSON file to save
|
||||||
|
*/
|
||||||
|
public void save(File file) {
|
||||||
|
|
||||||
JSONObject universe = gameUniverse.serialise();
|
if (new File(new File("save.json").getAbsolutePath()).exists()) {
|
||||||
|
saveArchive.add(ZipUtils.bytifyFile("save.json"));
|
||||||
|
while(saveArchive.size() > maxArchiveSize) {
|
||||||
|
saveArchive.remove(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
JSONArray plugins = new JSONArray();
|
try {
|
||||||
|
FileWriter fileWriter = new FileWriter(file);
|
||||||
|
|
||||||
for (ServerPlugin plugin : pluginManager.getPlugins()) {
|
JSONObject universe = gameUniverse.serialise();
|
||||||
plugins.add(plugin.serialise());
|
|
||||||
}
|
|
||||||
|
|
||||||
universe.put("plugins", plugins);
|
JSONArray plugins = new JSONArray();
|
||||||
|
|
||||||
fileWriter.write(universe.toJSONString());
|
for (ServerPlugin plugin : pluginManager.getPlugins()) {
|
||||||
fileWriter.close();
|
plugins.add(plugin.serialise());
|
||||||
|
}
|
||||||
|
|
||||||
LogManager.LOGGER.info("Saved to file " + file.getName());
|
universe.put("plugins", plugins);
|
||||||
|
|
||||||
} catch (IOException e) {
|
fileWriter.write(universe.toJSONString());
|
||||||
e.printStackTrace();
|
fileWriter.close();
|
||||||
}
|
|
||||||
|
|
||||||
}
|
LogManager.LOGGER.info("Saved to file " + file.getName());
|
||||||
|
|
||||||
public ServerConfiguration getConfig() {
|
} catch (IOException e) {
|
||||||
return config;
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
public PluginManager getPluginManager() {
|
}
|
||||||
return pluginManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSocketServer(SocketServer socketServer) {
|
public ServerConfiguration getConfig() {
|
||||||
this.socketServer = socketServer;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public PluginManager getPluginManager() {
|
||||||
|
return pluginManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSocketServer(SocketServer socketServer) {
|
||||||
|
this.socketServer = socketServer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ArrayList<byte[]> getSaveArchive() {
|
||||||
|
return this.saveArchive;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,12 +4,24 @@ import net.simon987.server.logging.LogManager;
|
|||||||
import net.simon987.server.webserver.SocketServer;
|
import net.simon987.server.webserver.SocketServer;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
|
|
||||||
|
|
||||||
public class Main {
|
public class Main {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
//Writes all of the files stored in GameServer.saveArray to a zip file.
|
||||||
|
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
|
||||||
|
public void run() {
|
||||||
|
try {
|
||||||
|
ZipUtils.writeSavesToZip(GameServer.INSTANCE.getSaveArchive());
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Error writing saves to zip");
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, "Shutdown-thread"));
|
||||||
|
|
||||||
LogManager.initialize();
|
LogManager.initialize();
|
||||||
ServerConfiguration config = new ServerConfiguration(new File("config.properties"));
|
ServerConfiguration config = new ServerConfiguration(new File("config.properties"));
|
||||||
|
91
Server/src/main/java/net/simon987/server/ZipUtils.java
Normal file
91
Server/src/main/java/net/simon987/server/ZipUtils.java
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
package net.simon987.server;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.UnsupportedEncodingException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import java.util.zip.ZipEntry;
|
||||||
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
|
import net.simon987.server.logging.LogManager;
|
||||||
|
|
||||||
|
public class ZipUtils {
|
||||||
|
|
||||||
|
private static final int BUFFER_SIZE = 1024;
|
||||||
|
|
||||||
|
public static byte[] bytifyFile(String fileName) {
|
||||||
|
|
||||||
|
Path path = Paths.get(fileName);
|
||||||
|
byte[] bytes = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
bytes = Files.readAllBytes(path);
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Failed to extract bytes from: " + fileName);
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getByteArrAsString(byte[] bytes) throws UnsupportedEncodingException {
|
||||||
|
return new String(bytes, "UTF-8");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeSavesToZip(ArrayList<byte[]> array) throws IOException {
|
||||||
|
|
||||||
|
int writeCount = 0;
|
||||||
|
FileOutputStream output = new FileOutputStream("archive_" + getDateTimeStamp() + ".zip");
|
||||||
|
ZipOutputStream stream = new ZipOutputStream(output);
|
||||||
|
byte[] buffer = new byte[BUFFER_SIZE];
|
||||||
|
ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
|
||||||
|
|
||||||
|
while ((bais.read(buffer)) > -1) {
|
||||||
|
for (int i = 0; i < array.size(); i++) {
|
||||||
|
|
||||||
|
ZipEntry entry = new ZipEntry("save_" + getTickTime(array.get(i)) + ".json");
|
||||||
|
stream.putNextEntry(entry);
|
||||||
|
stream.write(array.get(i));
|
||||||
|
stream.closeEntry();
|
||||||
|
writeCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stream.close();
|
||||||
|
output.close();
|
||||||
|
|
||||||
|
LogManager.LOGGER.info(writeCount + " saves moved to zip file archive");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String getTickTime(byte[] bytes) throws UnsupportedEncodingException {
|
||||||
|
|
||||||
|
Pattern pattern = Pattern.compile("\"time\"");
|
||||||
|
String stringedBytes = getByteArrAsString(bytes);
|
||||||
|
Matcher matcher = pattern.matcher(stringedBytes);
|
||||||
|
int startIndex = 0;
|
||||||
|
|
||||||
|
while (matcher.find()) {
|
||||||
|
startIndex = matcher.end() + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int endIndex = stringedBytes.indexOf(",", startIndex);
|
||||||
|
|
||||||
|
return stringedBytes.substring(startIndex, endIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String getDateTimeStamp() {
|
||||||
|
Date millisToDate = new Date(System.currentTimeMillis());
|
||||||
|
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmss");
|
||||||
|
return f.format(millisToDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -63,3 +63,6 @@ wg_maxCopperCount=2
|
|||||||
user_timeout=500
|
user_timeout=500
|
||||||
# Free CPU execution time in ms
|
# Free CPU execution time in ms
|
||||||
user_free_execution_time=2
|
user_free_execution_time=2
|
||||||
|
# ----------------------------------------------
|
||||||
|
# Max saves to archive when the server is shutdown
|
||||||
|
max_archive_size=10
|
Loading…
x
Reference in New Issue
Block a user