Compare commits
8
Commits
07dc3f0fad
...
v0.5.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
68f090061f | ||
|
|
be08756c36 | ||
|
|
49af536786 | ||
|
|
9178d36168 | ||
|
|
e61026a3d4 | ||
|
|
99f4f49a7c | ||
|
|
43df96391c | ||
|
|
607d5b2b32 |
No files matched your search
@@ -38,26 +38,28 @@ podman run -d --name zomboidforge \
|
||||
|
||||
Unset variables keep the value in the server `.ini` (or the game default).
|
||||
|
||||
| Variable | Default | |
|
||||
|----------------------|--------------------------|-----------------------------------------------------------------------------------------------------|
|
||||
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
|
||||
| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
|
||||
| `PUBLIC` | | `true`/`false`: listed in the in-game server browser |
|
||||
| `PUBLIC_NAME` | | Name in the server browser |
|
||||
| `PORT` | `16261` | Game port (`-port`) |
|
||||
| `UDP_PORT` | `16262` | Direct connection port (`-udpport`) |
|
||||
| `UPNP` | | `true`/`false`: UPnP port mapping on the router (`.ini` `UPnP`); `false` recommended (see below) |
|
||||
| `ADMIN_USERNAME` | `admin` | First start only |
|
||||
| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards |
|
||||
| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` |
|
||||
| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` |
|
||||
| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` |
|
||||
| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it |
|
||||
| `JVM_MIN_HEAP` | JVM default | `-Xms`; unused heap memory is returned to the system only down to this size |
|
||||
| `JVM_MAX_HEAP` | 75 % of the memory limit | `-Xmx`; `8g` when the container has no memory limit |
|
||||
| `JVM_UNCOMMIT_DELAY` | `60` | Seconds after which unused heap memory is returned to the system (`-XX:ZUncommitDelay`) |
|
||||
| `STEAM` | `1` | `0` runs the server without Steam |
|
||||
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
|
||||
| Variable | Default | |
|
||||
|--------------------------------|--------------------------|-----------------------------------------------------------------------------------------------------------------------------|
|
||||
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
|
||||
| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
|
||||
| `PUBLIC` | | `true`/`false`: listed in the in-game server browser |
|
||||
| `PUBLIC_NAME` | | Name in the server browser |
|
||||
| `PORT` | `16261` | Game port (`-port`) |
|
||||
| `UDP_PORT` | `16262` | Direct connection port (`-udpport`) |
|
||||
| `UPNP` | | `true`/`false`: UPnP port mapping on the router (`.ini` `UPnP`); `false` recommended (see below) |
|
||||
| `ADMIN_USERNAME` | `admin` | First start only |
|
||||
| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards |
|
||||
| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` |
|
||||
| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` |
|
||||
| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` |
|
||||
| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it |
|
||||
| `JVM_MIN_HEAP` | JVM default | `-Xms`; unused heap memory is returned to the system only down to this size |
|
||||
| `JVM_MAX_HEAP` | 75 % of the memory limit | `-Xmx`; `8g` when the container has no memory limit |
|
||||
| `JVM_UNCOMMIT_DELAY` | `60` | Seconds after which unused heap memory is returned to the system (`-XX:ZUncommitDelay`) |
|
||||
| `JVM_EXPERIMENTAL_PERFORMANCE` | `false` | `true`/`false`: `-XX:+UseCompactObjectHeaders` and `-XX:+UseTransparentHugePages` (see below) |
|
||||
| `STEAM` | `1` | `0` runs the server without Steam |
|
||||
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
|
||||
| `ZF_EXPERIMENTAL_PERFORMANCE` | `false` | `true`/`false`: performance changes that alter timing or resource use (more threads, shorter waits); overrides `forge.toml` |
|
||||
|
||||
Notes:
|
||||
|
||||
@@ -75,6 +77,9 @@ Notes:
|
||||
rest stays for native memory. The startup briefly needs a large heap; with 8 players
|
||||
exploring, the heap held up to 4.4 GB of live data in tests. A limit below about 6 GB is
|
||||
not recommended. Without a limit the heap is `8g`, as in vanilla.
|
||||
- **Huge pages:** `JVM_EXPERIMENTAL_PERFORMANCE=true` maps the heap with transparent huge pages
|
||||
only when the host's `/sys/kernel/mm/transparent_hugepage/shmem_enabled` is `advise` or
|
||||
`always` (a container cannot change it); otherwise the JVM logs a warning and runs without them.
|
||||
- **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large worlds.
|
||||
|
||||
For local testing use `compose.yaml` (`podman compose up --build`, settings from `.env`).
|
||||
@@ -130,6 +135,9 @@ budget_ms = 2 # time per tick for tasks that mods hand to the main thread
|
||||
|
||||
[shutdown]
|
||||
timeout_s = 10 # time the mods' threads get to finish when the server stops
|
||||
|
||||
[features]
|
||||
experimental_performance = false # default false; ZF_EXPERIMENTAL_PERFORMANCE takes precedence when set
|
||||
```
|
||||
|
||||
### Mod development
|
||||
|
||||
+3
-1
@@ -38,7 +38,9 @@ public final class B42PatchSet implements PatchSet
|
||||
new ZipBackupWaitPerformancePatch(),
|
||||
new ServerPlayersVehiclesRoundPerformancePatch(),
|
||||
new ServerPlayersVehiclesStopPerformancePatch(),
|
||||
new ServerPlayerDBSaveWaitPerformancePatch()
|
||||
new ServerPlayerDBSaveWaitPerformancePatch(),
|
||||
new GameServerAssetLoadingPerformancePatch(),
|
||||
new ServerMapQuitSleepPerformancePatch()
|
||||
);
|
||||
|
||||
@Override
|
||||
|
||||
+6
-1
@@ -13,7 +13,12 @@ import java.util.List;
|
||||
*
|
||||
* <pre>{@code
|
||||
* if (!ClientCommandHooks.onClientCommand(module, command, player, tbl))
|
||||
* LuaEventManager.triggerEvent("OnClientCommand", module, command, player, tbl);
|
||||
* {
|
||||
* LuaEventManager.triggerEvent(
|
||||
* "OnClientCommand", module,
|
||||
* command, player, tbl
|
||||
* );
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* The arguments are the method's local variables of these names.
|
||||
|
||||
-1
@@ -15,7 +15,6 @@ import java.util.List;
|
||||
*/
|
||||
public final class CommandListPatch extends ReturnHookPatch
|
||||
{
|
||||
/** The whole method: {@code getstatic childrenClasses}, {@code areturn}. */
|
||||
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
|
||||
new Anchor.Method("getSubClasses", "()[Ljava/lang/Class;"),
|
||||
new Anchor.Instruction.Opcode(Opcodes.GETSTATIC),
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
/**
|
||||
* Replaces the update call of the asset loop in {@code GameServer.doMinimumInit}:
|
||||
*
|
||||
* <pre>{@code
|
||||
* while (GameWindow.fileSystem.hasWork()) {
|
||||
* // GameWindow.fileSystem.updateAsyncTransactions()
|
||||
* AssetLoadingHooks.updateAsyncTransactions(GameWindow.fileSystem);
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* With the feature {@code experimental_performance} the hook grows the loader pool to one thread
|
||||
* per CPU but one and parks the main thread between updates instead of spinning. The
|
||||
* per-frame call in {@code GameServer.main} stays.
|
||||
*/
|
||||
public final class GameServerAssetLoadingPerformancePatch extends PerformancePatch
|
||||
{
|
||||
private static final String FILE_SYSTEM = "zombie/fileSystem/FileSystem";
|
||||
|
||||
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||
new Anchor.Method("doMinimumInit", "()V"),
|
||||
GameServerAssetLoadingPerformancePatch.FILE_SYSTEM, "updateAsyncTransactions", "()V"
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(
|
||||
"dev/overlord/zomboidforge/compat/b42/hooks/AssetLoadingHooks", "updateAsyncTransactions", "(L" + GameServerAssetLoadingPerformancePatch.FILE_SYSTEM + ";)V"
|
||||
);
|
||||
|
||||
public GameServerAssetLoadingPerformancePatch() {
|
||||
super("zombie/network/GameServer", GameServerAssetLoadingPerformancePatch.ANCHOR, GameServerAssetLoadingPerformancePatch.HOOK);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
|
||||
|
||||
@Override
|
||||
public void apply(ClassNode node)
|
||||
{
|
||||
MethodNode method = GameServerAssetLoadingPerformancePatch.ANCHOR.in().resolve(node);
|
||||
MethodInsnNode update = GameServerAssetLoadingPerformancePatch.ANCHOR.resolve(node);
|
||||
|
||||
if (update.getOpcode() != Opcodes.INVOKEVIRTUAL)
|
||||
throw new IllegalStateException("'" + node.name + ".doMinimumInit': 'FileSystem.updateAsyncTransactions' is not called virtually.");
|
||||
|
||||
// The hook takes the receiver of the virtual call as its argument: the stack is unchanged.
|
||||
method.instructions.set(update, new MethodInsnNode(Opcodes.INVOKESTATIC, GameServerAssetLoadingPerformancePatch.HOOK.owner(),
|
||||
GameServerAssetLoadingPerformancePatch.HOOK.name(), GameServerAssetLoadingPerformancePatch.HOOK.desc(), false));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -18,7 +18,7 @@ import java.util.List;
|
||||
*
|
||||
* <pre>{@code
|
||||
* File testDir = ChunkMapFilenames.instance.getDir(Core.gameSaveWorld);
|
||||
* if (!testDir.exists()) { // removed
|
||||
* if (!testDir.exists()) { // removed
|
||||
* testDir.mkdir();
|
||||
* }
|
||||
* }</pre>
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.patches.ThreadSleepPerformancePatch;
|
||||
|
||||
/**
|
||||
* {@code ServerMap.QueuedQuit()} sleeps 5 s after the world save and the {@code ServerQuit}
|
||||
* broadcast, so the clients can disconnect. The sleep becomes {@code QuitHooks.quitSleep}. With
|
||||
* the feature {@code experimental_performance} enabled, the shutdown continues as soon as no
|
||||
* client is connected, after at most 5s. With the feature disabled, it keeps the vanilla sleep.
|
||||
*/
|
||||
public final class ServerMapQuitSleepPerformancePatch extends ThreadSleepPerformancePatch
|
||||
{
|
||||
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/QuitHooks", "quitSleep", "(J)V");
|
||||
|
||||
public ServerMapQuitSleepPerformancePatch() {
|
||||
super("zombie/network/ServerMap", new Anchor.Method("QueuedQuit", "()V"), 1, ServerMapQuitSleepPerformancePatch.HOOK);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.Label;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||
import static org.objectweb.asm.Opcodes.GETSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.GOTO;
|
||||
import static org.objectweb.asm.Opcodes.IFEQ;
|
||||
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
class GameServerAssetLoadingPerformancePatchTest
|
||||
{
|
||||
private static final String GAME_SERVER = "zombie/network/GameServer";
|
||||
private static final String FILE_SYSTEM = "zombie/fileSystem/FileSystem";
|
||||
|
||||
/**
|
||||
* {@code GameServer} with the loop of {@code doMinimumInit} and the per-frame call of
|
||||
* {@code main}: {@code while (GameWindow.fileSystem.hasWork()) GameWindow.fileSystem.updateAsyncTransactions();}
|
||||
* and {@code GameWindow.fileSystem.updateAsyncTransactions();}.
|
||||
*/
|
||||
private static ClassNode gameServer()
|
||||
{
|
||||
ClassNode node = new ClassNode();
|
||||
node.visit(V25, ACC_PUBLIC, GameServerAssetLoadingPerformancePatchTest.GAME_SERVER, null, "java/lang/Object", null);
|
||||
|
||||
MethodVisitor init = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "doMinimumInit", "()V", null, null);
|
||||
Label check = new Label();
|
||||
Label end = new Label();
|
||||
init.visitLabel(check);
|
||||
init.visitFieldInsn(GETSTATIC, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
|
||||
init.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "hasWork", "()Z", false);
|
||||
init.visitJumpInsn(IFEQ, end);
|
||||
init.visitFieldInsn(GETSTATIC, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
|
||||
init.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "updateAsyncTransactions", "()V", false);
|
||||
init.visitJumpInsn(GOTO, check);
|
||||
init.visitLabel(end);
|
||||
init.visitInsn(RETURN);
|
||||
init.visitMaxs(0, 0);
|
||||
|
||||
MethodVisitor main = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
|
||||
main.visitFieldInsn(GETSTATIC, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
|
||||
main.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "updateAsyncTransactions", "()V", false);
|
||||
main.visitInsn(RETURN);
|
||||
main.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private static List<String> calls(ClassNode node, String name)
|
||||
{
|
||||
MethodNode method = node.methods.stream().filter(candidate -> candidate.name.equals(name)).findFirst().orElseThrow();
|
||||
List<String> calls = new ArrayList<>();
|
||||
|
||||
for (AbstractInsnNode instruction : method.instructions) {
|
||||
if (instruction instanceof MethodInsnNode call) calls.add(call.owner.substring(call.owner.lastIndexOf('/') + 1) + "." + call.name + call.desc);
|
||||
}
|
||||
|
||||
return calls;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorMatchesTheTarget()
|
||||
{
|
||||
new GameServerAssetLoadingPerformancePatch().anchor().verify(GameServerAssetLoadingPerformancePatchTest.gameServer());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacesTheUpdateInTheStartupLoopOnly()
|
||||
{
|
||||
ClassNode node = GameServerAssetLoadingPerformancePatchTest.gameServer();
|
||||
new GameServerAssetLoadingPerformancePatch().apply(node);
|
||||
|
||||
assertEquals(
|
||||
List.of("FileSystem.hasWork()Z", "AssetLoadingHooks.updateAsyncTransactions(Lzombie/fileSystem/FileSystem;)V"),
|
||||
GameServerAssetLoadingPerformancePatchTest.calls(node, "doMinimumInit")
|
||||
);
|
||||
assertEquals(List.of("FileSystem.updateAsyncTransactions()V"), GameServerAssetLoadingPerformancePatchTest.calls(node, "main"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void patchedClassIsValid() throws ClassNotFoundException
|
||||
{
|
||||
ClassNode node = GameServerAssetLoadingPerformancePatchTest.gameServer();
|
||||
new GameServerAssetLoadingPerformancePatch().apply(node);
|
||||
|
||||
// Initializing links the class, which runs the bytecode verifier on the changed loop.
|
||||
ClassDefiner definer = new ClassDefiner();
|
||||
definer.define(node);
|
||||
Class.forName(node.name.replace('/', '.'), true, definer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void appliesOnlyToVerifiedVersions()
|
||||
{
|
||||
GameServerAssetLoadingPerformancePatch patch = new GameServerAssetLoadingPerformancePatch();
|
||||
|
||||
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
|
||||
assertTrue(patch.appliesTo(GameVersion.parse("42.21.3")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
|
||||
}
|
||||
}
|
||||
+11
-10
@@ -26,13 +26,13 @@ import static org.objectweb.asm.Opcodes.LCONST_1;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
/** The five Build 42 waiting-loop patches: each with its target, number of sleeps and hook. */
|
||||
/** The Build 42 patches that redirect {@code Thread.sleep}: each with its target, number of sleeps and hook. */
|
||||
class ThreadSleepPatchesTest
|
||||
{
|
||||
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks";
|
||||
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/";
|
||||
|
||||
/** Each patch with its target method, number of sleeps and hook. */
|
||||
private record Case(ThreadSleepPerformancePatch patch, String target, String method, int sleeps, String hook)
|
||||
/** Each patch with its target method, number of sleeps, hook class and hook. */
|
||||
private record Case(ThreadSleepPerformancePatch patch, String target, String method, int sleeps, String hooks, String hook)
|
||||
{
|
||||
@Override
|
||||
public @NonNull String toString() { return this.patch.getClass().getSimpleName(); }
|
||||
@@ -41,11 +41,12 @@ class ThreadSleepPatchesTest
|
||||
private static Stream<Case> cases()
|
||||
{
|
||||
return Stream.of(
|
||||
new Case(new ServerChunkLoaderQuitPerformancePatch(), "zombie/network/ServerChunkLoader", "quit", 2, "pollSleep"),
|
||||
new Case(new ZipBackupWaitPerformancePatch(), "zombie/core/backup/ZipBackup", "waitFinish", 1, "pollSleep"),
|
||||
new Case(new ServerPlayersVehiclesRoundPerformancePatch(), "zombie/network/ServerPlayersVehicles$SPVThread", "runInner", 1, "vehicleRoundSleep"),
|
||||
new Case(new ServerPlayersVehiclesStopPerformancePatch(), "zombie/network/ServerPlayersVehicles", "stop", 1, "wakeVehiclesAndPoll"),
|
||||
new Case(new ServerPlayerDBSaveWaitPerformancePatch(), "zombie/savefile/ServerPlayerDB", "saveFinishWait", 1, "wakeVehiclesAndPoll")
|
||||
new Case(new ServerChunkLoaderQuitPerformancePatch(), "zombie/network/ServerChunkLoader", "quit", 2, "WaitHooks", "pollSleep"),
|
||||
new Case(new ZipBackupWaitPerformancePatch(), "zombie/core/backup/ZipBackup", "waitFinish", 1, "WaitHooks", "pollSleep"),
|
||||
new Case(new ServerPlayersVehiclesRoundPerformancePatch(), "zombie/network/ServerPlayersVehicles$SPVThread", "runInner", 1, "WaitHooks", "vehicleRoundSleep"),
|
||||
new Case(new ServerPlayersVehiclesStopPerformancePatch(), "zombie/network/ServerPlayersVehicles", "stop", 1, "WaitHooks", "wakeVehiclesAndPoll"),
|
||||
new Case(new ServerPlayerDBSaveWaitPerformancePatch(), "zombie/savefile/ServerPlayerDB", "saveFinishWait", 1, "WaitHooks", "wakeVehiclesAndPoll"),
|
||||
new Case(new ServerMapQuitSleepPerformancePatch(), "zombie/network/ServerMap", "QueuedQuit", 1, "QuitHooks", "quitSleep")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -97,7 +98,7 @@ class ThreadSleepPatchesTest
|
||||
for (MethodInsnNode call : calls)
|
||||
{
|
||||
assertEquals(INVOKESTATIC, call.getOpcode());
|
||||
assertEquals(ThreadSleepPatchesTest.HOOKS, call.owner);
|
||||
assertEquals(ThreadSleepPatchesTest.HOOKS + test.hooks(), call.owner);
|
||||
assertEquals(test.hook(), call.name);
|
||||
assertEquals("(J)V", call.desc);
|
||||
}
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.core.config.Feature;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
import zombie.fileSystem.FileSystem;
|
||||
import zombie.fileSystem.FileSystemImpl;
|
||||
|
||||
/**
|
||||
* Hooks for the asset loading at startup ({@link Feature#EXPERIMENTAL_PERFORMANCE}): the loop
|
||||
* in {@code GameServer.doMinimumInit}
|
||||
*
|
||||
* <pre>{@code
|
||||
* while (GameWindow.fileSystem.hasWork()) GameWindow.fileSystem.updateAsyncTransactions();
|
||||
* }</pre>
|
||||
*
|
||||
* hands file tasks (model and animation imports, 16 at most in flight) to the loader threads of
|
||||
* {@code FileSystemImpl} and collects their results on the main thread. It spins: the main
|
||||
* thread takes a CPU that the loaders could use. Vanilla has 2 loader threads with up to 4
|
||||
* CPUs, 4 with more.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public final class AssetLoadingHooks
|
||||
{
|
||||
/** Pause of the main thread after each update; one task takes about 8 ms of loader time. */
|
||||
private static final long PARK_NANOS = 500_000L;
|
||||
|
||||
/** {@code FileSystemImpl.executor}, private; {@code null} when it cannot be reached. */
|
||||
private static final @Nullable VarHandle EXECUTOR;
|
||||
|
||||
static
|
||||
{
|
||||
VarHandle executor = null;
|
||||
try
|
||||
{
|
||||
executor = MethodHandles.privateLookupIn(FileSystemImpl.class, MethodHandles.lookup())
|
||||
.findVarHandle(FileSystemImpl.class, "executor", ExecutorService.class);
|
||||
}
|
||||
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Unable to register hook 'AssetLoadingHooks.updateAsyncTransactions': 'FileSystemImpl.executor' not found: " + e); }
|
||||
|
||||
EXECUTOR = executor;
|
||||
}
|
||||
|
||||
/** Whether the loader pool was checked; the main thread is the only caller. */
|
||||
private static boolean poolChecked;
|
||||
|
||||
private AssetLoadingHooks() {}
|
||||
|
||||
/**
|
||||
* Replaces {@code fileSystem.updateAsyncTransactions()} in that loop. With the feature off,
|
||||
* only that call. On: the first call grows the loader pool to one thread per CPU but one (at
|
||||
* least 2), and every call parks the main thread for 0.5 ms after the update instead of
|
||||
* spinning. Fewer threads with a spinning main thread, or more threads alone, load slower.
|
||||
* The pool keeps its size after startup; the loaders run the same tasks as in vanilla.
|
||||
*/
|
||||
public static void updateAsyncTransactions(FileSystem fileSystem)
|
||||
{
|
||||
if (!ForgeInstance.FORGE.settings().enabled(Feature.EXPERIMENTAL_PERFORMANCE))
|
||||
{
|
||||
fileSystem.updateAsyncTransactions();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!AssetLoadingHooks.poolChecked)
|
||||
{
|
||||
AssetLoadingHooks.poolChecked = true;
|
||||
|
||||
Object executor = AssetLoadingHooks.EXECUTOR != null && fileSystem instanceof FileSystemImpl ? AssetLoadingHooks.EXECUTOR.get(fileSystem) : null;
|
||||
int threads = Math.max(2, Runtime.getRuntime().availableProcessors() - 1);
|
||||
|
||||
// A fixed pool: maximum first, the core size may not exceed it.
|
||||
if (executor instanceof ThreadPoolExecutor pool && pool.getMaximumPoolSize() < threads)
|
||||
{
|
||||
System.out.println("[ZomboidForge] Loader threads: " + pool.getMaximumPoolSize() + " -> " + threads + ".");
|
||||
pool.setMaximumPoolSize(threads);
|
||||
pool.setCorePoolSize(threads);
|
||||
}
|
||||
}
|
||||
|
||||
fileSystem.updateAsyncTransactions();
|
||||
LockSupport.parkNanos(AssetLoadingHooks.PARK_NANOS);
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.core.config.Feature;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.util.Map;
|
||||
|
||||
import zombie.core.raknet.UdpEngine;
|
||||
import zombie.network.GameServer;
|
||||
|
||||
/**
|
||||
* Hooks for the shutdown sleep in {@code ServerMap.QueuedQuit} ({@link Feature#EXPERIMENTAL_PERFORMANCE}).
|
||||
* After the world save, vanilla broadcasts {@code ServerQuit} and sleeps 5 s, so the clients
|
||||
* receive it and disconnect, then closes the databases and the network.
|
||||
*
|
||||
* <p>The connections are those of {@code UdpEngine.connectionMap}: the network thread
|
||||
* ({@code UdpEngine}) removes a connection from it as soon as RakNet reports the disconnect
|
||||
* notification or the lost connection. {@code GameServer.udpEngine.connections} is updated only
|
||||
* by the main thread, which is in {@code QueuedQuit} at this point.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public final class QuitHooks
|
||||
{
|
||||
private static final long POLL_MILLIS = 10L;
|
||||
|
||||
/** {@code UdpEngine.connectionMap}, private; {@code null} when it cannot be reached. */
|
||||
private static final @Nullable VarHandle CONNECTIONS;
|
||||
|
||||
static
|
||||
{
|
||||
VarHandle connections = null;
|
||||
try
|
||||
{
|
||||
connections = MethodHandles.privateLookupIn(UdpEngine.class, MethodHandles.lookup())
|
||||
.findVarHandle(UdpEngine.class, "connectionMap", Map.class);
|
||||
}
|
||||
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Unable to register hook 'QuitHooks.quitSleep': 'UdpEngine.connectionMap' not found: " + e); }
|
||||
|
||||
CONNECTIONS = connections;
|
||||
}
|
||||
|
||||
private QuitHooks() {}
|
||||
|
||||
/**
|
||||
* Replaces {@code Thread.sleep(5000L)} in {@code QueuedQuit}. Sleeps {@code millis} when the
|
||||
* feature is off, {@code connectionMap} is unreachable, or there is no {@code udpEngine};
|
||||
* otherwise returns once no client is connected, polling every 10 ms, after at most
|
||||
* {@code millis}.
|
||||
*/
|
||||
@SuppressWarnings("BusyWait")
|
||||
public static void quitSleep(long millis) throws InterruptedException
|
||||
{
|
||||
UdpEngine engine = GameServer.udpEngine;
|
||||
|
||||
if (!ForgeInstance.FORGE.settings().enabled(Feature.EXPERIMENTAL_PERFORMANCE) || QuitHooks.CONNECTIONS == null || engine == null)
|
||||
{
|
||||
Thread.sleep(millis);
|
||||
return;
|
||||
}
|
||||
|
||||
long deadline = System.nanoTime() + millis * 1_000_000L;
|
||||
|
||||
while (true)
|
||||
{
|
||||
// The network thread writes the map without synchronisation.
|
||||
VarHandle.acquireFence();
|
||||
int connected = ((Map<?, ?>) QuitHooks.CONNECTIONS.get(engine)).size();
|
||||
|
||||
long now = System.nanoTime();
|
||||
if (connected == 0 || now >= deadline) return;
|
||||
|
||||
Thread.sleep(Math.min(QuitHooks.POLL_MILLIS, (deadline - now) / 1_000_000L + 1L));
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -33,7 +33,7 @@ public final class RolesHooks
|
||||
connection = MethodHandles.privateLookupIn(ServerWorldDatabase.class, MethodHandles.lookup())
|
||||
.findVarHandle(ServerWorldDatabase.class, "conn", Connection.class);
|
||||
}
|
||||
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Roles are saved without a transaction: 'ServerWorldDatabase.conn' not found: " + e); }
|
||||
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Unable to register hook 'RolesHooks.beginSave': 'ServerWorldDatabase.conn' not found: " + e); }
|
||||
|
||||
CONNECTION = connection;
|
||||
}
|
||||
@@ -58,7 +58,7 @@ public final class RolesHooks
|
||||
connection.setAutoCommit(false);
|
||||
RolesHooks.transaction = connection;
|
||||
}
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Roles are saved without a transaction: " + e); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Unable to begin the roles transaction: " + e); }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -72,11 +72,11 @@ public final class RolesHooks
|
||||
if (connection == null) return;
|
||||
|
||||
try { connection.commit(); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Committing the saved roles failed: " + e); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Unable to commit the roles transaction: " + e); }
|
||||
finally
|
||||
{
|
||||
try { connection.setAutoCommit(true); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Switching the database back to autocommit failed: " + e); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Unable to restore autocommit: " + e); }
|
||||
}
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.core.Forge;
|
||||
import dev.overlord.zomboidforge.core.config.Feature;
|
||||
import dev.overlord.zomboidforge.core.config.ForgeSettings;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import zombie.fileSystem.FileSystemImpl;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.time.Duration;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/** The hook on a real {@code FileSystemImpl}; the feature is switched through the settings of {@code ForgeInstance.FORGE}. */
|
||||
class AssetLoadingHooksTest
|
||||
{
|
||||
private static void settings(ForgeSettings settings) throws ReflectiveOperationException
|
||||
{
|
||||
Field field = Forge.class.getDeclaredField("settings");
|
||||
field.setAccessible(true);
|
||||
field.set(ForgeInstance.FORGE, settings);
|
||||
}
|
||||
|
||||
private static ThreadPoolExecutor pool(FileSystemImpl fileSystem) throws ReflectiveOperationException
|
||||
{
|
||||
Field field = FileSystemImpl.class.getDeclaredField("executor");
|
||||
field.setAccessible(true);
|
||||
return (ThreadPoolExecutor) field.get(fileSystem);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void resetSettings() throws ReflectiveOperationException
|
||||
{
|
||||
AssetLoadingHooksTest.settings(ForgeSettings.DEFAULTS);
|
||||
}
|
||||
|
||||
/** One test: the first call with the feature on grows the pool once per JVM. */
|
||||
@Test
|
||||
void growsTheLoaderPoolOnlyWithTheFeature() throws ReflectiveOperationException
|
||||
{
|
||||
FileSystemImpl fileSystem = new FileSystemImpl();
|
||||
ThreadPoolExecutor pool = AssetLoadingHooksTest.pool(fileSystem);
|
||||
int vanilla = Runtime.getRuntime().availableProcessors() <= 4 ? 2 : 4;
|
||||
int expected = Math.max(vanilla, Math.max(2, Runtime.getRuntime().availableProcessors() - 1));
|
||||
|
||||
try
|
||||
{
|
||||
assertEquals(vanilla, pool.getMaximumPoolSize());
|
||||
|
||||
AssetLoadingHooks.updateAsyncTransactions(fileSystem);
|
||||
assertEquals(vanilla, pool.getCorePoolSize());
|
||||
assertEquals(vanilla, pool.getMaximumPoolSize());
|
||||
|
||||
AssetLoadingHooksTest.settings(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of(Feature.EXPERIMENTAL_PERFORMANCE)));
|
||||
AssetLoadingHooks.updateAsyncTransactions(fileSystem);
|
||||
AssetLoadingHooks.updateAsyncTransactions(fileSystem);
|
||||
assertEquals(expected, pool.getCorePoolSize());
|
||||
assertEquals(expected, pool.getMaximumPoolSize());
|
||||
}
|
||||
finally { pool.shutdownNow(); }
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||
import dev.overlord.zomboidforge.core.Forge;
|
||||
import dev.overlord.zomboidforge.core.config.Feature;
|
||||
import dev.overlord.zomboidforge.core.config.ForgeSettings;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import zombie.core.raknet.UdpEngine;
|
||||
import zombie.network.GameServer;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The paths without a network engine; the wait for disconnects is checked on a running server. */
|
||||
class QuitHooksTest
|
||||
{
|
||||
private static final long MILLIS = 50L;
|
||||
|
||||
private static void settings(ForgeSettings settings) throws ReflectiveOperationException
|
||||
{
|
||||
Field field = Forge.class.getDeclaredField("settings");
|
||||
field.setAccessible(true);
|
||||
field.set(ForgeInstance.FORGE, settings);
|
||||
}
|
||||
|
||||
private static long sleptMillis() throws InterruptedException
|
||||
{
|
||||
long start = System.nanoTime();
|
||||
QuitHooks.quitSleep(QuitHooksTest.MILLIS);
|
||||
return (System.nanoTime() - start) / 1_000_000L;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void resetSettings() throws ReflectiveOperationException
|
||||
{
|
||||
QuitHooksTest.settings(ForgeSettings.DEFAULTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sleepsTheFullTimeWithoutTheFeature() throws InterruptedException
|
||||
{
|
||||
assertTrue(QuitHooksTest.sleptMillis() >= QuitHooksTest.MILLIS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sleepsTheFullTimeWithoutANetworkEngine() throws Exception
|
||||
{
|
||||
assertNull(GameServer.udpEngine);
|
||||
QuitHooksTest.settings(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of(Feature.EXPERIMENTAL_PERFORMANCE)));
|
||||
|
||||
assertTrue(QuitHooksTest.sleptMillis() >= QuitHooksTest.MILLIS);
|
||||
}
|
||||
|
||||
/** The hook reads this field; without it the shutdown keeps the vanilla sleep. */
|
||||
@Test
|
||||
void connectionMapExistsInTheGame() throws NoSuchFieldException
|
||||
{
|
||||
assertEquals(Map.class, UdpEngine.class.getDeclaredField("connectionMap").getType());
|
||||
}
|
||||
}
|
||||
+18
-16
@@ -6,22 +6,24 @@ services:
|
||||
image: localhost/zomboidforge:dev
|
||||
platform: linux/amd64
|
||||
environment:
|
||||
SERVER_NAME: ${SERVER_NAME:-zomboidforgetest}
|
||||
SERVER_PASSWORD: ${SERVER_PASSWORD:-}
|
||||
PUBLIC: ${PUBLIC:-}
|
||||
PUBLIC_NAME: ${PUBLIC_NAME:-}
|
||||
PORT: ${PORT:-16261}
|
||||
UDP_PORT: ${UDP_PORT:-16262}
|
||||
ADMIN_USERNAME: ${ADMIN_USERNAME:-}
|
||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
||||
SERVER_PRESET: ${SERVER_PRESET:-}
|
||||
MODS: ${MODS:-}
|
||||
WORKSHOP_ITEMS: ${WORKSHOP_ITEMS:-}
|
||||
RCON_PASSWORD: ${RCON_PASSWORD:-}
|
||||
UPNP: ${UPNP:-}
|
||||
JVM_MIN_HEAP: ${JVM_MIN_HEAP:-}
|
||||
JVM_MAX_HEAP: ${JVM_MAX_HEAP:-}
|
||||
JVM_UNCOMMIT_DELAY: ${JVM_UNCOMMIT_DELAY:-}
|
||||
SERVER_NAME: ${SERVER_NAME:-zomboidforgetest}
|
||||
SERVER_PASSWORD: ${SERVER_PASSWORD:-}
|
||||
PUBLIC: ${PUBLIC:-}
|
||||
PUBLIC_NAME: ${PUBLIC_NAME:-}
|
||||
PORT: ${PORT:-16261}
|
||||
UDP_PORT: ${UDP_PORT:-16262}
|
||||
ADMIN_USERNAME: ${ADMIN_USERNAME:-}
|
||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
||||
SERVER_PRESET: ${SERVER_PRESET:-}
|
||||
MODS: ${MODS:-}
|
||||
WORKSHOP_ITEMS: ${WORKSHOP_ITEMS:-}
|
||||
RCON_PASSWORD: ${RCON_PASSWORD:-}
|
||||
UPNP: ${UPNP:-}
|
||||
JVM_MIN_HEAP: ${JVM_MIN_HEAP:-}
|
||||
JVM_MAX_HEAP: ${JVM_MAX_HEAP:-}
|
||||
JVM_UNCOMMIT_DELAY: ${JVM_UNCOMMIT_DELAY:-}
|
||||
JVM_EXPERIMENTAL_PERFORMANCE: ${JVM_EXPERIMENTAL_PERFORMANCE:-}
|
||||
ZF_EXPERIMENTAL_PERFORMANCE: ${ZF_EXPERIMENTAL_PERFORMANCE:-}
|
||||
ports:
|
||||
# Host and container ports must be equal: the server reports its own port
|
||||
# to Steam and to clients, so a remapped port is unreachable.
|
||||
|
||||
@@ -10,6 +10,7 @@ import dev.overlord.zomboidforge.api.storage.StorageException;
|
||||
import dev.overlord.zomboidforge.core.commands.ClientCommandSender;
|
||||
import dev.overlord.zomboidforge.core.commands.CommandRegistry;
|
||||
import dev.overlord.zomboidforge.core.commands.ModClientCommands;
|
||||
import dev.overlord.zomboidforge.core.config.Feature;
|
||||
import dev.overlord.zomboidforge.core.config.ForgeSettings;
|
||||
import dev.overlord.zomboidforge.core.mods.GameClasses;
|
||||
import dev.overlord.zomboidforge.core.mods.ModDiscovery;
|
||||
@@ -100,6 +101,9 @@ public final class Forge
|
||||
|
||||
public Lifecycle.Phase phase() { return this.lifecycle.phase(); }
|
||||
|
||||
/** The settings from {@code forge.toml} and the system properties; {@link ForgeSettings#DEFAULTS} until {@link #load} reads them. */
|
||||
public ForgeSettings settings() { return this.settings; }
|
||||
|
||||
public List<ModLoader.LoadedMod> mods() { return this.mods; }
|
||||
|
||||
/** The admin command classes that mods registered, in registration order. */
|
||||
@@ -119,8 +123,14 @@ public final class Forge
|
||||
{
|
||||
Path modsDirectory = this.directory.resolve(Forge.MODS);
|
||||
|
||||
try { this.settings = ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)); }
|
||||
catch (IllegalArgumentException e) { throw new ModLoadException("'" + ForgeSettings.FILE + "': " + e.getMessage(), e); }
|
||||
try { this.settings = ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), System.getProperties()); }
|
||||
catch (IllegalArgumentException e) { throw new ModLoadException("'" + ForgeSettings.FILE + "' or system properties: " + e.getMessage(), e); }
|
||||
|
||||
if (!this.settings.features().isEmpty())
|
||||
{
|
||||
String features = this.settings.features().stream().sorted().map(Feature::key).collect(Collectors.joining(", "));
|
||||
this.logger.log(System.Logger.Level.INFO, "Features on: " + features + ".");
|
||||
}
|
||||
|
||||
this.queue.budget(this.settings.mainThreadBudget());
|
||||
this.queue.bindToCurrentThread();
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Optional behavior of ZomboidForge, off by default. Each feature has one key, from which its
|
||||
* switches follow:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code features.<key> = true|false} in {@code forge.toml};</li>
|
||||
* <li>the system property {@code zomboidforge.features.<key>=true|false}, which takes
|
||||
* precedence; the container entrypoint sets it from the environment variable
|
||||
* {@code ZF_<KEY>}.</li>
|
||||
* </ul>
|
||||
*
|
||||
* Code that a feature switches reads it through {@link ForgeSettings#enabled(Feature)} of the
|
||||
* running {@code Forge}, which has the defaults (every feature off) until the settings are read
|
||||
* at load.
|
||||
*/
|
||||
public enum Feature
|
||||
{
|
||||
/**
|
||||
* Performance changes that alter timing or resource use: more threads, shorter waits. Off,
|
||||
* the patched code does what vanilla does.
|
||||
*/
|
||||
EXPERIMENTAL_PERFORMANCE;
|
||||
|
||||
/** Prefix of the system properties: {@code zomboidforge.features.<key>}. */
|
||||
public static final String PROPERTY_PREFIX = "zomboidforge.features.";
|
||||
|
||||
/** The key in {@code forge.toml} and in the property name: the lowercase constant name. */
|
||||
public String key() { return this.name().toLowerCase(Locale.ROOT); }
|
||||
|
||||
/** The system property that switches this feature. */
|
||||
public String property() { return Feature.PROPERTY_PREFIX + this.key(); }
|
||||
|
||||
/** The feature with {@code key}. */
|
||||
public static Optional<Feature> byKey(String key)
|
||||
{
|
||||
return Arrays.stream(Feature.values()).filter(feature -> feature.key().equals(key)).findFirst();
|
||||
}
|
||||
}
|
||||
@@ -7,47 +7,58 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* Global settings from {@code <forge>/forge.toml}. Every key is optional:
|
||||
*
|
||||
* <pre>
|
||||
* [main_thread]
|
||||
* budget_ms = 2 # time per tick for tasks that mods hand to the main thread
|
||||
*
|
||||
* [shutdown]
|
||||
* timeout_s = 10 # how long mod threads get to finish when the server stops
|
||||
* </pre>
|
||||
* Global settings from {@code <forge>/forge.toml}.
|
||||
* The system property {@code zomboidforge.features.<key>}
|
||||
* of a feature takes precedence over its key in the file.
|
||||
*
|
||||
* @param mainThreadBudget at least 1 ms
|
||||
* @param shutdownTimeout 0 or more
|
||||
* @param features the features that are enabled
|
||||
*/
|
||||
public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout)
|
||||
public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout, Set<Feature> features)
|
||||
{
|
||||
public static final String FILE = "forge.toml";
|
||||
public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10));
|
||||
public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of());
|
||||
|
||||
private record Document(Optional<MainThread> mainThread, Optional<Shutdown> shutdown) {}
|
||||
public ForgeSettings
|
||||
{
|
||||
features = Set.copyOf(features);
|
||||
}
|
||||
|
||||
/** Whether {@code feature} is on. */
|
||||
public boolean enabled(Feature feature) { return this.features.contains(feature); }
|
||||
|
||||
private record Document(Optional<MainThread> mainThread, Optional<Shutdown> shutdown, Optional<Map<String, Boolean>> features) {}
|
||||
private record MainThread(Optional<Long> budgetMs) {}
|
||||
private record Shutdown(Optional<Long> timeoutS) {}
|
||||
|
||||
/**
|
||||
* The settings in {@code file}, or {@link #DEFAULTS} when it does not exist.
|
||||
* The settings in {@code file}, the defaults for what it leaves out or when it does not
|
||||
* exist; then the features switched in {@code properties} (the system properties).
|
||||
*
|
||||
* @throws IllegalArgumentException listing every problem: invalid TOML, unknown keys, values
|
||||
* of the wrong type or out of range
|
||||
* of the wrong type or out of range, feature properties that
|
||||
* name no feature or are not {@code true} or {@code false}
|
||||
*/
|
||||
public static ForgeSettings read(Path file)
|
||||
public static ForgeSettings read(Path file, Properties properties)
|
||||
{
|
||||
if (!Files.isRegularFile(file)) return ForgeSettings.DEFAULTS;
|
||||
Map<String, Object> values = Map.of();
|
||||
|
||||
Map<String, Object> values;
|
||||
|
||||
try { values = TomlTree.parse(Files.readString(file)); }
|
||||
catch (IOException e) { throw new IllegalArgumentException("Cannot read '" + file + "': " + e.getMessage(), e); }
|
||||
if (Files.isRegularFile(file))
|
||||
{
|
||||
try { values = TomlTree.parse(Files.readString(file)); }
|
||||
catch (IOException e) { throw new IllegalArgumentException("Cannot read '" + file + "': " + e.getMessage(), e); }
|
||||
}
|
||||
|
||||
RecordBinder binder = new RecordBinder();
|
||||
@Nullable Document document = binder.record(values, Document.class, "");
|
||||
@@ -63,8 +74,31 @@ public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout)
|
||||
if (budget < 1) problems.add("'main_thread.budget_ms' must be at least 1, found " + budget + ".");
|
||||
if (timeout < 0) problems.add("'shutdown.timeout_s' must not be negative, found " + timeout + ".");
|
||||
|
||||
Set<Feature> features = EnumSet.noneOf(Feature.class);
|
||||
|
||||
for (Map.Entry<String, Boolean> entry : new TreeMap<>(document.features().orElse(Map.of())).entrySet())
|
||||
{
|
||||
Optional<Feature> feature = Feature.byKey(entry.getKey());
|
||||
|
||||
if (feature.isEmpty()) problems.add("Unknown key 'features." + entry.getKey() + "'.");
|
||||
else if (entry.getValue()) features.add(feature.get());
|
||||
}
|
||||
|
||||
for (String name : new TreeSet<>(properties.stringPropertyNames()))
|
||||
{
|
||||
if (!name.startsWith(Feature.PROPERTY_PREFIX)) continue;
|
||||
|
||||
Optional<Feature> feature = Feature.byKey(name.substring(Feature.PROPERTY_PREFIX.length()));
|
||||
String value = properties.getProperty(name);
|
||||
|
||||
if (feature.isEmpty()) problems.add("Unknown system property '" + name + "'.");
|
||||
else if (value.equalsIgnoreCase("true")) features.add(feature.get());
|
||||
else if (value.equalsIgnoreCase("false")) features.remove(feature.get());
|
||||
else problems.add("System property '" + name + "' must be true or false, found \"" + value + "\".");
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||
|
||||
return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout));
|
||||
return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout), features);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class FeatureTest
|
||||
{
|
||||
@Test
|
||||
void keyAndPropertyFollowFromTheName()
|
||||
{
|
||||
assertEquals("experimental_performance", Feature.EXPERIMENTAL_PERFORMANCE.key());
|
||||
assertEquals("zomboidforge.features.experimental_performance", Feature.EXPERIMENTAL_PERFORMANCE.property());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findsFeaturesByKey()
|
||||
{
|
||||
assertEquals(Optional.of(Feature.EXPERIMENTAL_PERFORMANCE), Feature.byKey("experimental_performance"));
|
||||
assertEquals(Optional.empty(), Feature.byKey("EXPERIMENTAL_PERFORMANCE"));
|
||||
assertEquals(Optional.empty(), Feature.byKey("faster"));
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,13 @@ import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ForgeSettingsTest
|
||||
{
|
||||
@@ -16,27 +20,41 @@ class ForgeSettingsTest
|
||||
Path directory;
|
||||
|
||||
private ForgeSettings read(String toml) throws Exception
|
||||
{
|
||||
return this.read(toml, new Properties());
|
||||
}
|
||||
|
||||
private ForgeSettings read(String toml, Properties properties) throws Exception
|
||||
{
|
||||
Path file = this.directory.resolve(ForgeSettings.FILE);
|
||||
Files.writeString(file, toml);
|
||||
|
||||
return ForgeSettings.read(file);
|
||||
return ForgeSettings.read(file, properties);
|
||||
}
|
||||
|
||||
private static Properties properties(String... namesAndValues)
|
||||
{
|
||||
Properties properties = new Properties();
|
||||
for (int i = 0; i < namesAndValues.length; i += 2) properties.setProperty(namesAndValues[i], namesAndValues[i + 1]);
|
||||
|
||||
return properties;
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultsWithoutFileOrKeys() throws Exception
|
||||
{
|
||||
assertEquals(ForgeSettings.DEFAULTS, ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)));
|
||||
assertEquals(ForgeSettings.DEFAULTS, ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), new Properties()));
|
||||
assertEquals(ForgeSettings.DEFAULTS, this.read("[main_thread]\n"));
|
||||
assertEquals(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10)), ForgeSettings.DEFAULTS);
|
||||
assertEquals(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of()), ForgeSettings.DEFAULTS);
|
||||
assertFalse(ForgeSettings.DEFAULTS.enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsEveryKey() throws Exception
|
||||
{
|
||||
assertEquals(
|
||||
new ForgeSettings(Duration.ofMillis(5), Duration.ofSeconds(0)),
|
||||
this.read("[main_thread]\nbudget_ms = 5\n\n[shutdown]\ntimeout_s = 0\n")
|
||||
new ForgeSettings(Duration.ofMillis(5), Duration.ofSeconds(0), Set.of(Feature.EXPERIMENTAL_PERFORMANCE)),
|
||||
this.read("[main_thread]\nbudget_ms = 5\n\n[shutdown]\ntimeout_s = 0\n\n[features]\nexperimental_performance = true\n")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -52,4 +70,50 @@ class ForgeSettingsTest
|
||||
IllegalArgumentException type = assertThrows(IllegalArgumentException.class, () -> this.read("[shutdown]\ntimeout_s = \"10\"\n"));
|
||||
assertEquals("'shutdown.timeout_s' must be an integer, found \"10\".", type.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void featuresAreOffUnlessSwitchedOn() throws Exception
|
||||
{
|
||||
assertFalse(this.read("[features]\nexperimental_performance = false\n").enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
assertTrue(this.read("[features]\nexperimental_performance = true\n").enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void systemPropertyTakesPrecedenceOverTheFile() throws Exception
|
||||
{
|
||||
String property = Feature.EXPERIMENTAL_PERFORMANCE.property();
|
||||
|
||||
assertTrue(this.read("", ForgeSettingsTest.properties(property, "true")).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
assertTrue(this.read("[features]\nexperimental_performance = false\n", ForgeSettingsTest.properties(property, "TRUE")).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
assertFalse(this.read("[features]\nexperimental_performance = true\n", ForgeSettingsTest.properties(property, "false")).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void systemPropertyAppliesWithoutFile()
|
||||
{
|
||||
Properties properties = ForgeSettingsTest.properties(Feature.EXPERIMENTAL_PERFORMANCE.property(), "true");
|
||||
|
||||
assertTrue(ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), properties).enabled(Feature.EXPERIMENTAL_PERFORMANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsUnknownFeaturesAndInvalidPropertyValues()
|
||||
{
|
||||
IllegalArgumentException key = assertThrows(IllegalArgumentException.class, () -> this.read("[features]\nexperimental_performance = \"yes\"\nfaster = true\n"));
|
||||
assertEquals("'features.experimental_performance' must be true or false, found \"yes\".", key.getMessage());
|
||||
|
||||
IllegalArgumentException unknown = assertThrows(IllegalArgumentException.class, () -> this.read("[features]\nfaster = true\n"));
|
||||
assertEquals("Unknown key 'features.faster'.", unknown.getMessage());
|
||||
|
||||
Properties properties = ForgeSettingsTest.properties(
|
||||
"zomboidforge.features.faster", "true",
|
||||
Feature.EXPERIMENTAL_PERFORMANCE.property(), "yes",
|
||||
"zomboidforge.dir", "/forge"
|
||||
);
|
||||
IllegalArgumentException property = assertThrows(IllegalArgumentException.class, () -> this.read("", properties));
|
||||
assertEquals(
|
||||
"System property 'zomboidforge.features.experimental_performance' must be true or false, found \"yes\". Unknown system property 'zomboidforge.features.faster'.",
|
||||
property.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -45,10 +45,21 @@
|
||||
# JVM_UNCOMMIT_DELAY
|
||||
# Seconds of disuse after which ZGC returns heap memory to the system
|
||||
# (-XX:ZUncommitDelay). Default: 60 (JVM default: 300)
|
||||
# JVM_EXPERIMENTAL_PERFORMANCE
|
||||
# true/false: compact object headers (-XX:+UseCompactObjectHeaders) and
|
||||
# transparent huge pages for the heap (-XX:+UseTransparentHugePages).
|
||||
# Huge pages need the host's
|
||||
# /sys/kernel/mm/transparent_hugepage/shmem_enabled at advise or always;
|
||||
# otherwise the JVM logs a warning and runs without them. Default: false
|
||||
#
|
||||
# Maintenance
|
||||
# SOFT_RESET true: start in Project Zomboid's soft reset mode (-Dsoftreset).
|
||||
# Intended for a single start; unset it afterwards.
|
||||
#
|
||||
# ZomboidForge features (also /forge/forge.toml [features]; a set variable takes precedence)
|
||||
# ZF_EXPERIMENTAL_PERFORMANCE
|
||||
# true/false: performance changes that alter timing or resource use
|
||||
# (more threads, shorter waits). Default: false
|
||||
|
||||
set -o errexit
|
||||
set -o nounset
|
||||
@@ -78,6 +89,7 @@ readonly RCON_PASSWORD="${RCON_PASSWORD:-}"
|
||||
readonly JVM_MIN_HEAP="${JVM_MIN_HEAP:-}"
|
||||
readonly JVM_MAX_HEAP="${JVM_MAX_HEAP:-}"
|
||||
readonly JVM_UNCOMMIT_DELAY="${JVM_UNCOMMIT_DELAY:-60}"
|
||||
readonly JVM_EXPERIMENTAL_PERFORMANCE="${JVM_EXPERIMENTAL_PERFORMANCE:-}"
|
||||
readonly SOFT_RESET="${SOFT_RESET:-}"
|
||||
|
||||
readonly SERVER_INI="${DATA_DIR}/Server/${SERVER_NAME}.ini"
|
||||
@@ -86,6 +98,9 @@ readonly SERVER_DB="${DATA_DIR}/db/${SERVER_NAME}.db"
|
||||
# Target of the /opt/pz/steamapps symlink; Steam stores Workshop downloads there.
|
||||
readonly STEAMAPPS_DIR="${DATA_DIR}/steamapps"
|
||||
readonly CGROUP_MEMORY_MAX="/sys/fs/cgroup/memory.max"
|
||||
# Keys of the ZomboidForge features (core/config/Feature): ZF_<KEY> becomes
|
||||
# -Dzomboidforge.features.<key>.
|
||||
readonly FEATURES=(experimental_performance)
|
||||
readonly UNLIMITED_MAX_HEAP="8g"
|
||||
|
||||
log() {
|
||||
@@ -272,6 +287,30 @@ default_max_heap() {
|
||||
echo "$(( limit * 3 / 4 / 1024 / 1024 ))m"
|
||||
}
|
||||
|
||||
# Appends -Dzomboidforge.features.<key>=true|false for every feature whose ZF_<KEY> is set.
|
||||
# Unset or empty: no property, so forge.toml or the default (off) decides.
|
||||
add_feature_properties() {
|
||||
local key
|
||||
local variable
|
||||
local value
|
||||
|
||||
for key in "${FEATURES[@]}"; do
|
||||
variable="ZF_${key^^}"
|
||||
value="${!variable:-}"
|
||||
|
||||
if [[ -z "${value}" ]]; then
|
||||
continue
|
||||
fi
|
||||
if is_true "${value}"; then
|
||||
jvm_args+=("-Dzomboidforge.features.${key}=true")
|
||||
elif is_false "${value}"; then
|
||||
jvm_args+=("-Dzomboidforge.features.${key}=false")
|
||||
else
|
||||
fail "${variable} must be true or false, got '${value}'."
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Same JVM setup as the vanilla ProjectZomboid64.json and start-server.sh.
|
||||
# Java runs directly instead of through the native ProjectZomboid64 launcher.
|
||||
build_jvm_args() {
|
||||
@@ -304,10 +343,18 @@ build_jvm_args() {
|
||||
if [[ -n "${JVM_MIN_HEAP}" ]]; then
|
||||
jvm_args+=("-Xms${JVM_MIN_HEAP}")
|
||||
fi
|
||||
if [[ -n "${JVM_EXPERIMENTAL_PERFORMANCE}" ]]; then
|
||||
if is_true "${JVM_EXPERIMENTAL_PERFORMANCE}"; then
|
||||
jvm_args+=("-XX:+UseCompactObjectHeaders" "-XX:+UseTransparentHugePages")
|
||||
elif ! is_false "${JVM_EXPERIMENTAL_PERFORMANCE}"; then
|
||||
fail "JVM_EXPERIMENTAL_PERFORMANCE must be true or false, got '${JVM_EXPERIMENTAL_PERFORMANCE}'."
|
||||
fi
|
||||
fi
|
||||
if [[ -n "${SOFT_RESET}" ]] && is_true "${SOFT_RESET}"; then
|
||||
log "SOFT_RESET is set: starting in soft reset mode. Unset it for the next start."
|
||||
jvm_args+=("-Dsoftreset")
|
||||
fi
|
||||
add_feature_properties
|
||||
}
|
||||
|
||||
build_server_args() {
|
||||
|
||||
Reference in new issue
Block a user