Compare commits
2
Commits
26ca1b90a2
...
18ff32b5ce
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18ff32b5ce | ||
|
|
67530d35e9 |
No files matched your search
@@ -20,7 +20,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
# release.sh derives the version from the newest v* tag
|
||||
# release.sh derives the version from the v* tags
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Build and verify
|
||||
|
||||
@@ -9,7 +9,6 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
maven:
|
||||
@@ -17,7 +16,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
# publish.sh derives the version from the newest v* tag
|
||||
# publish.sh derives the version from the v* tag on HEAD
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
# release.sh derives the version from the newest v* tag
|
||||
# release.sh derives the version from the v* tags
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Log in to the registry
|
||||
|
||||
+10
-3
@@ -69,7 +69,8 @@ game jar for mods that declare `game` versions. Default settings go into
|
||||
| `gameJar` | see below | the `projectzomboid.jar` to compile and check against |
|
||||
| `steamBranch` | `public` | Steam branch for the download: `public`, `unstable`, or a version such as `42.19` |
|
||||
| `serverImage` | the ZomboidForge image, `latest` | image for `runServer` |
|
||||
| `adminPassword` | `admin` | admin password of the `runServer` server |
|
||||
| `adminPassword` | random, generated once per volume | admin password of the `runServer` server (see below) |
|
||||
| `serverAddress` | `127.0.0.1` | host address `runServer` publishes the game ports on; `0.0.0.0` for the network |
|
||||
| `dataVolume` | `zomboidforge-<id>` | volume for the `runServer` world and server config |
|
||||
| `containerEngine` | podman or docker, whichever is installed | for `runServer` and the download |
|
||||
| `deployDirectory` | none | a server's mods directory for `deployMod` |
|
||||
@@ -104,9 +105,15 @@ The game jar has to be one of the declared `game` versions; the check below fail
|
||||
| `modFolder` | `build/mod/<id>/` with `<id>.jar` and `lib/`, as a server expects it in `<forge>/mods` |
|
||||
| `modZip` | the same as `build/distributions/<id>-<version>.zip` |
|
||||
| `runServer` | a ZomboidForge server in a container with the mod; Ctrl+C stops it after it saved the world |
|
||||
| `deployMod` | copies the mod folder into `deployDirectory` |
|
||||
| `deployMod` | copies the mod folder into `deployDirectory`; keeps the server's `config.toml` of the mod |
|
||||
| `downloadGame` | installs the dedicated server for its game jar; runs only when needed |
|
||||
|
||||
`runServer` is reachable from this machine only, unless `serverAddress` says otherwise. Without
|
||||
`adminPassword`, the first run generates a random admin password for the volume, prints it, and
|
||||
keeps it in `<Gradle user home>/zomboidforge/admin-passwords/<volume>`. The server uses the
|
||||
password only when it creates the admin account, on the volume's first start; a later change
|
||||
needs a new volume (`dataVolume`, or remove the old one).
|
||||
|
||||
### Working on ZomboidForge itself
|
||||
|
||||
To build a mod against a local ZomboidForge checkout instead of a published version, include it
|
||||
@@ -220,7 +227,7 @@ balances.set("player1", new Balance(250, Instant.now()));
|
||||
Optional<Balance> balance = balances.get("player1");
|
||||
balances.update("player1", old -> new Balance(old.coins() + 10, Instant.now()), () -> new Balance(0, null));
|
||||
|
||||
this.storage().transaction(() -> { // all or nothing
|
||||
this.storage().transaction(() -> { // all or nothing, also when nested
|
||||
balances.update("player1", old -> new Balance(old.coins() - 5, old.lastPaid()), () -> new Balance(0, null));
|
||||
balances.update("player2", old -> new Balance(old.coins() + 5, old.lastPaid()), () -> new Balance(0, null));
|
||||
});
|
||||
|
||||
+5
-5
@@ -2,10 +2,10 @@
|
||||
#
|
||||
# Publishes the mod API (dev.overlord.zomboidforge:api), the mod tools (mod-tools), and the
|
||||
# Gradle plugin (dev.overlord.zomboidforge.mod) to the Maven registry of the ZomboidForge Gitea,
|
||||
# in the version of the newest v* git tag reachable from HEAD, without the "v".
|
||||
# in the version of the v* git tag on HEAD, without the "v".
|
||||
#
|
||||
# A pre-release version (containing "-", e.g. 0.3.0-rc.1) is built and tested but never
|
||||
# published. Without any v* tag nothing is published.
|
||||
# published. Without a v* tag on HEAD nothing is published.
|
||||
#
|
||||
# Environment:
|
||||
# ORG_GRADLE_PROJECT_giteaUsername Gitea user with package write access
|
||||
@@ -31,11 +31,11 @@ log() {
|
||||
echo "[publish] $*" >&2
|
||||
}
|
||||
|
||||
# Prints the newest v* tag reachable from HEAD without its "v", or nothing.
|
||||
# Prints the v* tag on HEAD without its "v", or nothing.
|
||||
release_tag_version() {
|
||||
local tag
|
||||
|
||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then
|
||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
|
||||
echo "${tag#v}"
|
||||
fi
|
||||
}
|
||||
@@ -69,7 +69,7 @@ main() {
|
||||
|
||||
version="$(release_tag_version)"
|
||||
if [[ -z "${version}" ]]; then
|
||||
log "No v* git tag found (shallow clone without tags?); nothing to publish."
|
||||
log "HEAD has no v* git tag (not a release commit, or a shallow clone without tags?); nothing to publish."
|
||||
exit 1
|
||||
fi
|
||||
if [[ "${version}" == *-* ]]; then
|
||||
|
||||
+10
-6
@@ -10,9 +10,10 @@
|
||||
# <major.minor.build> is the version the branch's server jar reports, read before the full
|
||||
# build (Dockerfile stage game-version, which downloads only the jar).
|
||||
#
|
||||
# <forge> is the newest v* git tag reachable from HEAD, without the "v" (v0.2.0 -> 0.2.0).
|
||||
# A pre-release version (containing "-", e.g. 0.2.0-rc.1) is built and verified but never
|
||||
# published. Without any v* tag the version is "0.0.0-prerelease".
|
||||
# <forge> is the v* git tag on HEAD, without the "v" (v0.2.0 -> 0.2.0). When HEAD has no such
|
||||
# tag, it is the git describe version of HEAD (0.2.0-3-g1a2b3c4: 3 commits after v0.2.0).
|
||||
# A pre-release version (containing "-", e.g. 0.2.0-rc.1 or 0.2.0-3-g1a2b3c4) is built and
|
||||
# verified but never published. Without any v* tag the version is "0.0.0-prerelease".
|
||||
#
|
||||
# Nothing is built when <forge>-pz<major.minor.build> already exists in the registry. The
|
||||
# server only admits clients with the same major.minor.build, so every hotfix (42.21.1 ->
|
||||
@@ -69,12 +70,15 @@ gradle_property() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Prints the forge version: the newest v* tag reachable from HEAD without its "v",
|
||||
# or nothing when the repository has no such tag.
|
||||
# Prints the forge version without the "v": the v* tag on HEAD, else the git describe version
|
||||
# of HEAD relative to the newest reachable v* tag (v0.2.0-3-g1a2b3c4), or nothing when the
|
||||
# repository has no such tag.
|
||||
release_tag_version() {
|
||||
local tag
|
||||
|
||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then
|
||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
|
||||
echo "${tag#v}"
|
||||
elif tag="$(git -C "${REPO_ROOT}" describe --tags --match 'v*' 2> /dev/null)"; then
|
||||
echo "${tag#v}"
|
||||
fi
|
||||
}
|
||||
|
||||
+3
-3
@@ -75,7 +75,7 @@ public final class ServerHooks
|
||||
ForgeInstance.FORGE.started();
|
||||
System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ").");
|
||||
}
|
||||
catch (RuntimeException e) { e.printStackTrace(); }
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,7 +87,7 @@ public final class ServerHooks
|
||||
public static void onTick()
|
||||
{
|
||||
try { ForgeInstance.FORGE.tick(); }
|
||||
catch (RuntimeException e) { e.printStackTrace(); }
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -105,6 +105,6 @@ public final class ServerHooks
|
||||
System.out.println("[ZomboidForge] Server stopping.");
|
||||
ForgeInstance.FORGE.stopping();
|
||||
}
|
||||
catch (RuntimeException e) { e.printStackTrace(); }
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -20,6 +20,6 @@ public final class StorageHooks
|
||||
if (running) ForgeInstance.FORGE.backupStarted();
|
||||
else ForgeInstance.FORGE.backupFinished();
|
||||
}
|
||||
catch (RuntimeException e) { e.printStackTrace(); }
|
||||
catch (Throwable t) { t.printStackTrace(); }
|
||||
}
|
||||
}
|
||||
@@ -154,14 +154,17 @@ public final class Forge
|
||||
);
|
||||
}
|
||||
|
||||
/** Calls {@link Mod#onServerStarted()} of every mod in load order. Main thread. */
|
||||
/**
|
||||
* Calls {@link Mod#onServerStarted()} of every mod in load order. Main thread. Anything a
|
||||
* mod throws is logged, and the next mod is called.
|
||||
*/
|
||||
public void started()
|
||||
{
|
||||
this.lifecycle.started();
|
||||
|
||||
for (ModLoader.LoadedMod mod : this.mods) {
|
||||
try { mod.mod().onServerStarted(); }
|
||||
catch (RuntimeException e) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", e); }
|
||||
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", t); }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,19 +208,25 @@ public final class Forge
|
||||
|
||||
/**
|
||||
* Once: calls {@link Mod#onStopping()} of every mod in reverse load order, then stops the
|
||||
* mods' threads, events, and storage (see {@link #stopMods}). Called on the shutdown thread.
|
||||
* mods' threads, events, and storage (see {@link #stopMods}). Called on the shutdown thread,
|
||||
* before the world is saved, so nothing a mod throws leaves this method.
|
||||
*/
|
||||
public void stopping()
|
||||
{
|
||||
if (!this.lifecycle.stopping()) return;
|
||||
|
||||
try
|
||||
{
|
||||
for (ModLoader.LoadedMod mod : this.mods.reversed()) {
|
||||
try { mod.mod().onStopping(); }
|
||||
catch (RuntimeException e) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", e); }
|
||||
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", t); }
|
||||
}
|
||||
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.stopMods(this.settings.shutdownTimeout());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects further main-thread tasks and cancels the queued ones, stops event delivery, gives
|
||||
|
||||
@@ -79,6 +79,8 @@ public final class MainThreadQueue
|
||||
int index = count == 0 ? 0 : this.next % count;
|
||||
int empty = 0;
|
||||
|
||||
try
|
||||
{
|
||||
while (empty < count && !this.closed)
|
||||
{
|
||||
ModQueue queue = queues[index];
|
||||
@@ -96,9 +98,12 @@ public final class MainThreadQueue
|
||||
|
||||
if (System.nanoTime() >= deadline) break;
|
||||
}
|
||||
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.next = index;
|
||||
}
|
||||
}
|
||||
|
||||
/** Rejects further tasks and cancels the queued ones (their futures are cancelled). Any thread. */
|
||||
public void close()
|
||||
|
||||
@@ -25,8 +25,8 @@ final class ModTaskEvent extends jdk.jfr.Event
|
||||
|
||||
/**
|
||||
* Runs {@code action} as a {@code zomboidforge.ModTask} event. Mod code must not end the
|
||||
* calling thread's work, so failures are returned instead of thrown: runtime exceptions,
|
||||
* missing classes or members ({@link LinkageError}), and stack overflows.
|
||||
* calling thread's work, so every failure is returned instead of thrown, including errors
|
||||
* and checked exceptions thrown without being declared.
|
||||
*
|
||||
* @return the failure, or {@code null} when {@code action} returned normally
|
||||
*/
|
||||
@@ -40,9 +40,9 @@ final class ModTaskEvent extends jdk.jfr.Event
|
||||
action.run();
|
||||
return null;
|
||||
}
|
||||
catch (RuntimeException | LinkageError | StackOverflowError e)
|
||||
catch (Throwable t)
|
||||
{
|
||||
return e;
|
||||
return t;
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -10,6 +10,7 @@ import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Savepoint;
|
||||
import java.sql.Statement;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.BooleanSupplier;
|
||||
@@ -104,8 +105,10 @@ public final class StorageDatabase implements AutoCloseable
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs {@code work} in a transaction. Nested calls on the same thread join the outer
|
||||
* transaction; it commits when the outermost call returns and rolls back when any throws.
|
||||
* Runs {@code work} in a transaction. The outermost call on a thread commits when
|
||||
* {@code work} returns and rolls back when it throws. A nested call runs inside a savepoint
|
||||
* of the outer transaction: when its {@code work} throws, only its own writes are rolled
|
||||
* back, also when the outer work catches the exception.
|
||||
*/
|
||||
public <T> T transaction(Work<T> work)
|
||||
{
|
||||
@@ -118,19 +121,23 @@ public final class StorageDatabase implements AutoCloseable
|
||||
boolean outermost = this.depth == 0;
|
||||
|
||||
if (outermost) connection.setAutoCommit(false);
|
||||
|
||||
Savepoint savepoint = outermost ? null : connection.setSavepoint();
|
||||
this.depth++;
|
||||
|
||||
try
|
||||
{
|
||||
T result = work.run(connection);
|
||||
if (outermost) connection.commit();
|
||||
|
||||
if (savepoint == null) connection.commit();
|
||||
else connection.releaseSavepoint(savepoint);
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (SQLException | RuntimeException | Error e)
|
||||
catch (Throwable t)
|
||||
{
|
||||
if (outermost) StorageDatabase.rollback(connection, e);
|
||||
throw e;
|
||||
StorageDatabase.rollback(connection, savepoint, t);
|
||||
throw t;
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -241,9 +248,21 @@ public final class StorageDatabase implements AutoCloseable
|
||||
return connection;
|
||||
}
|
||||
|
||||
private static void rollback(Connection connection, Throwable cause)
|
||||
/** Rolls back the transaction, or only to {@code savepoint} (and releases it) when one is given. */
|
||||
private static void rollback(Connection connection, @Nullable Savepoint savepoint, Throwable cause)
|
||||
{
|
||||
try { connection.rollback(); }
|
||||
catch (SQLException e) { cause.addSuppressed(e); }
|
||||
try
|
||||
{
|
||||
if (savepoint == null) {
|
||||
connection.rollback();
|
||||
} else {
|
||||
connection.rollback(savepoint);
|
||||
connection.releaseSavepoint(savepoint);
|
||||
}
|
||||
}
|
||||
catch (SQLException e)
|
||||
{
|
||||
cause.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import testmods.ContextMod;
|
||||
import testmods.ErrorMod;
|
||||
import testmods.Recorder;
|
||||
import testmods.ThreadMod;
|
||||
|
||||
@@ -197,6 +198,25 @@ class ForgeTest
|
||||
assertEquals(Lifecycle.Phase.BOOTING, forge.phase());
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorsOfModsInStartedAndStoppingReachNeitherTheGameNorTheOtherMods() throws Exception
|
||||
{
|
||||
TestMods.folder(this.mods, "economy", TestMods.toml("economy", "economy.EconomyMod", ForgeTest.USES_GAME), Map.of(
|
||||
"economy/EconomyMod", TestMods.modClass("economy/EconomyMod", "economy", null, false)
|
||||
));
|
||||
TestMods.folder(this.mods, "errors", TestMods.toml("errors", ErrorMod.class.getName(), "[dependencies]\neconomy = \"1.0\"\n"), Map.of(
|
||||
"testmods/ErrorMod", TestMods.classFile(ErrorMod.class)
|
||||
));
|
||||
|
||||
Forge forge = this.load();
|
||||
|
||||
forge.started();
|
||||
forge.stopping();
|
||||
|
||||
assertEquals(List.of("economy:new", "economy:onLoad", "economy:onServerStarted", "economy:onStopping"), Recorder.EVENTS, "economy is stopped after errors stopped");
|
||||
assertEquals(Lifecycle.Phase.STOPPING, forge.phase());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheEntryPointIsNoMod() throws IOException
|
||||
{
|
||||
|
||||
@@ -152,6 +152,22 @@ class MainThreadQueueTest
|
||||
assertEquals(List.of("ERROR: A main-thread task threw. (java.lang.IllegalStateException: executed)"), this.logger.messages);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsErrorsOfTasksAndRunsTheNextTask() throws Exception
|
||||
{
|
||||
MainThread a = this.queue.forMod("a", this.logger);
|
||||
|
||||
MainThreadQueueTest.fromOtherThread(() -> {
|
||||
a.execute(() -> { throw new AssertionError("failed"); });
|
||||
a.execute(() -> this.ran.add("next"));
|
||||
});
|
||||
|
||||
this.queue.drain();
|
||||
|
||||
assertEquals(List.of("next"), this.ran);
|
||||
assertEquals(List.of("ERROR: A main-thread task threw. (java.lang.AssertionError: failed)"), this.logger.messages);
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeCancelsQueuedTasksAndRejectsNewOnes() throws Exception
|
||||
{
|
||||
|
||||
@@ -140,6 +140,50 @@ class ModTablesTest
|
||||
assertEquals(9, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollsBackAFailedNestedTransactionThatTheOuterOneCatches()
|
||||
{
|
||||
ModStorage storage = this.storage("shop");
|
||||
Table<Balance> balances = storage.table("balances", Balance.class);
|
||||
|
||||
storage.transaction(() -> {
|
||||
balances.set("a", new Balance(1));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> storage.transaction(() -> {
|
||||
balances.set("a", new Balance(100));
|
||||
balances.set("b", new Balance(100));
|
||||
throw new IllegalStateException("abort");
|
||||
}));
|
||||
|
||||
balances.set("c", new Balance(3));
|
||||
});
|
||||
|
||||
assertEquals(Optional.of(new Balance(1)), balances.get("a"));
|
||||
assertFalse(balances.contains("b"));
|
||||
assertEquals(Optional.of(new Balance(3)), balances.get("c"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollsBackForErrorsAndUndeclaredCheckedExceptions()
|
||||
{
|
||||
ModStorage storage = this.storage("shop");
|
||||
Table<Balance> balances = storage.table("balances", Balance.class);
|
||||
|
||||
assertThrows(AssertionError.class, () -> storage.transaction(() -> {
|
||||
balances.set("a", new Balance(1));
|
||||
throw new AssertionError("abort");
|
||||
}));
|
||||
assertThrows(Exception.class, () -> storage.transaction(() -> {
|
||||
balances.set("b", new Balance(1));
|
||||
ModTablesTest.sneakyThrow(new Exception("abort"));
|
||||
}));
|
||||
|
||||
assertEquals(0, balances.count());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <E extends Throwable> void sneakyThrow(Throwable t) throws E { throw (E) t; }
|
||||
|
||||
@Test
|
||||
void keepsModsApart()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package testmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
|
||||
/**
|
||||
* Entry point that tests package into a mod jar. Its lifecycle methods throw errors, which aren't
|
||||
* {@link RuntimeException}.
|
||||
*/
|
||||
public final class ErrorMod extends Mod
|
||||
{
|
||||
@Override
|
||||
public void onServerStarted() { throw new AssertionError("started"); }
|
||||
|
||||
@Override
|
||||
public void onStopping() { throw new NoClassDefFoundError("stopping"); }
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package dev.overlord.zomboidforge.gradle;
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.file.DirectoryProperty;
|
||||
import org.gradle.api.file.RegularFileProperty;
|
||||
import org.gradle.api.provider.Property;
|
||||
import org.gradle.api.tasks.Input;
|
||||
import org.gradle.api.tasks.Internal;
|
||||
@@ -15,6 +16,13 @@ import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.attribute.PosixFileAttributeView;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -37,6 +45,8 @@ public abstract class RunServer extends DefaultTask
|
||||
/** Seconds the server gets to save the world after a stop request. */
|
||||
private static final int STOP_TIMEOUT = 120;
|
||||
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
/** Contains one folder per mod, as in {@code <forge>/mods}. */
|
||||
@Internal
|
||||
public abstract DirectoryProperty getModsDirectory();
|
||||
@@ -50,9 +60,17 @@ public abstract class RunServer extends DefaultTask
|
||||
@Input
|
||||
public abstract Property<String> getDataVolume();
|
||||
|
||||
@Input
|
||||
/** Not an input, so it is not stored in the task history. */
|
||||
@Internal
|
||||
public abstract Property<String> getAdminPassword();
|
||||
|
||||
/** Holds the generated admin password of the volume when {@link #getAdminPassword()} is not set. */
|
||||
@Internal
|
||||
public abstract RegularFileProperty getAdminPasswordFile();
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getServerAddress();
|
||||
|
||||
@Input
|
||||
@Optional
|
||||
public abstract Property<String> getContainerEngine();
|
||||
@@ -62,21 +80,26 @@ public abstract class RunServer extends DefaultTask
|
||||
{
|
||||
String engine = Executables.containerEngine(this.getContainerEngine().getOrNull());
|
||||
String name = this.getContainerName().get();
|
||||
String address = this.getServerAddress().get();
|
||||
|
||||
// ADMIN_PASSWORD without a value takes the value from the engine's environment, so it is not in the command line.
|
||||
List<String> command = List.of(
|
||||
engine, "run", "--rm",
|
||||
"--name", name,
|
||||
"--publish", "16261:16261/udp",
|
||||
"--publish", "16262:16262/udp",
|
||||
"--env", "ADMIN_PASSWORD=" + this.getAdminPassword().get(),
|
||||
"--publish", address + ":16261:16261/udp",
|
||||
"--publish", address + ":16262:16262/udp",
|
||||
"--env", "ADMIN_PASSWORD",
|
||||
"--volume", this.getDataVolume().get() + ":/data",
|
||||
"--volume", this.getModsDirectory().get().getAsFile().getAbsolutePath() + ":/forge/mods:ro,Z",
|
||||
this.getImage().get()
|
||||
);
|
||||
|
||||
this.getLogger().lifecycle("Starting {} with the mod; connect to localhost:16261. Cancel the build (Ctrl+C) to stop the server.", this.getImage().get());
|
||||
ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true);
|
||||
builder.environment().put("ADMIN_PASSWORD", this.adminPassword());
|
||||
|
||||
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||
this.getLogger().lifecycle("Starting {} with the mod on {}:16261. Cancel the build (Ctrl+C) to stop the server.", this.getImage().get(), address);
|
||||
|
||||
Process process = builder.start();
|
||||
Thread output = new Thread(() -> RunServer.forward(process), "runServer output");
|
||||
|
||||
output.setDaemon(true);
|
||||
@@ -96,6 +119,42 @@ public abstract class RunServer extends DefaultTask
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The configured admin password, else the one in {@link #getAdminPasswordFile()}; a random one
|
||||
* is generated into the file when it does not exist. The server uses the password only when it
|
||||
* creates the admin account on the volume's first start.
|
||||
*/
|
||||
private String adminPassword() throws IOException
|
||||
{
|
||||
String configured = this.getAdminPassword().getOrNull();
|
||||
if (configured != null) return configured;
|
||||
|
||||
Path file = this.getAdminPasswordFile().get().getAsFile().toPath();
|
||||
|
||||
if (Files.exists(file)) return Files.readString(file, StandardCharsets.UTF_8).strip();
|
||||
|
||||
byte[] random = new byte[18];
|
||||
RunServer.RANDOM.nextBytes(random);
|
||||
|
||||
String password = Base64.getUrlEncoder().withoutPadding().encodeToString(random);
|
||||
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, password, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
|
||||
RunServer.restrictToOwner(file);
|
||||
|
||||
this.getLogger().lifecycle("Generated the admin password '{}' for '{}', kept in '{}'.", password, this.getDataVolume().get(), file);
|
||||
|
||||
return password;
|
||||
}
|
||||
|
||||
/** Makes {@code file} readable and writable by its owner only, where the file system has POSIX permissions. */
|
||||
private static void restrictToOwner(Path file) throws IOException
|
||||
{
|
||||
if (!Files.getFileStore(file).supportsFileAttributeView(PosixFileAttributeView.class)) return;
|
||||
|
||||
Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rw-------"));
|
||||
}
|
||||
|
||||
/** Copies the container's output to the build output, line by line. */
|
||||
private static void forward(Process process)
|
||||
{
|
||||
|
||||
+8
-1
@@ -64,9 +64,16 @@ public abstract class ZomboidForgeExtension
|
||||
/** Image for {@code runServer}. Default: the ZomboidForge image tagged "latest". */
|
||||
public abstract Property<String> getServerImage();
|
||||
|
||||
/** Admin password of the {@code runServer} server. Default: "admin". */
|
||||
/**
|
||||
* Admin password of the {@code runServer} server, used when its volume is created. Default:
|
||||
* a random password, generated once per volume and kept in
|
||||
* {@code <Gradle user home>/zomboidforge/admin-passwords/<volume>}.
|
||||
*/
|
||||
public abstract Property<String> getAdminPassword();
|
||||
|
||||
/** Host address {@code runServer} publishes the game ports on. Default: "127.0.0.1" (this machine only); "0.0.0.0" for every interface. */
|
||||
public abstract Property<String> getServerAddress();
|
||||
|
||||
/** Volume for the {@code runServer} server's /data (world, config). Default: "zomboidforge-<id>". */
|
||||
public abstract Property<String> getDataVolume();
|
||||
|
||||
|
||||
+8
-2
@@ -55,6 +55,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
private static final String TOOLS = "dev.overlord.zomboidforge:mod-tools:";
|
||||
private static final String TOOLS_MAIN = "dev.overlord.zomboidforge.tools.ModCheck";
|
||||
private static final String DEFAULT_IMAGE = "git.security-command.org/overlord/zomboidforge:latest";
|
||||
private static final String MOD_CONFIG = "config.toml";
|
||||
private static final int JAVA = 25;
|
||||
|
||||
@Override
|
||||
@@ -72,7 +73,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
extension.getApi().convention(version);
|
||||
extension.getSteamBranch().convention("public");
|
||||
extension.getServerImage().convention(ZomboidForgeModPlugin.DEFAULT_IMAGE);
|
||||
extension.getAdminPassword().convention("admin");
|
||||
extension.getServerAddress().convention("127.0.0.1");
|
||||
extension.getDataVolume().convention(extension.getId().map(id -> "zomboidforge-" + id));
|
||||
extension.getGameJar().convention(layout.file(project.getProviders().gradleProperty("zomboidforge.gameJar").map(File::new)));
|
||||
|
||||
@@ -220,6 +221,8 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
project.getTasks().named(LifecycleBasePlugin.ASSEMBLE_TASK_NAME, task -> task.dependsOn(modFolder, modZip));
|
||||
|
||||
// Trying the mod.
|
||||
File passwords = new File(project.getGradle().getGradleUserHomeDir(), "zomboidforge/admin-passwords");
|
||||
|
||||
project.getTasks().register("runServer", RunServer.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
@@ -230,14 +233,17 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
task.getContainerName().set(id.map(name -> "zomboidforge-" + name));
|
||||
task.getDataVolume().set(extension.getDataVolume());
|
||||
task.getAdminPassword().set(extension.getAdminPassword());
|
||||
task.getAdminPasswordFile().set(layout.file(extension.getDataVolume().map(volume -> new File(passwords, volume))));
|
||||
task.getServerAddress().set(extension.getServerAddress());
|
||||
task.getContainerEngine().set(extension.getContainerEngine());
|
||||
});
|
||||
|
||||
project.getTasks().register("deployMod", Sync.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setDescription("Copies the mod folder into zomboidForge.deployDirectory (a server's mods directory).");
|
||||
task.setDescription("Copies the mod folder into zomboidForge.deployDirectory (a server's mods directory); keeps the server's config.toml of the mod.");
|
||||
task.from(modFolder);
|
||||
task.preserve(filter -> filter.include(ZomboidForgeModPlugin.MOD_CONFIG));
|
||||
task.into(extension.getDeployDirectory().dir(id).orElse(layout.getBuildDirectory().dir("deploy-not-configured")));
|
||||
task.onlyIf("zomboidForge.deployDirectory is set", element -> extension.getDeployDirectory().isPresent());
|
||||
});
|
||||
|
||||
+18
@@ -22,6 +22,7 @@ import java.util.jar.JarOutputStream;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
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_FINAL;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
|
||||
@@ -140,6 +141,23 @@ class ZomboidForgeModPluginTest
|
||||
assertEquals(TaskOutcome.UP_TO_DATE, again.task(":checkMod").getOutcome());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deployReplacesTheModButKeepsTheServerSettings() throws IOException
|
||||
{
|
||||
this.modProject(" deployDirectory = layout.projectDirectory.dir(\"server/mods\")", "");
|
||||
|
||||
Path deployed = this.project.resolve("server/mods/shop");
|
||||
this.write("server/mods/shop/config.toml", "limit = 7\n");
|
||||
this.write("server/mods/shop/lib/old.jar", "");
|
||||
|
||||
this.runner("deployMod").build();
|
||||
|
||||
assertTrue(Files.isRegularFile(deployed.resolve("shop.jar")));
|
||||
assertTrue(Files.isRegularFile(deployed.resolve("lib/util.jar")));
|
||||
assertFalse(Files.exists(deployed.resolve("lib/old.jar")), "files the mod no longer has are removed");
|
||||
assertEquals("limit = 7\n", Files.readString(deployed.resolve("config.toml")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checksAGameModAgainstTheGameJar() throws IOException
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user