4 Commits
25 changed files with 436 additions and 104 deletions

No files matched your search

+2 -2
View File
@@ -15,12 +15,12 @@ jobs:
include:
# One entry per supported version; add older Steam version branches
# (e.g. pz_version 42.19, steam_branch 42.19) to keep them building.
- pz_version: "42.21"
- pz_version: "42"
steam_branch: public
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
+1 -2
View File
@@ -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
+9 -5
View File
@@ -1,12 +1,16 @@
# Publishes an image for every new Steam build of each supported Project Zomboid
# version. Immutable tags are never overwritten (see ci/release.sh).
# Publishes an image for every new Project Zomboid version (hotfixes included) of each
# matrix entry and every new ZomboidForge release; full version tags are never overwritten
# (see ci/release.sh).
# Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with
# package write access) and a runner with a Docker (or Podman) CLI.
name: release
on:
# Every 2.5 hours; cron cannot divide a day into 2.5-hour steps, so the gap
# from 22:30 to 00:00 is 1.5 hours.
schedule:
- cron: "0 */6 * * *"
- cron: "0 0,5,10,15,20 * * *"
- cron: "30 2,7,12,17,22 * * *"
workflow_dispatch:
jobs:
@@ -16,13 +20,13 @@ jobs:
fail-fast: false
matrix:
include:
- pz_version: "42.21"
- pz_version: "42"
steam_branch: public
latest: "true"
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
+38 -4
View File
@@ -6,6 +6,10 @@
# podman build --platform linux/amd64 -t zomboidforge .
# podman build --build-arg PZ_BRANCH=42.19 --build-arg PZ_VERSION=42.19 ...
#
# The stage game-version (--target game-version) downloads only the server jar of
# PZ_BRANCH and writes its game version to /game-version; ci/release.sh uses it to
# name the image before the full build.
#
# Build arguments:
# PZ_BRANCH Steam branch of app 380870: public, unstable, or a version branch (42.19, ...)
# PZ_VERSION Expected Project Zomboid version; the build fails when the downloaded
@@ -14,7 +18,8 @@
# files with steamcmd's newer copies
# FORGE_VERSION ZomboidForge version (jar manifest, image label); set by ci/release.sh.
# Default: 0.0.0-prerelease
# STEAM_BUILDID Image label only; set by ci/release.sh
# STEAM_BUILDID Image label; in the stage game-version it keeps the cached result until
# Steam publishes a new build. Set by ci/release.sh
# DISABLED_PATCHES Comma-separated simple class names of build-time patches to skip
# (debug builds only; ci/release.sh never sets it)
@@ -36,8 +41,8 @@ ARG STEAMCLIENT
COPY docker/install-server.sh /usr/local/bin/install-server
RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}"
# --- Stage 2: ZomboidForge build and server jar patching -----------------------
FROM docker.io/library/eclipse-temurin:25-jdk AS build
# --- Stage 2: ZomboidForge sources and Gradle -----------------------------------
FROM docker.io/library/eclipse-temurin:25-jdk AS sources
WORKDIR /src
# Gradle distribution download, cached independently of the sources.
@@ -53,6 +58,35 @@ COPY agent agent
COPY patcher patcher
COPY mod-tools mod-tools
COPY gradle-plugin gradle-plugin
# --- Game version of a Steam branch, from its server jar alone ------------------
# Not part of the image; built on its own by ci/release.sh.
FROM sources AS game-version
# DepotDownloader downloads single files of a depot; steamcmd only whole apps.
ADD --checksum=sha256:a999dec66b4850fc961bd50366696d23c2d0fad7b18790e6a5647b2f19097a53 \
https://github.com/SteamRE/DepotDownloader/releases/download/DepotDownloader_3.4.0/DepotDownloader-linux-x64.zip \
/opt/depotdownloader/depotdownloader.zip
RUN cd /opt/depotdownloader \
&& jar xf depotdownloader.zip \
&& chmod +x DepotDownloader \
&& rm depotdownloader.zip
# FORGE_VERSION only keeps Gradle from asking git (not in this stage) for the version.
ARG PZ_BRANCH
ARG STEAM_BUILDID
ARG FORGE_VERSION
RUN echo java/projectzomboid.jar > /tmp/files \
&& /opt/depotdownloader/DepotDownloader \
-app 380870 -depot 380871 -branch "${PZ_BRANCH}" -filelist /tmp/files -dir /pz \
&& ./gradlew --no-daemon --quiet \
-Ppz.jar=/pz/java/projectzomboid.jar \
-Pversion=${FORGE_VERSION} \
:patcher:printGameVersion > /game-version
# --- Stage 3: ZomboidForge build and server jar patching -----------------------
FROM sources AS build
COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar
# An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a
@@ -67,7 +101,7 @@ RUN ./gradlew --no-daemon \
${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \
build -x :gradle-plugin:test :patcher:patchServerJar
# --- Stage 3: runtime ------------------------------------------------------------
# --- Stage 4: runtime ------------------------------------------------------------
FROM docker.io/library/debian:trixie-slim
# ca-certificates: required by steamclient.so to connect to Steam.
+15 -4
View File
@@ -40,7 +40,7 @@ version = "1.2.0"
zomboidForge {
id = "shop"
entrypoint = "com.example.shop.ShopMod"
game("42.21") // only when the mod uses game classes
game("42") // only when the mod uses game classes
dependsOn("economy", "2.1") // other mods: id and minimum version
}
@@ -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` |
@@ -77,6 +78,10 @@ game jar for mods that declare `game` versions. Default settings go into
The plugin generates `META-INF/zomboidforge/mod.toml` from these settings; a hand-written one
fails the build.
Declare a minor version in `game(...)` only when the mod needs it. A mod declaring `"42.21"`
stops the server after an update to 42.22, while the server checks every game member a mod uses
against the running jar anyway.
### The game jar
Mods that declare `game` versions compile against `projectzomboid.jar`, which cannot be
@@ -100,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
@@ -216,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));
});
+4 -2
View File
@@ -22,8 +22,10 @@ podman build --platform linux/amd64 -t zomboidforge . # or: docker build ...
| `FORGE_VERSION` | `0.0.0-prerelease` | ZomboidForge version (jar manifest, image label). The build stage has no `git`, so the version is never read from a tag there; `ci/release.sh` passes it |
| `DISABLED_PATCHES` | | Comma-separated simple class names of build-time patches to skip (debug builds only), e.g. `IsoZombieVehiclePerformancePatch` |
Published images are tagged `<forge>-pz<pz>-build<steam buildid>` (immutable),
`<forge>-pz<pz>`, and `latest`.
Published images are tagged `<forge>-pz<major.minor.build>` (never overwritten),
`<forge>-pz<major.minor>` (the newest hotfix of that minor version), and `latest`. A new image
is built for every ZomboidForge release and every Project Zomboid version, hotfixes included:
the server only admits clients with the same version.
## Running
+5 -5
View File
@@ -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
+61 -26
View File
@@ -1,22 +1,29 @@
#!/usr/bin/env bash
#
# Builds the ZomboidForge image for one Project Zomboid version and optionally
# Builds the ZomboidForge image for the current build of a Steam branch and optionally
# publishes it. Published tags:
#
# <forge>-pz<pz>-build<steam_buildid> immutable; never overwritten
# <forge>-pz<pz> moves to the newest Steam build of that version
# latest only with LATEST=true
# <forge>-pz<major.minor.build> written once per ZomboidForge and Project Zomboid version
# <forge>-pz<major.minor> moves to the newest hotfix of that minor version
# latest only with LATEST=true
#
# <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".
# <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).
#
# Nothing is built when the immutable tag already exists in the registry.
# <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 ->
# 42.21.2) gets an image; a new Steam build with an unchanged version does not.
#
# Environment:
# IMAGE Image name without tag, e.g. git.security-command.org/overlord/zomboidforge
# PZ_BRANCH Steam branch. Default: public
# PZ_VERSION Expected Project Zomboid version. Default: pz.version in gradle.properties
# PZ_VERSION Accepted Project Zomboid versions ("42": every Build 42 version).
# Default: pz.version in gradle.properties
# PUBLISH true: push the tags (not for pre-release versions). Default: false (build and verify only)
# LATEST true: also push "latest". Default: false
# CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman
@@ -63,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
}
@@ -78,6 +88,22 @@ image_exists() {
"$(container_engine)" manifest inspect "${reference}" > /dev/null 2>&1
}
# Prints the game version of the branch's current server jar, e.g. 42.21.0. Downloads only
# the jar; the result stays cached until the build ID changes.
read_game_version() {
local build_id="$1"
local image
image="$("$(container_engine)" build --quiet \
--platform linux/amd64 \
--target game-version \
--build-arg "PZ_BRANCH=${PZ_BRANCH}" \
--build-arg "STEAM_BUILDID=${build_id}" \
"${REPO_ROOT}")"
"$(container_engine)" run --rm --entrypoint cat "${image}" /game-version
}
build_image() {
local reference="$1"
local forge_version="$2"
@@ -119,8 +145,9 @@ push_as() {
main() {
local forge_version
local publish="${REQUESTED_PUBLISH}"
local pz_version
local pz_prefix
local build_id
local game_version
forge_version="$(release_tag_version)"
if [[ -z "${forge_version}" ]]; then
@@ -132,31 +159,39 @@ main() {
log "${forge_version} is a pre-release version; nothing will be published."
fi
pz_version="${PZ_VERSION:-$(gradle_property pz.version)}"
pz_prefix="${PZ_VERSION:-$(gradle_property pz.version)}"
build_id="$("${REPO_ROOT}/ci/steam-buildid.sh" "${PZ_BRANCH}")"
game_version="$(read_game_version "${build_id}")"
log "ZomboidForge ${forge_version}, Project Zomboid ${game_version}, Steam branch ${PZ_BRANCH} build ${build_id}"
local immutable_tag="${IMAGE}:${forge_version}-pz${pz_version}-build${build_id}"
local version_tag="${IMAGE}:${forge_version}-pz${pz_version}"
log "ZomboidForge ${forge_version}, Project Zomboid ${pz_version}, Steam branch ${PZ_BRANCH} build ${build_id}"
# Checked here as well as by the patcher, to fail before the full download.
if [[ "${game_version}" != "${pz_prefix}" && "${game_version}" != "${pz_prefix}."* ]]; then
log "Steam branch ${PZ_BRANCH} has Project Zomboid ${game_version}; the build accepts ${pz_prefix}."
exit 1
fi
if [[ "${publish}" == true ]] && image_exists "${immutable_tag}"; then
log "${immutable_tag} is already published; nothing to do."
local version_tag="${IMAGE}:${forge_version}-pz${game_version}"
# 42.21.2 -> 42.21
local minor_tag="${IMAGE}:${forge_version}-pz${game_version%.*}"
if [[ "${publish}" == true ]] && image_exists "${version_tag}"; then
log "${version_tag} is already published; nothing to do."
return
fi
build_image "${immutable_tag}" "${forge_version}" "${pz_version}" "${build_id}"
verify_build_id "${immutable_tag}" "${build_id}"
build_image "${version_tag}" "${forge_version}" "${game_version}" "${build_id}"
verify_build_id "${version_tag}" "${build_id}"
if [[ "${publish}" != true ]]; then
log "Built ${immutable_tag} (not published)"
log "Built ${version_tag} (not published)"
return
fi
"$(container_engine)" push "${immutable_tag}"
log "Pushed ${immutable_tag}"
push_as "${immutable_tag}" "${version_tag}"
"$(container_engine)" push "${version_tag}"
log "Pushed ${version_tag}"
push_as "${version_tag}" "${minor_tag}"
if [[ "${LATEST}" == true ]]; then
push_as "${immutable_tag}" "${IMAGE}:latest"
push_as "${version_tag}" "${IMAGE}:latest"
fi
}
@@ -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(); }
}
/**
@@ -86,8 +86,8 @@ public final class ServerHooks
*/
public static void onTick()
{
try { ForgeInstance.FORGE.tick(); }
catch (RuntimeException e) { e.printStackTrace(); }
try { ForgeInstance.FORGE.tick(); }
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(); }
}
}
@@ -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); }
try { mod.mod().onServerStarted(); }
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", t); }
}
}
@@ -205,18 +208,24 @@ 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;
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); }
try
{
for (ModLoader.LoadedMod mod : this.mods.reversed()) {
try { mod.mod().onStopping(); }
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", t); }
}
}
finally
{
this.stopMods(this.settings.shutdownTimeout());
}
this.stopMods(this.settings.shutdownTimeout());
}
/**
@@ -79,25 +79,30 @@ public final class MainThreadQueue
int index = count == 0 ? 0 : this.next % count;
int empty = 0;
while (empty < count && !this.closed)
try
{
ModQueue queue = queues[index];
index = (index + 1) % count;
while (empty < count && !this.closed)
{
ModQueue queue = queues[index];
index = (index + 1) % count;
Task task = queue.tasks.poll();
Task task = queue.tasks.poll();
if (task == null) {
empty++;
continue;
if (task == null) {
empty++;
continue;
}
empty = 0;
queue.run(task.action());
if (System.nanoTime() >= deadline) break;
}
empty = 0;
queue.run(task.action());
if (System.nanoTime() >= deadline) break;
}
this.next = index;
finally
{
this.next = index;
}
}
/** Rejects further tasks and cancels the queued ones (their futures are cancelled). Any thread. */
@@ -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()
{
+16
View File
@@ -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();
@@ -60,23 +78,28 @@ public abstract class RunServer extends DefaultTask
@TaskAction
public void run() throws IOException
{
String engine = Executables.containerEngine(this.getContainerEngine().getOrNull());
String name = this.getContainerName().get();
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)
{
@@ -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();
@@ -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());
});
@@ -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
{
+2 -2
View File
@@ -2,8 +2,8 @@ group=dev.overlord.zomboidforge
# Project Zomboid version the build targets. Selects compat/b<major>/, and
# :patcher:patchServerJar fails when the server jar reports another version.
# "42.21" matches every 42.21.x build; "42.21.0" matches exactly.
pz.version=42.21
# "42" matches every Build 42 version, "42.21" every 42.21.x build, "42.21.0" exactly.
pz.version=42
# Vanilla dedicated server jar used for compilation and patching.
# Default: lib/server/java/projectzomboid.jar (relative to the root project).
+14
View File
@@ -60,3 +60,17 @@ tasks.register<JavaExec>("patchServerJar") {
)
})
}
// Used by ci/release.sh (Dockerfile stage game-version) to name the image before the full build.
tasks.register<JavaExec>("printGameVersion") {
description = "Prints the game version of the server jar (pz.jar)."
group = "help"
val serverJar = projectZomboid.serverJar
classpath = sourceSets.main.get().runtimeClasspath
mainClass = "dev.overlord.zomboidforge.patcher.GameVersionReader"
argumentProviders.add(CommandLineArgumentProvider {
listOf(serverJar.get().asFile.absolutePath)
})
}
@@ -13,6 +13,8 @@ import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@@ -32,6 +34,18 @@ public final class GameVersionReader
private GameVersionReader() {}
/** Usage: {@code GameVersionReader <server.jar>}. Prints the jar's game version, e.g. {@code 42.21.0}. */
static void main(String[] args) throws IOException
{
if (args.length != 1)
{
System.err.println("Usage: GameVersionReader <server.jar>");
System.exit(2);
}
System.out.println(JarPatcher.readGameVersion(Path.of(args[0])));
}
public static GameVersion read(byte[] coreClass)
{
ClassNode core = new ClassNode();