Compare commits
5 Commits
master
...
99d7e5fdc9
| Author | SHA1 | Date | |
|---|---|---|---|
| 99d7e5fdc9 | |||
| df2a826624 | |||
| 863918a611 | |||
| 98fea4e855 | |||
| 96f3a5abc1 |
@@ -13,15 +13,10 @@ services:
|
|||||||
DB_NAME: /data/db/acc.db
|
DB_NAME: /data/db/acc.db
|
||||||
STEAMCMD_LINUX_PATH: /usr/games/steamcmd
|
STEAMCMD_LINUX_PATH: /usr/games/steamcmd
|
||||||
PORT_POOL_MIN: "9600"
|
PORT_POOL_MIN: "9600"
|
||||||
PORT_POOL_MAX: "9699"
|
PORT_POOL_MAX: "9700"
|
||||||
ACC_IMAGE: acc-wine:latest
|
ACC_IMAGE: acc-wine:latest
|
||||||
ACC_SERVERS_PATH: /data/servers
|
ACC_SERVERS_PATH: /data/servers
|
||||||
ACC_SERVERS_HOST_PATH: /opt/acc-servers
|
ACC_SERVERS_HOST_PATH: /opt/acc-servers
|
||||||
# ACC_CPUSET: Pin all ACC containers to specific CPU cores (e.g., "0-11").
|
|
||||||
# Reduces simulation timing misses ("not enough CPU power" in accServer.exe).
|
|
||||||
# Set the CPU governor to 'performance' on the host for best results:
|
|
||||||
# echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
|
|
||||||
# ACC_CPUSET: "0-11"
|
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
@@ -1,32 +1,24 @@
|
|||||||
# ACC Server container: Wine Staging + accServer.exe
|
# ACC Server container: Wine + accServer.exe
|
||||||
# Game files are bind-mounted from the host at /acc/game.
|
# Game files are mounted read-only from the shared acc-game volume.
|
||||||
|
# Per-server config files are mounted read-write from the manager's config volume.
|
||||||
FROM debian:bookworm-slim
|
FROM debian:bookworm-slim
|
||||||
|
|
||||||
# Install Wine Staging from WineHQ (newer than Debian's packages, includes fsync support).
|
# Install Wine, Xvfb (headless display for Wine), and minimal runtime deps.
|
||||||
RUN dpkg --add-architecture i386 && \
|
RUN dpkg --add-architecture i386 && \
|
||||||
apt-get update && \
|
apt-get update && \
|
||||||
apt-get install -y --no-install-recommends wget ca-certificates && \
|
apt-get install -y --no-install-recommends \
|
||||||
mkdir -pm755 /etc/apt/keyrings && \
|
wine \
|
||||||
wget -q -O /etc/apt/keyrings/winehq-archive.key https://dl.winehq.org/wine-builds/winehq.key && \
|
wine32 \
|
||||||
echo "deb [arch=amd64,i386 signed-by=/etc/apt/keyrings/winehq-archive.key] https://dl.winehq.org/wine-builds/debian/ bookworm main" \
|
wine64 \
|
||||||
> /etc/apt/sources.list.d/winehq.list && \
|
xvfb \
|
||||||
apt-get update && \
|
ca-certificates \
|
||||||
apt-get install -y --install-recommends \
|
|
||||||
winehq-staging \
|
|
||||||
tcpdump \
|
|
||||||
&& \
|
&& \
|
||||||
rm -rf /var/lib/apt/lists/*
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Create a non-root user for running the server.
|
||||||
|
RUN useradd -ms /bin/bash accserver
|
||||||
|
|
||||||
WORKDIR /root
|
WORKDIR /home/accserver
|
||||||
|
|
||||||
ENV WINEARCH=win64
|
|
||||||
ENV WINEPREFIX=/root/.wine
|
|
||||||
ENV WINEDEBUG=-all
|
|
||||||
# fsync uses Linux futex2 for Wine synchronization — reduces timing jitter under load.
|
|
||||||
# Falls back to esync (eventfd) if fsync is unavailable; falls back to standard if neither.
|
|
||||||
ENV WINEFSYNC=1
|
|
||||||
ENV WINEESYNC=1
|
|
||||||
|
|
||||||
# Copy entrypoint script.
|
# Copy entrypoint script.
|
||||||
COPY entrypoint.sh /entrypoint.sh
|
COPY entrypoint.sh /entrypoint.sh
|
||||||
@@ -35,6 +27,13 @@ RUN chmod +x /entrypoint.sh
|
|||||||
# Bind-mounted by DockerRuntime.Create: per-server game install (rw)
|
# Bind-mounted by DockerRuntime.Create: per-server game install (rw)
|
||||||
VOLUME ["/acc/game"]
|
VOLUME ["/acc/game"]
|
||||||
|
|
||||||
|
# Default server port — overridden at runtime via SERVER_PORT env var.
|
||||||
ENV SERVER_PORT=9600
|
ENV SERVER_PORT=9600
|
||||||
|
ENV WINEDEBUG=-all
|
||||||
|
ENV DISPLAY=:99
|
||||||
|
|
||||||
|
EXPOSE ${SERVER_PORT}/tcp
|
||||||
|
EXPOSE ${SERVER_PORT}/udp
|
||||||
|
|
||||||
|
USER accserver
|
||||||
ENTRYPOINT ["/entrypoint.sh"]
|
ENTRYPOINT ["/entrypoint.sh"]
|
||||||
|
|||||||
@@ -1,26 +1,16 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
# Wine Staging looks for PulseAudio via XDG_RUNTIME_DIR. There is no audio
|
Xvfb :99 -screen 0 1024x768x16 &
|
||||||
# in this container, so point it at a valid (empty) directory to silence
|
XVFB_PID=$!
|
||||||
# the "XDG_RUNTIME_DIR is invalid" errors.
|
|
||||||
export XDG_RUNTIME_DIR=/tmp/runtime-${SERVER_PORT}
|
|
||||||
mkdir -p "${XDG_RUNTIME_DIR}"
|
|
||||||
|
|
||||||
# Use Wine's headless (null) display driver — accServer.exe has no GUI so
|
|
||||||
# there is no need for Xvfb at all. This avoids the X11 client limit and
|
|
||||||
# removes the Xvfb process entirely.
|
|
||||||
export DISPLAY=
|
|
||||||
export WINEDLLOVERRIDES="winex11.drv="
|
|
||||||
|
|
||||||
cleanup() {
|
cleanup() {
|
||||||
echo "Stopping ACC server..."
|
echo "Stopping ACC server..."
|
||||||
|
kill $XVFB_PID 2>/dev/null || true
|
||||||
}
|
}
|
||||||
trap cleanup SIGTERM SIGINT
|
trap cleanup SIGTERM SIGINT
|
||||||
|
|
||||||
mkdir -p /acc/game/log
|
|
||||||
|
|
||||||
echo "Starting ACC server on port ${SERVER_PORT}..."
|
echo "Starting ACC server on port ${SERVER_PORT}..."
|
||||||
|
|
||||||
cd /acc/game
|
exec wine /acc/game/accServer.exe \
|
||||||
exec wine /acc/game/accServer.exe
|
-port "${SERVER_PORT}"
|
||||||
|
|||||||
13
go.mod
13
go.mod
@@ -3,7 +3,7 @@ module acc-server-manager
|
|||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/docker/docker v27.5.1+incompatible
|
github.com/docker/docker v24.0.9+incompatible
|
||||||
github.com/docker/go-connections v0.6.0
|
github.com/docker/go-connections v0.6.0
|
||||||
github.com/gofiber/fiber/v2 v2.52.8
|
github.com/gofiber/fiber/v2 v2.52.8
|
||||||
github.com/gofiber/swagger v1.1.0
|
github.com/gofiber/swagger v1.1.0
|
||||||
@@ -26,14 +26,9 @@ require (
|
|||||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||||
github.com/Microsoft/go-winio v0.4.21 // indirect
|
github.com/Microsoft/go-winio v0.4.21 // indirect
|
||||||
github.com/andybalholm/brotli v1.1.0 // indirect
|
github.com/andybalholm/brotli v1.1.0 // indirect
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
|
||||||
github.com/distribution/reference v0.6.0 // indirect
|
|
||||||
github.com/docker/distribution v2.7.1+incompatible // indirect
|
github.com/docker/distribution v2.7.1+incompatible // indirect
|
||||||
github.com/docker/go-units v0.5.0 // indirect
|
github.com/docker/go-units v0.5.0 // indirect
|
||||||
github.com/fasthttp/websocket v1.5.3 // indirect
|
github.com/fasthttp/websocket v1.5.3 // indirect
|
||||||
github.com/felixge/httpsnoop v1.0.4 // indirect
|
|
||||||
github.com/go-logr/logr v1.4.3 // indirect
|
|
||||||
github.com/go-logr/stdr v1.2.2 // indirect
|
|
||||||
github.com/go-openapi/jsonpointer v0.21.0 // indirect
|
github.com/go-openapi/jsonpointer v0.21.0 // indirect
|
||||||
github.com/go-openapi/jsonreference v0.21.0 // indirect
|
github.com/go-openapi/jsonreference v0.21.0 // indirect
|
||||||
github.com/go-openapi/spec v0.21.0 // indirect
|
github.com/go-openapi/spec v0.21.0 // indirect
|
||||||
@@ -49,7 +44,6 @@ require (
|
|||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||||
github.com/moby/docker-image-spec v1.3.1 // indirect
|
|
||||||
github.com/moby/term v0.5.2 // indirect
|
github.com/moby/term v0.5.2 // indirect
|
||||||
github.com/morikuni/aec v1.1.0 // indirect
|
github.com/morikuni/aec v1.1.0 // indirect
|
||||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||||
@@ -62,11 +56,6 @@ require (
|
|||||||
github.com/swaggo/files/v2 v2.0.0 // indirect
|
github.com/swaggo/files/v2 v2.0.0 // indirect
|
||||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||||
github.com/valyala/tcplisten v1.0.0 // indirect
|
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect
|
|
||||||
go.opentelemetry.io/otel v1.42.0 // indirect
|
|
||||||
go.opentelemetry.io/otel/metric v1.42.0 // indirect
|
|
||||||
go.opentelemetry.io/otel/trace v1.42.0 // indirect
|
|
||||||
golang.org/x/sys v0.41.0 // indirect
|
golang.org/x/sys v0.41.0 // indirect
|
||||||
golang.org/x/time v0.9.0 // indirect
|
golang.org/x/time v0.9.0 // indirect
|
||||||
golang.org/x/tools v0.33.0 // indirect
|
golang.org/x/tools v0.33.0 // indirect
|
||||||
|
|||||||
25
go.sum
25
go.sum
@@ -6,31 +6,18 @@ github.com/Microsoft/go-winio v0.4.21 h1:+6mVbXh4wPzUrl1COX9A+ZCvEpYsOBZ6/+kwDnv
|
|||||||
github.com/Microsoft/go-winio v0.4.21/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84=
|
github.com/Microsoft/go-winio v0.4.21/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84=
|
||||||
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
|
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
|
||||||
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
|
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
|
||||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
|
||||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
|
||||||
github.com/docker/distribution v2.7.1+incompatible h1:a5mlkVzth6W5A4fOsS3D2EO5BUmsJpcB+cRlLU7cSug=
|
github.com/docker/distribution v2.7.1+incompatible h1:a5mlkVzth6W5A4fOsS3D2EO5BUmsJpcB+cRlLU7cSug=
|
||||||
github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
|
github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
|
||||||
github.com/docker/docker v24.0.9+incompatible h1:HPGzNmwfLZWdxHqK9/II92pyi1EpYKsAqcl4G0Of9v0=
|
github.com/docker/docker v24.0.9+incompatible h1:HPGzNmwfLZWdxHqK9/II92pyi1EpYKsAqcl4G0Of9v0=
|
||||||
github.com/docker/docker v24.0.9+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
github.com/docker/docker v24.0.9+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||||
github.com/docker/docker v27.5.1+incompatible h1:4PYU5dnBYqRQi0294d1FBECqT9ECWeQAIfE8q4YnPY8=
|
|
||||||
github.com/docker/docker v27.5.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
|
||||||
github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pMmjSD94=
|
github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pMmjSD94=
|
||||||
github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vmaMAntpSFH5BFKE=
|
github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vmaMAntpSFH5BFKE=
|
||||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||||
github.com/fasthttp/websocket v1.5.3 h1:TPpQuLwJYfd4LJPXvHDYPMFWbLjsT91n3GpWtCQtdek=
|
github.com/fasthttp/websocket v1.5.3 h1:TPpQuLwJYfd4LJPXvHDYPMFWbLjsT91n3GpWtCQtdek=
|
||||||
github.com/fasthttp/websocket v1.5.3/go.mod h1:46gg/UBmTU1kUaTcwQXpUxtRwG2PvIZYeA8oL6vF3Fs=
|
github.com/fasthttp/websocket v1.5.3/go.mod h1:46gg/UBmTU1kUaTcwQXpUxtRwG2PvIZYeA8oL6vF3Fs=
|
||||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
|
||||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
|
||||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
|
||||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
|
||||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
|
||||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
|
||||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
|
||||||
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
|
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
|
||||||
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
|
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
|
||||||
github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
|
github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
|
||||||
@@ -80,8 +67,6 @@ github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6T
|
|||||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
|
||||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
|
||||||
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
||||||
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
|
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
|
||||||
github.com/morikuni/aec v1.1.0 h1:vBBl0pUnvi/Je71dsRrhMBtreIqNMYErSAbEeb8jrXQ=
|
github.com/morikuni/aec v1.1.0 h1:vBBl0pUnvi/Je71dsRrhMBtreIqNMYErSAbEeb8jrXQ=
|
||||||
@@ -119,16 +104,6 @@ github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVS
|
|||||||
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
||||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=
|
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=
|
|
||||||
go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=
|
|
||||||
go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=
|
|
||||||
go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=
|
|
||||||
go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=
|
|
||||||
go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=
|
|
||||||
go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=
|
|
||||||
go.uber.org/dig v1.17.1 h1:Tga8Lz8PcYNsWsyHMZ1Vm0OQOUaJNDyvPImgbAu9YSc=
|
go.uber.org/dig v1.17.1 h1:Tga8Lz8PcYNsWsyHMZ1Vm0OQOUaJNDyvPImgbAu9YSc=
|
||||||
go.uber.org/dig v1.17.1/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE=
|
go.uber.org/dig v1.17.1/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
|||||||
@@ -34,10 +34,6 @@ func Init(di *dig.Container, app *fiber.App) {
|
|||||||
WebSocket: groups.Group("/ws"),
|
WebSocket: groups.Group("/ws"),
|
||||||
Leaderboard: serverIdGroup.Group("/leaderboard"),
|
Leaderboard: serverIdGroup.Group("/leaderboard"),
|
||||||
Steam: groups.Group("/steam"),
|
Steam: groups.Group("/steam"),
|
||||||
ActivityLog: serverIdGroup.Group("/activity-log"),
|
|
||||||
Groups: groups,
|
|
||||||
Log: serverIdGroup.Group("/log"),
|
|
||||||
Presets: groups.Group("/presets"),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
accessKeyMiddleware := middleware.NewAccessKeyMiddleware()
|
accessKeyMiddleware := middleware.NewAccessKeyMiddleware()
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
package controller
|
|
||||||
|
|
||||||
import (
|
|
||||||
"acc-server-manager/local/middleware"
|
|
||||||
"acc-server-manager/local/model"
|
|
||||||
"acc-server-manager/local/service"
|
|
||||||
"acc-server-manager/local/utl/common"
|
|
||||||
"acc-server-manager/local/utl/error_handler"
|
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ActivityLogController struct {
|
|
||||||
service *service.ActivityLogService
|
|
||||||
errorHandler *error_handler.ControllerErrorHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewActivityLogController(as *service.ActivityLogService, routeGroups *common.RouteGroups, auth *middleware.AuthMiddleware) *ActivityLogController {
|
|
||||||
ac := &ActivityLogController{
|
|
||||||
service: as,
|
|
||||||
errorHandler: error_handler.NewControllerErrorHandler(),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Global activity log: GET /activity-log (admin use)
|
|
||||||
routeGroups.Groups.Group("/activity-log").Use(auth.Authenticate).Get("/", ac.GetAllLogs)
|
|
||||||
|
|
||||||
return ac
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetAllLogs returns activity logs across all servers (admin).
|
|
||||||
//
|
|
||||||
// @Summary Return all activity logs
|
|
||||||
// @Tags ActivityLog
|
|
||||||
// @Success 200 {array} model.ActivityLog
|
|
||||||
// @Router /activity-log [get]
|
|
||||||
func (ac *ActivityLogController) GetAllLogs(c *fiber.Ctx) error {
|
|
||||||
var filter model.ActivityLogFilter
|
|
||||||
if err := common.ParseQueryFilter(c, &filter); err != nil {
|
|
||||||
return ac.errorHandler.HandleValidationError(c, err, "query_filter")
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := ac.service.GetAll(c.UserContext(), &filter)
|
|
||||||
if err != nil {
|
|
||||||
return ac.errorHandler.HandleServiceError(c, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.JSON(result)
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,6 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"acc-server-manager/local/middleware"
|
"acc-server-manager/local/middleware"
|
||||||
"acc-server-manager/local/model"
|
|
||||||
"acc-server-manager/local/service"
|
"acc-server-manager/local/service"
|
||||||
"acc-server-manager/local/utl/common"
|
"acc-server-manager/local/utl/common"
|
||||||
"acc-server-manager/local/utl/error_handler"
|
"acc-server-manager/local/utl/error_handler"
|
||||||
@@ -35,7 +34,6 @@ func NewConfigController(as *service.ConfigService, routeGroups *common.RouteGro
|
|||||||
|
|
||||||
configGroup := routeGroups.Config
|
configGroup := routeGroups.Config
|
||||||
configGroup.Use(auth.Authenticate)
|
configGroup.Use(auth.Authenticate)
|
||||||
configGroup.Patch("/", ac.UpdateAllConfigs)
|
|
||||||
configGroup.Put("/:file", ac.UpdateConfig)
|
configGroup.Put("/:file", ac.UpdateConfig)
|
||||||
configGroup.Get("/:file", ac.GetConfig)
|
configGroup.Get("/:file", ac.GetConfig)
|
||||||
configGroup.Get("/", ac.GetConfigs)
|
configGroup.Get("/", ac.GetConfigs)
|
||||||
@@ -43,54 +41,6 @@ func NewConfigController(as *service.ConfigService, routeGroups *common.RouteGro
|
|||||||
return ac
|
return ac
|
||||||
}
|
}
|
||||||
|
|
||||||
// updateAllConfigs updates all configuration files
|
|
||||||
//
|
|
||||||
// @Summary Bulk update all server configuration files
|
|
||||||
// @Description Update multiple ACC server configuration files in one request. Null or omitted sections are skipped.
|
|
||||||
// @Tags Server Configuration
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param id path string true "Server ID (UUID format)"
|
|
||||||
// @Param restart query bool false "Restart the server after update"
|
|
||||||
// @Param override query bool false "Override instead of merging with existing config"
|
|
||||||
// @Param content body model.ConfigurationsUpdateRequest true "Configuration sections to update (null sections are skipped)"
|
|
||||||
// @Success 200 {array} model.Config "List of updated config audit records"
|
|
||||||
// @Failure 400 {object} error_handler.ErrorResponse "Invalid request or JSON format"
|
|
||||||
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
|
|
||||||
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
|
|
||||||
// @Failure 404 {object} error_handler.ErrorResponse "Server not found"
|
|
||||||
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Router /server/{id}/config [patch]
|
|
||||||
func (ac *ConfigController) UpdateAllConfigs(c *fiber.Ctx) error {
|
|
||||||
restart := c.QueryBool("restart")
|
|
||||||
serverID := c.Params("id")
|
|
||||||
|
|
||||||
if _, err := uuid.Parse(serverID); err != nil {
|
|
||||||
return ac.errorHandler.HandleUUIDError(c, "server ID")
|
|
||||||
}
|
|
||||||
|
|
||||||
c.Locals("serverId", serverID)
|
|
||||||
|
|
||||||
var req model.ConfigurationsUpdateRequest
|
|
||||||
if err := c.BodyParser(&req); err != nil {
|
|
||||||
return ac.errorHandler.HandleParsingError(c, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
configs, err := ac.service.UpdateAllConfigs(c, &req)
|
|
||||||
if err != nil {
|
|
||||||
return ac.errorHandler.HandleServiceError(c, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if restart {
|
|
||||||
if _, err := ac.apiService.ServiceControlRestartServer(c); err != nil {
|
|
||||||
logging.ErrorWithContext("CONFIG_RESTART", "Failed to restart server after bulk config update: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.JSON(configs)
|
|
||||||
}
|
|
||||||
|
|
||||||
// updateConfig returns Config
|
// updateConfig returns Config
|
||||||
//
|
//
|
||||||
// @Summary Update server configuration file
|
// @Summary Update server configuration file
|
||||||
|
|||||||
@@ -1,246 +0,0 @@
|
|||||||
package controller
|
|
||||||
|
|
||||||
import (
|
|
||||||
"acc-server-manager/local/middleware"
|
|
||||||
"acc-server-manager/local/model"
|
|
||||||
"acc-server-manager/local/service"
|
|
||||||
"acc-server-manager/local/utl/common"
|
|
||||||
"acc-server-manager/local/utl/error_handler"
|
|
||||||
"acc-server-manager/local/utl/logging"
|
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ConfigPresetController struct {
|
|
||||||
service *service.ConfigPresetService
|
|
||||||
apiService *service.ServiceControlService
|
|
||||||
errorHandler *error_handler.ControllerErrorHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewConfigPresetController initializes ConfigPresetController.
|
|
||||||
func NewConfigPresetController(s *service.ConfigPresetService, apiService *service.ServiceControlService, routeGroups *common.RouteGroups, auth *middleware.AuthMiddleware) *ConfigPresetController {
|
|
||||||
c := &ConfigPresetController{
|
|
||||||
service: s,
|
|
||||||
apiService: apiService,
|
|
||||||
errorHandler: error_handler.NewControllerErrorHandler(),
|
|
||||||
}
|
|
||||||
|
|
||||||
presetRoutes := routeGroups.Presets
|
|
||||||
presetRoutes.Use(auth.Authenticate)
|
|
||||||
presetRoutes.Get("/", auth.HasPermission(model.PresetView), c.ListPresets)
|
|
||||||
presetRoutes.Post("/", auth.HasPermission(model.PresetCreate), c.CreatePreset)
|
|
||||||
presetRoutes.Get("/:presetId", auth.HasPermission(model.PresetView), c.GetPreset)
|
|
||||||
presetRoutes.Put("/:presetId", auth.HasPermission(model.PresetUpdate), c.UpdatePreset)
|
|
||||||
presetRoutes.Delete("/:presetId", auth.HasPermission(model.PresetDelete), c.DeletePreset)
|
|
||||||
|
|
||||||
configRoutes := routeGroups.Config
|
|
||||||
configRoutes.Post("/presets/:presetId/apply", auth.HasPermission(model.ConfigUpdate), c.ApplyPreset)
|
|
||||||
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListPresets returns all config presets.
|
|
||||||
//
|
|
||||||
// @Summary List config presets
|
|
||||||
// @Description Get a list of all saved configuration presets
|
|
||||||
// @Tags Config Presets
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param name query string false "Filter by preset name (partial match)"
|
|
||||||
// @Success 200 {array} model.ConfigPreset "List of presets"
|
|
||||||
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
|
|
||||||
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
|
|
||||||
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Router /presets [get]
|
|
||||||
func (c *ConfigPresetController) ListPresets(ctx *fiber.Ctx) error {
|
|
||||||
var filter model.ConfigPresetFilter
|
|
||||||
if err := common.ParseQueryFilter(ctx, &filter); err != nil {
|
|
||||||
return c.errorHandler.HandleParsingError(ctx, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
presets, err := c.service.ListPresets(ctx.UserContext(), &filter)
|
|
||||||
if err != nil {
|
|
||||||
return c.errorHandler.HandleServiceError(ctx, err)
|
|
||||||
}
|
|
||||||
return ctx.JSON(presets)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPreset returns a single config preset by ID.
|
|
||||||
//
|
|
||||||
// @Summary Get config preset
|
|
||||||
// @Description Retrieve a single configuration preset by ID
|
|
||||||
// @Tags Config Presets
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param presetId path string true "Preset ID (UUID format)"
|
|
||||||
// @Success 200 {object} model.ConfigPreset "Preset"
|
|
||||||
// @Failure 400 {object} error_handler.ErrorResponse "Invalid preset ID"
|
|
||||||
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
|
|
||||||
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
|
|
||||||
// @Failure 404 {object} error_handler.ErrorResponse "Preset not found"
|
|
||||||
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Router /presets/{presetId} [get]
|
|
||||||
func (c *ConfigPresetController) GetPreset(ctx *fiber.Ctx) error {
|
|
||||||
id, err := uuid.Parse(ctx.Params("presetId"))
|
|
||||||
if err != nil {
|
|
||||||
return c.errorHandler.HandleUUIDError(ctx, "preset ID")
|
|
||||||
}
|
|
||||||
|
|
||||||
preset, err := c.service.GetPreset(ctx.UserContext(), id)
|
|
||||||
if err != nil {
|
|
||||||
return c.errorHandler.HandleServiceError(ctx, err)
|
|
||||||
}
|
|
||||||
return ctx.JSON(preset)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreatePreset creates a new config preset.
|
|
||||||
//
|
|
||||||
// @Summary Create config preset
|
|
||||||
// @Description Save a new configuration preset with one or more ACC config sections
|
|
||||||
// @Tags Config Presets
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param content body model.ConfigPresetCreateRequest true "Preset data"
|
|
||||||
// @Success 201 {object} model.ConfigPreset "Created preset"
|
|
||||||
// @Failure 400 {object} error_handler.ErrorResponse "Invalid request"
|
|
||||||
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
|
|
||||||
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
|
|
||||||
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Router /presets [post]
|
|
||||||
func (c *ConfigPresetController) CreatePreset(ctx *fiber.Ctx) error {
|
|
||||||
var req model.ConfigPresetCreateRequest
|
|
||||||
if err := ctx.BodyParser(&req); err != nil {
|
|
||||||
return c.errorHandler.HandleParsingError(ctx, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
actorID, _ := ctx.Locals("userID").(string)
|
|
||||||
actorUsername, _ := ctx.Locals("actorUsername").(string)
|
|
||||||
if actorUsername == "" {
|
|
||||||
actorUsername = "system"
|
|
||||||
}
|
|
||||||
|
|
||||||
preset, err := c.service.CreatePreset(ctx.UserContext(), &req, actorID, actorUsername)
|
|
||||||
if err != nil {
|
|
||||||
return c.errorHandler.HandleServiceError(ctx, err)
|
|
||||||
}
|
|
||||||
return ctx.Status(fiber.StatusCreated).JSON(preset)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdatePreset updates an existing config preset.
|
|
||||||
//
|
|
||||||
// @Summary Update config preset
|
|
||||||
// @Description Update name, description, or any config sections of an existing preset
|
|
||||||
// @Tags Config Presets
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param presetId path string true "Preset ID (UUID format)"
|
|
||||||
// @Param content body model.ConfigPresetUpdateRequest true "Fields to update (omit to keep existing)"
|
|
||||||
// @Success 200 {object} model.ConfigPreset "Updated preset"
|
|
||||||
// @Failure 400 {object} error_handler.ErrorResponse "Invalid request or preset ID"
|
|
||||||
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
|
|
||||||
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
|
|
||||||
// @Failure 404 {object} error_handler.ErrorResponse "Preset not found"
|
|
||||||
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Router /presets/{presetId} [put]
|
|
||||||
func (c *ConfigPresetController) UpdatePreset(ctx *fiber.Ctx) error {
|
|
||||||
id, err := uuid.Parse(ctx.Params("presetId"))
|
|
||||||
if err != nil {
|
|
||||||
return c.errorHandler.HandleUUIDError(ctx, "preset ID")
|
|
||||||
}
|
|
||||||
|
|
||||||
var req model.ConfigPresetUpdateRequest
|
|
||||||
if err := ctx.BodyParser(&req); err != nil {
|
|
||||||
return c.errorHandler.HandleParsingError(ctx, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
preset, err := c.service.UpdatePreset(ctx.UserContext(), id, &req)
|
|
||||||
if err != nil {
|
|
||||||
return c.errorHandler.HandleServiceError(ctx, err)
|
|
||||||
}
|
|
||||||
return ctx.JSON(preset)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeletePreset deletes a config preset.
|
|
||||||
//
|
|
||||||
// @Summary Delete config preset
|
|
||||||
// @Description Permanently delete a configuration preset
|
|
||||||
// @Tags Config Presets
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param presetId path string true "Preset ID (UUID format)"
|
|
||||||
// @Success 204 "No Content"
|
|
||||||
// @Failure 400 {object} error_handler.ErrorResponse "Invalid preset ID"
|
|
||||||
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
|
|
||||||
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
|
|
||||||
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Router /presets/{presetId} [delete]
|
|
||||||
func (c *ConfigPresetController) DeletePreset(ctx *fiber.Ctx) error {
|
|
||||||
id, err := uuid.Parse(ctx.Params("presetId"))
|
|
||||||
if err != nil {
|
|
||||||
return c.errorHandler.HandleUUIDError(ctx, "preset ID")
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := c.service.DeletePreset(ctx.UserContext(), id); err != nil {
|
|
||||||
return c.errorHandler.HandleServiceError(ctx, err)
|
|
||||||
}
|
|
||||||
return ctx.SendStatus(fiber.StatusNoContent)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ApplyPreset applies a saved preset to a server's config files.
|
|
||||||
//
|
|
||||||
// @Summary Apply config preset to server
|
|
||||||
// @Description Apply a saved configuration preset to an ACC server, writing only the sections stored in the preset
|
|
||||||
// @Tags Server Configuration
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param id path string true "Server ID (UUID format)"
|
|
||||||
// @Param presetId path string true "Preset ID (UUID format)"
|
|
||||||
// @Param restart query bool false "Restart the server after applying the preset"
|
|
||||||
// @Success 200 {array} model.Config "List of updated config audit records"
|
|
||||||
// @Failure 400 {object} error_handler.ErrorResponse "Invalid server or preset ID"
|
|
||||||
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
|
|
||||||
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
|
|
||||||
// @Failure 404 {object} error_handler.ErrorResponse "Server or preset not found"
|
|
||||||
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Router /server/{id}/config/presets/{presetId}/apply [post]
|
|
||||||
func (c *ConfigPresetController) ApplyPreset(ctx *fiber.Ctx) error {
|
|
||||||
restart := ctx.QueryBool("restart")
|
|
||||||
serverID := ctx.Params("id")
|
|
||||||
|
|
||||||
if _, err := uuid.Parse(serverID); err != nil {
|
|
||||||
return c.errorHandler.HandleUUIDError(ctx, "server ID")
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.Locals("serverId", serverID)
|
|
||||||
|
|
||||||
presetID, err := uuid.Parse(ctx.Params("presetId"))
|
|
||||||
if err != nil {
|
|
||||||
return c.errorHandler.HandleUUIDError(ctx, "preset ID")
|
|
||||||
}
|
|
||||||
|
|
||||||
actorID, _ := ctx.Locals("userID").(string)
|
|
||||||
actorUsername, _ := ctx.Locals("actorUsername").(string)
|
|
||||||
if actorUsername == "" {
|
|
||||||
actorUsername = "system"
|
|
||||||
}
|
|
||||||
|
|
||||||
configs, err := c.service.ApplyPreset(ctx.UserContext(), serverID, presetID, actorID, actorUsername)
|
|
||||||
if err != nil {
|
|
||||||
return c.errorHandler.HandleServiceError(ctx, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if restart {
|
|
||||||
if _, err := c.apiService.ServiceControlRestartServer(ctx); err != nil {
|
|
||||||
logging.ErrorWithContext("PRESET_APPLY_RESTART", "Failed to restart server after preset apply: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ctx.JSON(configs)
|
|
||||||
}
|
|
||||||
@@ -35,11 +35,6 @@ func InitializeControllers(c *dig.Container) {
|
|||||||
logging.Panic("unable to initialize config controller")
|
logging.Panic("unable to initialize config controller")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = c.Invoke(NewConfigPresetController)
|
|
||||||
if err != nil {
|
|
||||||
logging.Panic("unable to initialize config preset controller")
|
|
||||||
}
|
|
||||||
|
|
||||||
err = c.Invoke(NewServerController)
|
err = c.Invoke(NewServerController)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Panic("unable to initialize server controller")
|
logging.Panic("unable to initialize server controller")
|
||||||
@@ -74,14 +69,4 @@ func InitializeControllers(c *dig.Container) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Panic("unable to initialize steam controller")
|
logging.Panic("unable to initialize steam controller")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = c.Invoke(NewActivityLogController)
|
|
||||||
if err != nil {
|
|
||||||
logging.Panic("unable to initialize activity log controller")
|
|
||||||
}
|
|
||||||
|
|
||||||
err = c.Invoke(NewLogController)
|
|
||||||
if err != nil {
|
|
||||||
logging.Panic("unable to initialize log controller")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
type LeaderboardController struct {
|
type LeaderboardController struct {
|
||||||
service *service.LeaderboardService
|
service *service.LeaderboardService
|
||||||
errorHandler *error_handler.ControllerErrorHandler
|
errorHandler *error_handler.ControllerErrorHandler
|
||||||
@@ -61,14 +60,7 @@ func (lc *LeaderboardController) Update(c *fiber.Ctx) error {
|
|||||||
return lc.errorHandler.HandleParsingError(c, err)
|
return lc.errorHandler.HandleParsingError(c, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
userInfo, _ := c.Locals("userInfo").(*middleware.CachedUserInfo)
|
data, err := lc.service.Update(c.UserContext(), serverID, &input)
|
||||||
actorID, actorUsername := "", "system"
|
|
||||||
if userInfo != nil {
|
|
||||||
actorID = userInfo.UserID
|
|
||||||
actorUsername = userInfo.Username
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := lc.service.Update(c.UserContext(), serverID, &input, actorID, actorUsername)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return lc.errorHandler.HandleServiceError(c, err)
|
return lc.errorHandler.HandleServiceError(c, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
package controller
|
|
||||||
|
|
||||||
import (
|
|
||||||
"acc-server-manager/local/middleware"
|
|
||||||
"acc-server-manager/local/model"
|
|
||||||
"acc-server-manager/local/service"
|
|
||||||
"acc-server-manager/local/utl/common"
|
|
||||||
"acc-server-manager/local/utl/error_handler"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
type LogController struct {
|
|
||||||
service *service.ServerService
|
|
||||||
errorHandler *error_handler.ControllerErrorHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewLogController(ss *service.ServerService, routeGroups *common.RouteGroups, auth *middleware.AuthMiddleware) *LogController {
|
|
||||||
lc := &LogController{
|
|
||||||
service: ss,
|
|
||||||
errorHandler: error_handler.NewControllerErrorHandler(),
|
|
||||||
}
|
|
||||||
|
|
||||||
logRoutes := routeGroups.Log
|
|
||||||
logRoutes.Use(auth.Authenticate)
|
|
||||||
logRoutes.Get("/", auth.HasPermission(model.ServerView), lc.GetLogLines)
|
|
||||||
|
|
||||||
return lc
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetLogLines godoc
|
|
||||||
// @Summary Get last N lines of server log
|
|
||||||
// @Tags Server
|
|
||||||
// @Param id path string true "Server ID"
|
|
||||||
// @Param lines query int false "Number of lines to return (default 100)"
|
|
||||||
// @Success 200 {object} object{lines=[]string}
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Router /server/{id}/log [get]
|
|
||||||
func (lc *LogController) GetLogLines(c *fiber.Ctx) error {
|
|
||||||
serverIDStr := c.Params("id")
|
|
||||||
serverID, err := uuid.Parse(serverIDStr)
|
|
||||||
if err != nil {
|
|
||||||
return lc.errorHandler.HandleUUIDError(c, "server ID")
|
|
||||||
}
|
|
||||||
|
|
||||||
n, _ := strconv.Atoi(c.Query("lines", "100"))
|
|
||||||
if n <= 0 {
|
|
||||||
n = 100
|
|
||||||
}
|
|
||||||
if n > 10000 {
|
|
||||||
n = 10000
|
|
||||||
}
|
|
||||||
|
|
||||||
lines, err := lc.service.GetLastLogLines(c, serverID, n)
|
|
||||||
if err != nil {
|
|
||||||
return lc.errorHandler.HandleServiceError(c, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.JSON(fiber.Map{"lines": lines})
|
|
||||||
}
|
|
||||||
@@ -29,7 +29,6 @@ func NewServiceControlController(as *service.ServiceControlService, routeGroups
|
|||||||
}
|
}
|
||||||
|
|
||||||
serviceRoutes := routeGroups.Server.Group("/:id/service")
|
serviceRoutes := routeGroups.Server.Group("/:id/service")
|
||||||
serviceRoutes.Use(auth.Authenticate)
|
|
||||||
serviceRoutes.Get("/:service", ac.getStatus)
|
serviceRoutes.Get("/:service", ac.getStatus)
|
||||||
serviceRoutes.Post("/start", ac.startServer)
|
serviceRoutes.Post("/start", ac.startServer)
|
||||||
serviceRoutes.Post("/stop", ac.stopServer)
|
serviceRoutes.Post("/stop", ac.stopServer)
|
||||||
|
|||||||
@@ -1,70 +1,39 @@
|
|||||||
package controller
|
package controller
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"acc-server-manager/local/middleware"
|
|
||||||
"acc-server-manager/local/model"
|
|
||||||
"acc-server-manager/local/service"
|
|
||||||
"acc-server-manager/local/utl/common"
|
"acc-server-manager/local/utl/common"
|
||||||
"acc-server-manager/local/utl/configs"
|
"acc-server-manager/local/utl/configs"
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
"github.com/gofiber/fiber/v2"
|
||||||
"go.uber.org/dig"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type SystemController struct {
|
type SystemController struct {
|
||||||
systemService *service.SystemService
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type SystemControllerParams struct {
|
// NewSystemController
|
||||||
dig.In
|
// Initializes SystemController.
|
||||||
RouteGroups *common.RouteGroups
|
//
|
||||||
AuthMiddleware *middleware.AuthMiddleware
|
// Args:
|
||||||
SystemService *service.SystemService `optional:"true"`
|
// *services.SystemService: Service control service
|
||||||
}
|
// *Fiber.RouterGroup: Fiber Router Group
|
||||||
|
// Returns:
|
||||||
|
// *SystemController: Controller for service control interactions
|
||||||
|
func NewSystemController(routeGroups *common.RouteGroups) *SystemController {
|
||||||
|
ac := &SystemController{}
|
||||||
|
|
||||||
// NewSystemController initializes SystemController.
|
apiGroup := routeGroups.System
|
||||||
func NewSystemController(p SystemControllerParams) *SystemController {
|
apiGroup.Get("/health", ac.getFirst)
|
||||||
ac := &SystemController{systemService: p.SystemService}
|
|
||||||
|
|
||||||
apiGroup := p.RouteGroups.System
|
|
||||||
apiGroup.Get("/health", ac.getHealth)
|
|
||||||
|
|
||||||
if p.SystemService != nil {
|
|
||||||
apiGroup.Post("/migrate-image", p.AuthMiddleware.Authenticate, ac.migrateImage)
|
|
||||||
}
|
|
||||||
|
|
||||||
return ac
|
return ac
|
||||||
}
|
}
|
||||||
|
|
||||||
// getHealth returns the current version string.
|
// getFirst returns service control status
|
||||||
//
|
//
|
||||||
// @Summary Return service health / version
|
// @Summary Return service control status
|
||||||
// @Description Return service health / version
|
// @Description Return service control status
|
||||||
// @Tags system
|
// @Tags system
|
||||||
// @Success 200 {string} string
|
// @Success 200 {array} string
|
||||||
// @Router /system/health [get]
|
// @Router /system/health [get]
|
||||||
func (ac *SystemController) getHealth(c *fiber.Ctx) error {
|
func (ac *SystemController) getFirst(c *fiber.Ctx) error {
|
||||||
return c.SendString(configs.Version)
|
return c.SendString(configs.Version)
|
||||||
}
|
}
|
||||||
|
|
||||||
// migrateImage godoc
|
|
||||||
//
|
|
||||||
// @Summary Migrate all Docker server containers to current ACC image
|
|
||||||
// @Description Pulls the current ACC_IMAGE, removes old containers, optionally stops running servers
|
|
||||||
// @Tags system
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body model.MigrateImageRequest true "Migration options"
|
|
||||||
// @Success 200 {object} model.MigrationResult
|
|
||||||
// @Router /system/migrate-image [post]
|
|
||||||
func (ac *SystemController) migrateImage(c *fiber.Ctx) error {
|
|
||||||
var req model.MigrateImageRequest
|
|
||||||
if err := c.BodyParser(&req); err != nil {
|
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
|
|
||||||
}
|
|
||||||
result, err := ac.systemService.MigrateImage(c.Context(), req.StopRunning)
|
|
||||||
if err != nil {
|
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
|
||||||
}
|
|
||||||
return c.JSON(result)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -115,7 +115,6 @@ func (m *AuthMiddleware) AuthenticateWithHandler(jwtHandler *jwt.JWTHandler, isO
|
|||||||
if os.Getenv("TESTING_ENV") == "true" {
|
if os.Getenv("TESTING_ENV") == "true" {
|
||||||
userInfo := CachedUserInfo{UserID: uuid.New().String(), Username: "test@example.com", RoleName: "Admin", Permissions: make(map[string]bool), CachedAt: time.Now()}
|
userInfo := CachedUserInfo{UserID: uuid.New().String(), Username: "test@example.com", RoleName: "Admin", Permissions: make(map[string]bool), CachedAt: time.Now()}
|
||||||
ctx.Locals("userID", userInfo.UserID)
|
ctx.Locals("userID", userInfo.UserID)
|
||||||
ctx.Locals("actorUsername", userInfo.Username)
|
|
||||||
ctx.Locals("userInfo", userInfo)
|
ctx.Locals("userInfo", userInfo)
|
||||||
ctx.Locals("authTime", time.Now())
|
ctx.Locals("authTime", time.Now())
|
||||||
} else {
|
} else {
|
||||||
@@ -128,7 +127,6 @@ func (m *AuthMiddleware) AuthenticateWithHandler(jwtHandler *jwt.JWTHandler, isO
|
|||||||
}
|
}
|
||||||
|
|
||||||
ctx.Locals("userID", claims.UserID)
|
ctx.Locals("userID", claims.UserID)
|
||||||
ctx.Locals("actorUsername", userInfo.Username)
|
|
||||||
ctx.Locals("userInfo", userInfo)
|
ctx.Locals("userInfo", userInfo)
|
||||||
ctx.Locals("authTime", time.Now())
|
ctx.Locals("authTime", time.Now())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
package migrations
|
|
||||||
|
|
||||||
import (
|
|
||||||
"acc-server-manager/local/utl/logging"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
func RunAddActivityLogMigration(db *gorm.DB) error {
|
|
||||||
if err := db.AutoMigrate(&MigrationRecord{}); err != nil {
|
|
||||||
return fmt.Errorf("failed to ensure migration_records table: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var record MigrationRecord
|
|
||||||
if err := db.Where("migration_name = ?", "006_add_activity_log").First(&record).Error; err == nil {
|
|
||||||
logging.Info("Activity log migration already applied, skipping")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
record = MigrationRecord{
|
|
||||||
MigrationName: "006_add_activity_log",
|
|
||||||
AppliedAt: "datetime('now')",
|
|
||||||
Success: true,
|
|
||||||
Notes: "Added ActivityLog table via GORM AutoMigrate",
|
|
||||||
}
|
|
||||||
if err := db.Create(&record).Error; err != nil {
|
|
||||||
return fmt.Errorf("failed to record migration 006: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
logging.Info("Activity log migration recorded")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
package migrations
|
|
||||||
|
|
||||||
import (
|
|
||||||
"acc-server-manager/local/utl/logging"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ConfigPresetMigration struct {
|
|
||||||
ID uint `gorm:"primaryKey"`
|
|
||||||
Name string `gorm:"not null"`
|
|
||||||
Description string
|
|
||||||
Configuration string `gorm:"type:text"`
|
|
||||||
AssistRules string `gorm:"type:text"`
|
|
||||||
Event string `gorm:"type:text"`
|
|
||||||
EventRules string `gorm:"type:text"`
|
|
||||||
Settings string `gorm:"type:text"`
|
|
||||||
CreatedAt string
|
|
||||||
UpdatedAt string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ConfigPresetMigration) TableName() string {
|
|
||||||
return "config_presets"
|
|
||||||
}
|
|
||||||
|
|
||||||
func RunAddConfigPresetsMigration(db *gorm.DB) error {
|
|
||||||
if err := db.AutoMigrate(&MigrationRecord{}); err != nil {
|
|
||||||
return fmt.Errorf("failed to ensure migration_records table: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var record MigrationRecord
|
|
||||||
if err := db.Where("migration_name = ?", "007_add_config_presets").First(&record).Error; err == nil {
|
|
||||||
logging.Info("Config presets migration already applied, skipping")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
record = MigrationRecord{
|
|
||||||
MigrationName: "007_add_config_presets",
|
|
||||||
AppliedAt: time.Now().UTC().Format(time.RFC3339),
|
|
||||||
Success: true,
|
|
||||||
Notes: "Added ConfigPreset table via GORM AutoMigrate",
|
|
||||||
}
|
|
||||||
if err := db.Create(&record).Error; err != nil {
|
|
||||||
return fmt.Errorf("failed to record migration 007: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
logging.Info("Config presets migration recorded")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
package model
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ActionType string
|
|
||||||
|
|
||||||
const (
|
|
||||||
ActionConfigUpdate ActionType = "config_update"
|
|
||||||
ActionServerStart ActionType = "server_start"
|
|
||||||
ActionServerStop ActionType = "server_stop"
|
|
||||||
ActionServerRestart ActionType = "server_restart"
|
|
||||||
ActionLeaderboardUpdate ActionType = "leaderboard_update"
|
|
||||||
ActionPresetCreate ActionType = "preset_create"
|
|
||||||
ActionPresetApply ActionType = "preset_apply"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ActivityLog struct {
|
|
||||||
ID uuid.UUID `json:"id" gorm:"type:uuid;primary_key;"`
|
|
||||||
ServerID *uuid.UUID `json:"serverId" gorm:"type:uuid;index"`
|
|
||||||
Server *Server `json:"server,omitempty" gorm:"foreignKey:ServerID"`
|
|
||||||
UserID string `json:"userId" gorm:"not null"`
|
|
||||||
Username string `json:"username" gorm:"not null"`
|
|
||||||
Action ActionType `json:"action" gorm:"not null"`
|
|
||||||
Details string `json:"details" gorm:"type:text"`
|
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *ActivityLog) BeforeCreate(tx *gorm.DB) error {
|
|
||||||
if a.ID == uuid.Nil {
|
|
||||||
a.ID = uuid.New()
|
|
||||||
}
|
|
||||||
if a.CreatedAt.IsZero() {
|
|
||||||
a.CreatedAt = time.Now().UTC()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type ActivityLogFilter struct {
|
|
||||||
BaseFilter
|
|
||||||
DateRangeFilter
|
|
||||||
UserID string `query:"user_id"`
|
|
||||||
Action ActionType `query:"action"`
|
|
||||||
ServerID string `query:"server_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *ActivityLogFilter) ApplyFilter(query *gorm.DB) *gorm.DB {
|
|
||||||
if f.ServerID != "" {
|
|
||||||
if serverUUID, err := uuid.Parse(f.ServerID); err == nil {
|
|
||||||
query = query.Where("server_id = ?", serverUUID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if f.UserID != "" {
|
|
||||||
query = query.Where("user_id = ?", f.UserID)
|
|
||||||
}
|
|
||||||
if f.Action != "" {
|
|
||||||
query = query.Where("action = ?", f.Action)
|
|
||||||
}
|
|
||||||
timeZero := time.Time{}
|
|
||||||
if f.StartDate != timeZero {
|
|
||||||
query = query.Where("created_at >= ?", f.StartDate)
|
|
||||||
}
|
|
||||||
if f.EndDate != timeZero {
|
|
||||||
query = query.Where("created_at <= ?", f.EndDate)
|
|
||||||
}
|
|
||||||
return query
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *ActivityLogFilter) GetSorting() (field string, desc bool) {
|
|
||||||
if f.SortBy == "" {
|
|
||||||
return "created_at", true
|
|
||||||
}
|
|
||||||
return f.SortBy, f.SortDesc
|
|
||||||
}
|
|
||||||
|
|
||||||
type LastActivityInfo struct {
|
|
||||||
UpdatedAt time.Time `json:"updatedAt"`
|
|
||||||
Username string `json:"username"`
|
|
||||||
Action ActionType `json:"action"`
|
|
||||||
}
|
|
||||||
@@ -40,14 +40,6 @@ type Configurations struct {
|
|||||||
Settings ServerSettings `json:"settings"`
|
Settings ServerSettings `json:"settings"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConfigurationsUpdateRequest struct {
|
|
||||||
Configuration *map[string]interface{} `json:"configuration"`
|
|
||||||
AssistRules *map[string]interface{} `json:"assistRules"`
|
|
||||||
Event *map[string]interface{} `json:"event"`
|
|
||||||
EventRules *map[string]interface{} `json:"eventRules"`
|
|
||||||
Settings *map[string]interface{} `json:"settings"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ServerSettings struct {
|
type ServerSettings struct {
|
||||||
ServerName string `json:"serverName"`
|
ServerName string `json:"serverName"`
|
||||||
AdminPassword string `json:"adminPassword"`
|
AdminPassword string `json:"adminPassword"`
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
package model
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ConfigPreset struct {
|
|
||||||
ID uuid.UUID `json:"id" gorm:"type:uuid;primary_key;"`
|
|
||||||
Name string `json:"name" gorm:"not null"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
Configuration string `json:"configuration" gorm:"type:text"`
|
|
||||||
AssistRules string `json:"assistRules" gorm:"type:text"`
|
|
||||||
Event string `json:"event" gorm:"type:text"`
|
|
||||||
EventRules string `json:"eventRules" gorm:"type:text"`
|
|
||||||
Settings string `json:"settings" gorm:"type:text"`
|
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
|
||||||
UpdatedAt time.Time `json:"updatedAt"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *ConfigPreset) BeforeCreate(tx *gorm.DB) error {
|
|
||||||
if p.ID == uuid.Nil {
|
|
||||||
p.ID = uuid.New()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type ConfigPresetCreateRequest struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
Configuration *map[string]interface{} `json:"configuration"`
|
|
||||||
AssistRules *map[string]interface{} `json:"assistRules"`
|
|
||||||
Event *map[string]interface{} `json:"event"`
|
|
||||||
EventRules *map[string]interface{} `json:"eventRules"`
|
|
||||||
Settings *map[string]interface{} `json:"settings"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ConfigPresetUpdateRequest struct {
|
|
||||||
Name *string `json:"name"`
|
|
||||||
Description *string `json:"description"`
|
|
||||||
Configuration *map[string]interface{} `json:"configuration"`
|
|
||||||
AssistRules *map[string]interface{} `json:"assistRules"`
|
|
||||||
Event *map[string]interface{} `json:"event"`
|
|
||||||
EventRules *map[string]interface{} `json:"eventRules"`
|
|
||||||
Settings *map[string]interface{} `json:"settings"`
|
|
||||||
}
|
|
||||||
@@ -30,18 +30,6 @@ type ConfigFilter struct {
|
|||||||
ChangedAt time.Time `query:"changed_at" time_format:"2006-01-02T15:04:05Z07:00"`
|
ChangedAt time.Time `query:"changed_at" time_format:"2006-01-02T15:04:05Z07:00"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConfigPresetFilter struct {
|
|
||||||
BaseFilter
|
|
||||||
Name string `query:"name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *ConfigPresetFilter) ApplyFilter(query *gorm.DB) *gorm.DB {
|
|
||||||
if f.Name != "" {
|
|
||||||
query = query.Where("name LIKE ?", "%"+f.Name+"%")
|
|
||||||
}
|
|
||||||
return query
|
|
||||||
}
|
|
||||||
|
|
||||||
type ServiceControlFilter struct {
|
type ServiceControlFilter struct {
|
||||||
BaseFilter
|
BaseFilter
|
||||||
ServiceControl string `query:"serviceControl"`
|
ServiceControl string `query:"serviceControl"`
|
||||||
|
|||||||
@@ -24,11 +24,6 @@ const (
|
|||||||
MembershipCreate = "membership.create"
|
MembershipCreate = "membership.create"
|
||||||
MembershipView = "membership.view"
|
MembershipView = "membership.view"
|
||||||
MembershipEdit = "membership.edit"
|
MembershipEdit = "membership.edit"
|
||||||
|
|
||||||
PresetView = "preset.view"
|
|
||||||
PresetCreate = "preset.create"
|
|
||||||
PresetUpdate = "preset.update"
|
|
||||||
PresetDelete = "preset.delete"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func AllPermissions() []string {
|
func AllPermissions() []string {
|
||||||
@@ -52,9 +47,5 @@ func AllPermissions() []string {
|
|||||||
MembershipCreate,
|
MembershipCreate,
|
||||||
MembershipView,
|
MembershipView,
|
||||||
MembershipEdit,
|
MembershipEdit,
|
||||||
PresetView,
|
|
||||||
PresetCreate,
|
|
||||||
PresetUpdate,
|
|
||||||
PresetDelete,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,7 +45,6 @@ type Server struct {
|
|||||||
Platform string `gorm:"not null;default:'windows'" json:"platform"`
|
Platform string `gorm:"not null;default:'windows'" json:"platform"`
|
||||||
ContainerID string `gorm:"default:''" json:"-"`
|
ContainerID string `gorm:"default:''" json:"-"`
|
||||||
State *ServerState `gorm:"-" json:"state"`
|
State *ServerState `gorm:"-" json:"state"`
|
||||||
LastActivity *LastActivityInfo `gorm:"-" json:"lastActivity,omitempty"`
|
|
||||||
DateCreated time.Time `json:"dateCreated"`
|
DateCreated time.Time `json:"dateCreated"`
|
||||||
FromSteamCMD bool `gorm:"not null; default:true" json:"-"`
|
FromSteamCMD bool `gorm:"not null; default:true" json:"-"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
package model
|
|
||||||
|
|
||||||
type MigrateImageRequest struct {
|
|
||||||
StopRunning bool `json:"stopRunning"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ServerMigrationEntry struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
WasRunning bool `json:"wasRunning"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ServerMigrationError struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Error string `json:"error"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type MigrationResult struct {
|
|
||||||
Image string `json:"image"`
|
|
||||||
Migrated []ServerMigrationEntry `json:"migrated"`
|
|
||||||
Skipped []ServerMigrationEntry `json:"skipped"`
|
|
||||||
Failed []ServerMigrationError `json:"failed"`
|
|
||||||
}
|
|
||||||
@@ -33,7 +33,6 @@ const (
|
|||||||
MessageTypeSteamOutput WebSocketMessageType = "steam_output"
|
MessageTypeSteamOutput WebSocketMessageType = "steam_output"
|
||||||
MessageTypeError WebSocketMessageType = "error"
|
MessageTypeError WebSocketMessageType = "error"
|
||||||
MessageTypeComplete WebSocketMessageType = "complete"
|
MessageTypeComplete WebSocketMessageType = "complete"
|
||||||
MessageTypeLogLine WebSocketMessageType = "log_line"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type WebSocketMessage struct {
|
type WebSocketMessage struct {
|
||||||
@@ -66,10 +65,6 @@ type CompleteMessage struct {
|
|||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type LogLineMessage struct {
|
|
||||||
Line string `json:"line"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetStepDescription(step ServerCreationStep) string {
|
func GetStepDescription(step ServerCreationStep) string {
|
||||||
descriptions := map[ServerCreationStep]string{
|
descriptions := map[ServerCreationStep]string{
|
||||||
StepValidation: "Validating server configuration",
|
StepValidation: "Validating server configuration",
|
||||||
|
|||||||
@@ -25,5 +25,4 @@ type FirewallManager interface {
|
|||||||
type LogStreamer interface {
|
type LogStreamer interface {
|
||||||
Start(ctx context.Context, server *model.Server, handleLine func(string)) error
|
Start(ctx context.Context, server *model.Server, handleLine func(string)) error
|
||||||
Stop(serverID uuid.UUID)
|
Stop(serverID uuid.UUID)
|
||||||
GetLastLines(ctx context.Context, server *model.Server, n int) ([]string, error)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,96 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"acc-server-manager/local/model"
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ActivityLogRepository struct {
|
|
||||||
*BaseRepository[model.ActivityLog, model.ActivityLogFilter]
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewActivityLogRepository(db *gorm.DB) *ActivityLogRepository {
|
|
||||||
return &ActivityLogRepository{
|
|
||||||
BaseRepository: NewBaseRepository[model.ActivityLog, model.ActivityLogFilter](db, model.ActivityLog{}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *ActivityLogRepository) Insert(ctx context.Context, entry *model.ActivityLog) error {
|
|
||||||
return r.BaseRepository.Insert(ctx, entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *ActivityLogRepository) GetAll(ctx context.Context, filter *model.ActivityLogFilter) (*[]model.ActivityLog, error) {
|
|
||||||
result := &[]model.ActivityLog{}
|
|
||||||
query := r.BaseRepository.db.WithContext(ctx).
|
|
||||||
Model(&model.ActivityLog{}).
|
|
||||||
Preload("Server")
|
|
||||||
|
|
||||||
query = filter.ApplyFilter(query)
|
|
||||||
|
|
||||||
offset, limit := filter.Pagination()
|
|
||||||
query = query.Offset(offset).Limit(limit)
|
|
||||||
|
|
||||||
field, desc := filter.GetSorting()
|
|
||||||
if desc {
|
|
||||||
query = query.Order(field + " DESC")
|
|
||||||
} else {
|
|
||||||
query = query.Order(field)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := query.Find(result).Error; err != nil {
|
|
||||||
return nil, fmt.Errorf("error getting activity logs: %w", err)
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type lastActivityRow struct {
|
|
||||||
ServerID string `gorm:"column:server_id"`
|
|
||||||
CreatedAt time.Time `gorm:"column:created_at"`
|
|
||||||
Username string `gorm:"column:username"`
|
|
||||||
Action model.ActionType `gorm:"column:action"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetLastActivityByServerIDs returns the most recent activity entry per server.
|
|
||||||
// Uses a single GROUP BY query with MAX(created_at); SQLite selects the other
|
|
||||||
// columns from the row that holds the max value — documented SQLite behaviour.
|
|
||||||
func (r *ActivityLogRepository) GetLastActivityByServerIDs(ctx context.Context, serverIDs []uuid.UUID) (map[uuid.UUID]*model.LastActivityInfo, error) {
|
|
||||||
out := make(map[uuid.UUID]*model.LastActivityInfo)
|
|
||||||
if len(serverIDs) == 0 {
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert to string slice so the IN clause works with SQLite UUID strings.
|
|
||||||
ids := make([]string, len(serverIDs))
|
|
||||||
for i, id := range serverIDs {
|
|
||||||
ids[i] = id.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
var rows []lastActivityRow
|
|
||||||
err := r.BaseRepository.db.WithContext(ctx).
|
|
||||||
Model(&model.ActivityLog{}).
|
|
||||||
Select("server_id, MAX(created_at) as created_at, username, action").
|
|
||||||
Where("server_id IN ?", ids).
|
|
||||||
Group("server_id").
|
|
||||||
Scan(&rows).Error
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, row := range rows {
|
|
||||||
serverUUID, err := uuid.Parse(row.ServerID)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
out[serverUUID] = &model.LastActivityInfo{
|
|
||||||
UpdatedAt: row.CreatedAt,
|
|
||||||
Username: row.Username,
|
|
||||||
Action: row.Action,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"acc-server-manager/local/model"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ConfigPresetRepository struct {
|
|
||||||
*BaseRepository[model.ConfigPreset, model.ConfigPresetFilter]
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewConfigPresetRepository(db *gorm.DB) *ConfigPresetRepository {
|
|
||||||
return &ConfigPresetRepository{
|
|
||||||
BaseRepository: NewBaseRepository[model.ConfigPreset, model.ConfigPresetFilter](db, model.ConfigPreset{}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -20,8 +20,6 @@ func InitializeRepositories(c *dig.Container) {
|
|||||||
c.Provide(NewSteamCredentialsRepository)
|
c.Provide(NewSteamCredentialsRepository)
|
||||||
c.Provide(NewMembershipRepository)
|
c.Provide(NewMembershipRepository)
|
||||||
c.Provide(NewLeaderboardRepository)
|
c.Provide(NewLeaderboardRepository)
|
||||||
c.Provide(NewActivityLogRepository)
|
|
||||||
c.Provide(NewConfigPresetRepository)
|
|
||||||
|
|
||||||
if err := c.Provide(func() *model.Steam2FAManager {
|
if err := c.Provide(func() *model.Steam2FAManager {
|
||||||
manager := model.NewSteam2FAManager()
|
manager := model.NewSteam2FAManager()
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"acc-server-manager/local/model"
|
|
||||||
"acc-server-manager/local/repository"
|
|
||||||
"acc-server-manager/local/utl/logging"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ActivityLogService struct {
|
|
||||||
repo *repository.ActivityLogRepository
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewActivityLogService(repo *repository.ActivityLogRepository) *ActivityLogService {
|
|
||||||
return &ActivityLogService{repo: repo}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Log persists an activity log entry. Errors are logged but not returned so
|
|
||||||
// callers can treat this as fire-and-forget.
|
|
||||||
func (s *ActivityLogService) Log(ctx context.Context, entry *model.ActivityLog) error {
|
|
||||||
if err := s.repo.Insert(ctx, entry); err != nil {
|
|
||||||
logging.Error("Failed to insert activity log: %v", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *ActivityLogService) GetAll(ctx context.Context, filter *model.ActivityLogFilter) (*[]model.ActivityLog, error) {
|
|
||||||
return s.repo.GetAll(ctx, filter)
|
|
||||||
}
|
|
||||||
|
|
||||||
// BuildConfigDetails produces a JSON string summarising which top-level keys
|
|
||||||
// changed between oldJSON and newJSON.
|
|
||||||
func BuildConfigDetails(file string, oldJSON, newJSON []byte) string {
|
|
||||||
var oldMap, newMap map[string]interface{}
|
|
||||||
|
|
||||||
if err := json.Unmarshal(oldJSON, &oldMap); err != nil {
|
|
||||||
oldMap = map[string]interface{}{}
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(newJSON, &newMap); err != nil {
|
|
||||||
newMap = map[string]interface{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
var changedKeys []string
|
|
||||||
for key, newVal := range newMap {
|
|
||||||
oldVal, exists := oldMap[key]
|
|
||||||
if !exists {
|
|
||||||
changedKeys = append(changedKeys, key)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
oldBytes, _ := json.Marshal(oldVal)
|
|
||||||
newBytes, _ := json.Marshal(newVal)
|
|
||||||
if string(oldBytes) != string(newBytes) {
|
|
||||||
changedKeys = append(changedKeys, key)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(changedKeys) == 0 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
keysJSON, _ := json.Marshal(changedKeys)
|
|
||||||
return fmt.Sprintf(`{"file":%q,"changed_keys":%s}`, file, string(keysJSON))
|
|
||||||
}
|
|
||||||
@@ -68,16 +68,14 @@ type ConfigService struct {
|
|||||||
repository *repository.ConfigRepository
|
repository *repository.ConfigRepository
|
||||||
serverRepository *repository.ServerRepository
|
serverRepository *repository.ServerRepository
|
||||||
serverService *ServerService
|
serverService *ServerService
|
||||||
activityLog *ActivityLogService
|
|
||||||
configCache *model.ServerConfigCache
|
configCache *model.ServerConfigCache
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewConfigService(repository *repository.ConfigRepository, serverRepository *repository.ServerRepository, activityLog *ActivityLogService) *ConfigService {
|
func NewConfigService(repository *repository.ConfigRepository, serverRepository *repository.ServerRepository) *ConfigService {
|
||||||
logging.Debug("Initializing ConfigService with 5m expiration and 1s throttle")
|
logging.Debug("Initializing ConfigService with 5m expiration and 1s throttle")
|
||||||
return &ConfigService{
|
return &ConfigService{
|
||||||
repository: repository,
|
repository: repository,
|
||||||
serverRepository: serverRepository,
|
serverRepository: serverRepository,
|
||||||
activityLog: activityLog,
|
|
||||||
configCache: model.NewServerConfigCache(model.CacheConfig{
|
configCache: model.NewServerConfigCache(model.CacheConfig{
|
||||||
ExpirationTime: 5 * time.Minute,
|
ExpirationTime: 5 * time.Minute,
|
||||||
ThrottleTime: 1 * time.Second,
|
ThrottleTime: 1 * time.Second,
|
||||||
@@ -93,104 +91,12 @@ func (as *ConfigService) SetServerService(serverService *ServerService) {
|
|||||||
// context.Context: Application context
|
// context.Context: Application context
|
||||||
// Returns:
|
// Returns:
|
||||||
// string: Application version
|
// string: Application version
|
||||||
func (as *ConfigService) UpdateAllConfigs(ctx *fiber.Ctx, req *model.ConfigurationsUpdateRequest) ([]*model.Config, error) {
|
|
||||||
serverID := ctx.Locals("serverId").(string)
|
|
||||||
override := ctx.QueryBool("override", false)
|
|
||||||
|
|
||||||
serverUUID, err := uuid.Parse(serverID)
|
|
||||||
if err != nil {
|
|
||||||
logging.Error("Invalid server ID format: %v", err)
|
|
||||||
return nil, fmt.Errorf("invalid server ID format")
|
|
||||||
}
|
|
||||||
|
|
||||||
server, err := as.serverRepository.GetByID(ctx.UserContext(), serverUUID)
|
|
||||||
if err != nil {
|
|
||||||
logging.Error("Server not found")
|
|
||||||
return nil, fmt.Errorf("server not found")
|
|
||||||
}
|
|
||||||
|
|
||||||
type configEntry struct {
|
|
||||||
fileName string
|
|
||||||
body *map[string]interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
entries := []configEntry{
|
|
||||||
{ConfigurationJson, req.Configuration},
|
|
||||||
{AssistRulesJson, req.AssistRules},
|
|
||||||
{EventJson, req.Event},
|
|
||||||
{EventRulesJson, req.EventRules},
|
|
||||||
{SettingsJson, req.Settings},
|
|
||||||
}
|
|
||||||
|
|
||||||
actorID, _ := ctx.Locals("userID").(string)
|
|
||||||
actorUsername, _ := ctx.Locals("actorUsername").(string)
|
|
||||||
if actorUsername == "" {
|
|
||||||
actorUsername = "system"
|
|
||||||
}
|
|
||||||
|
|
||||||
var results []*model.Config
|
|
||||||
for _, entry := range entries {
|
|
||||||
if entry.body == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
oldDataUTF8, newData, err := as.updateConfigFiles(ctx.UserContext(), server, entry.fileName, entry.body, override)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if entry.fileName == SettingsJson {
|
|
||||||
if nameVal, ok := (*entry.body)["serverName"]; ok {
|
|
||||||
if nameStr, ok := nameVal.(string); ok && nameStr != "" && nameStr != server.Name {
|
|
||||||
server.Name = nameStr
|
|
||||||
if err := as.serverRepository.Update(ctx.UserContext(), server); err != nil {
|
|
||||||
logging.Error("Failed to update server name in DB: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
result := as.repository.UpdateConfig(ctx.UserContext(), &model.Config{
|
|
||||||
ServerID: serverUUID,
|
|
||||||
ConfigFile: entry.fileName,
|
|
||||||
OldConfig: string(oldDataUTF8),
|
|
||||||
NewConfig: string(newData),
|
|
||||||
ChangedAt: time.Now(),
|
|
||||||
})
|
|
||||||
results = append(results, result)
|
|
||||||
|
|
||||||
if as.activityLog != nil {
|
|
||||||
if details := BuildConfigDetails(entry.fileName, oldDataUTF8, newData); details != "" {
|
|
||||||
go func(details string) {
|
|
||||||
_ = as.activityLog.Log(context.Background(), &model.ActivityLog{
|
|
||||||
ServerID: &serverUUID,
|
|
||||||
UserID: actorID,
|
|
||||||
Username: actorUsername,
|
|
||||||
Action: model.ActionConfigUpdate,
|
|
||||||
Details: details,
|
|
||||||
})
|
|
||||||
}(details)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(results) > 0 {
|
|
||||||
as.configCache.InvalidateServerCache(serverID)
|
|
||||||
as.serverService.StartAccServerRuntime(server)
|
|
||||||
}
|
|
||||||
|
|
||||||
return results, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (as *ConfigService) UpdateConfig(ctx *fiber.Ctx, body *map[string]interface{}) (*model.Config, error) {
|
func (as *ConfigService) UpdateConfig(ctx *fiber.Ctx, body *map[string]interface{}) (*model.Config, error) {
|
||||||
serverID := ctx.Locals("serverId").(string)
|
serverID := ctx.Locals("serverId").(string)
|
||||||
configFile := ctx.Params("file")
|
configFile := ctx.Params("file")
|
||||||
override := ctx.QueryBool("override", false)
|
override := ctx.QueryBool("override", false)
|
||||||
|
|
||||||
actorID, _ := ctx.Locals("userID").(string)
|
return as.updateConfigInternal(ctx.UserContext(), serverID, configFile, body, override)
|
||||||
actorUsername, _ := ctx.Locals("actorUsername").(string)
|
|
||||||
if actorUsername == "" {
|
|
||||||
actorUsername = "system"
|
|
||||||
}
|
|
||||||
|
|
||||||
return as.updateConfigInternal(ctx.UserContext(), serverID, configFile, body, override, actorID, actorUsername)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (as *ConfigService) updateConfigFiles(ctx context.Context, server *model.Server, configFile string, body *map[string]interface{}, override bool) ([]byte, []byte, error) {
|
func (as *ConfigService) updateConfigFiles(ctx context.Context, server *model.Server, configFile string, body *map[string]interface{}, override bool) ([]byte, []byte, error) {
|
||||||
@@ -249,7 +155,7 @@ func (as *ConfigService) updateConfigFiles(ctx context.Context, server *model.Se
|
|||||||
return oldDataUTF8, newData, nil
|
return oldDataUTF8, newData, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (as *ConfigService) updateConfigInternal(ctx context.Context, serverID string, configFile string, body *map[string]interface{}, override bool, actorID, actorUsername string) (*model.Config, error) {
|
func (as *ConfigService) updateConfigInternal(ctx context.Context, serverID string, configFile string, body *map[string]interface{}, override bool) (*model.Config, error) {
|
||||||
serverUUID, err := uuid.Parse(serverID)
|
serverUUID, err := uuid.Parse(serverID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Error("Invalid server ID format: %v", err)
|
logging.Error("Invalid server ID format: %v", err)
|
||||||
@@ -267,34 +173,9 @@ func (as *ConfigService) updateConfigInternal(ctx context.Context, serverID stri
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if configFile == SettingsJson {
|
|
||||||
if nameVal, ok := (*body)["serverName"]; ok {
|
|
||||||
if nameStr, ok := nameVal.(string); ok && nameStr != "" && nameStr != server.Name {
|
|
||||||
server.Name = nameStr
|
|
||||||
if err := as.serverRepository.Update(ctx, server); err != nil {
|
|
||||||
logging.Error("Failed to update server name in DB: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
as.configCache.InvalidateServerCache(serverID)
|
as.configCache.InvalidateServerCache(serverID)
|
||||||
|
|
||||||
as.serverService.StartAccServerRuntime(server)
|
as.serverService.StartAccServerRuntime(server)
|
||||||
|
|
||||||
if as.activityLog != nil {
|
|
||||||
if details := BuildConfigDetails(configFile, oldDataUTF8, newData); details != "" {
|
|
||||||
go func() {
|
|
||||||
_ = as.activityLog.Log(context.Background(), &model.ActivityLog{
|
|
||||||
ServerID: &serverUUID,
|
|
||||||
UserID: actorID,
|
|
||||||
Username: actorUsername,
|
|
||||||
Action: model.ActionConfigUpdate,
|
|
||||||
Details: details,
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return as.repository.UpdateConfig(ctx, &model.Config{
|
return as.repository.UpdateConfig(ctx, &model.Config{
|
||||||
ServerID: serverUUID,
|
ServerID: serverUUID,
|
||||||
ConfigFile: configFile,
|
ConfigFile: configFile,
|
||||||
@@ -539,14 +420,6 @@ func (as *ConfigService) GetConfiguration(server *model.Server) (*model.Configur
|
|||||||
return &config, nil
|
return &config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (as *ConfigService) SetIgnorePrematureDisconnects(server *model.Server, value int) error {
|
|
||||||
configMap := map[string]interface{}{
|
|
||||||
"ignorePrematureDisconnects": value,
|
|
||||||
}
|
|
||||||
_, _, err := as.updateConfigFiles(context.Background(), server, SettingsJson, &configMap, false)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (as *ConfigService) SaveConfiguration(server *model.Server, config *model.Configuration) error {
|
func (as *ConfigService) SaveConfiguration(server *model.Server, config *model.Configuration) error {
|
||||||
configMap := make(map[string]interface{})
|
configMap := make(map[string]interface{})
|
||||||
configBytes, err := json.Marshal(config)
|
configBytes, err := json.Marshal(config)
|
||||||
@@ -560,17 +433,3 @@ func (as *ConfigService) SaveConfiguration(server *model.Server, config *model.C
|
|||||||
_, _, err = as.updateConfigFiles(context.Background(), server, ConfigurationJson, &configMap, true)
|
_, _, err = as.updateConfigFiles(context.Background(), server, ConfigurationJson, &configMap, true)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ApplySection writes a single config section to the server's config file and
|
|
||||||
// records the change. It is used by ConfigPresetService to apply preset sections.
|
|
||||||
func (as *ConfigService) ApplySection(ctx context.Context, serverID, configFile string, body *map[string]interface{}, actorID, actorUsername string) (*model.Config, error) {
|
|
||||||
return as.updateConfigInternal(ctx, serverID, configFile, body, true, actorID, actorUsername)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (as *ConfigService) SetServerName(server *model.Server, name string) error {
|
|
||||||
configMap := map[string]interface{}{
|
|
||||||
"serverName": name,
|
|
||||||
}
|
|
||||||
_, _, err := as.updateConfigFiles(context.Background(), server, SettingsJson, &configMap, false)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,210 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"acc-server-manager/local/model"
|
|
||||||
"acc-server-manager/local/repository"
|
|
||||||
"acc-server-manager/local/utl/logging"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
presetMaxNameLen = 100
|
|
||||||
presetMaxDescLen = 500
|
|
||||||
presetMaxSectionBytes = 64 * 1024 // 64 KB per config section
|
|
||||||
)
|
|
||||||
|
|
||||||
type ConfigPresetService struct {
|
|
||||||
repository *repository.ConfigPresetRepository
|
|
||||||
configService *ConfigService
|
|
||||||
activityLog *ActivityLogService
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewConfigPresetService(repo *repository.ConfigPresetRepository, configService *ConfigService, activityLog *ActivityLogService) *ConfigPresetService {
|
|
||||||
return &ConfigPresetService{
|
|
||||||
repository: repo,
|
|
||||||
configService: configService,
|
|
||||||
activityLog: activityLog,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *ConfigPresetService) ListPresets(ctx context.Context, filter *model.ConfigPresetFilter) (*[]model.ConfigPreset, error) {
|
|
||||||
return s.repository.GetAll(ctx, filter)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *ConfigPresetService) GetPreset(ctx context.Context, id uuid.UUID) (*model.ConfigPreset, error) {
|
|
||||||
preset, err := s.repository.GetByID(ctx, id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if preset == nil {
|
|
||||||
return nil, fmt.Errorf("preset not found")
|
|
||||||
}
|
|
||||||
return preset, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *ConfigPresetService) CreatePreset(ctx context.Context, req *model.ConfigPresetCreateRequest, actorID, actorUsername string) (*model.ConfigPreset, error) {
|
|
||||||
if req.Name == "" {
|
|
||||||
return nil, fmt.Errorf("preset name is required")
|
|
||||||
}
|
|
||||||
if len(req.Name) > presetMaxNameLen {
|
|
||||||
return nil, fmt.Errorf("preset name exceeds maximum length of %d characters", presetMaxNameLen)
|
|
||||||
}
|
|
||||||
if len(req.Description) > presetMaxDescLen {
|
|
||||||
return nil, fmt.Errorf("preset description exceeds maximum length of %d characters", presetMaxDescLen)
|
|
||||||
}
|
|
||||||
|
|
||||||
preset := &model.ConfigPreset{
|
|
||||||
Name: req.Name,
|
|
||||||
Description: req.Description,
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := marshalSections(req.Configuration, req.AssistRules, req.Event, req.EventRules, req.Settings, preset); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.repository.Insert(ctx, preset); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
details := fmt.Sprintf(`{"preset_id":%q,"preset_name":%q}`, preset.ID, preset.Name)
|
|
||||||
go func() {
|
|
||||||
if logErr := s.activityLog.Log(context.Background(), &model.ActivityLog{
|
|
||||||
UserID: actorID,
|
|
||||||
Username: actorUsername,
|
|
||||||
Action: model.ActionPresetCreate,
|
|
||||||
Details: details,
|
|
||||||
}); logErr != nil {
|
|
||||||
logging.Error("Failed to log preset create: %v", logErr)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return preset, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *ConfigPresetService) UpdatePreset(ctx context.Context, id uuid.UUID, req *model.ConfigPresetUpdateRequest) (*model.ConfigPreset, error) {
|
|
||||||
preset, err := s.GetPreset(ctx, id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Name != nil {
|
|
||||||
if len(*req.Name) == 0 {
|
|
||||||
return nil, fmt.Errorf("preset name cannot be empty")
|
|
||||||
}
|
|
||||||
if len(*req.Name) > presetMaxNameLen {
|
|
||||||
return nil, fmt.Errorf("preset name exceeds maximum length of %d characters", presetMaxNameLen)
|
|
||||||
}
|
|
||||||
preset.Name = *req.Name
|
|
||||||
}
|
|
||||||
if req.Description != nil {
|
|
||||||
if len(*req.Description) > presetMaxDescLen {
|
|
||||||
return nil, fmt.Errorf("preset description exceeds maximum length of %d characters", presetMaxDescLen)
|
|
||||||
}
|
|
||||||
preset.Description = *req.Description
|
|
||||||
}
|
|
||||||
if err := marshalSections(req.Configuration, req.AssistRules, req.Event, req.EventRules, req.Settings, preset); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.repository.Update(ctx, preset); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return preset, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *ConfigPresetService) DeletePreset(ctx context.Context, id uuid.UUID) error {
|
|
||||||
return s.repository.Delete(ctx, id)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *ConfigPresetService) ApplyPreset(ctx context.Context, serverID string, presetID uuid.UUID, actorID, actorUsername string) ([]*model.Config, error) {
|
|
||||||
preset, err := s.GetPreset(ctx, presetID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
serverUUID, err := uuid.Parse(serverID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid server ID: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
type sectionEntry struct {
|
|
||||||
fileName string
|
|
||||||
raw string
|
|
||||||
}
|
|
||||||
|
|
||||||
sections := []sectionEntry{
|
|
||||||
{ConfigurationJson, preset.Configuration},
|
|
||||||
{AssistRulesJson, preset.AssistRules},
|
|
||||||
{EventJson, preset.Event},
|
|
||||||
{EventRulesJson, preset.EventRules},
|
|
||||||
{SettingsJson, preset.Settings},
|
|
||||||
}
|
|
||||||
|
|
||||||
var results []*model.Config
|
|
||||||
for _, section := range sections {
|
|
||||||
if section.raw == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
var body map[string]interface{}
|
|
||||||
if err := json.Unmarshal([]byte(section.raw), &body); err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to unmarshal preset section %s: %v", section.fileName, err)
|
|
||||||
}
|
|
||||||
result, err := s.configService.ApplySection(ctx, serverID, section.fileName, &body, actorID, actorUsername)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to apply preset section %s: %v", section.fileName, err)
|
|
||||||
}
|
|
||||||
if result != nil {
|
|
||||||
results = append(results, result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
details := fmt.Sprintf(`{"preset_id":%q,"preset_name":%q,"sections_applied":%d}`, presetID, preset.Name, len(results))
|
|
||||||
go func() {
|
|
||||||
if logErr := s.activityLog.Log(context.Background(), &model.ActivityLog{
|
|
||||||
ServerID: &serverUUID,
|
|
||||||
UserID: actorID,
|
|
||||||
Username: actorUsername,
|
|
||||||
Action: model.ActionPresetApply,
|
|
||||||
Details: details,
|
|
||||||
}); logErr != nil {
|
|
||||||
logging.Error("Failed to log preset apply: %v", logErr)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return results, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// marshalSections marshals each non-nil config section into the preset's JSON string fields,
|
|
||||||
// enforcing the per-section byte size limit.
|
|
||||||
func marshalSections(configuration, assistRules, event, eventRules, settings *map[string]interface{}, preset *model.ConfigPreset) error {
|
|
||||||
type entry struct {
|
|
||||||
src *map[string]interface{}
|
|
||||||
name string
|
|
||||||
dest *string
|
|
||||||
}
|
|
||||||
entries := []entry{
|
|
||||||
{configuration, "configuration", &preset.Configuration},
|
|
||||||
{assistRules, "assistRules", &preset.AssistRules},
|
|
||||||
{event, "event", &preset.Event},
|
|
||||||
{eventRules, "eventRules", &preset.EventRules},
|
|
||||||
{settings, "settings", &preset.Settings},
|
|
||||||
}
|
|
||||||
for _, e := range entries {
|
|
||||||
if e.src == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
b, err := json.Marshal(e.src)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to marshal %s: %v", e.name, err)
|
|
||||||
}
|
|
||||||
if len(b) > presetMaxSectionBytes {
|
|
||||||
return fmt.Errorf("%s section exceeds maximum size of %d bytes", e.name, presetMaxSectionBytes)
|
|
||||||
}
|
|
||||||
*e.dest = string(b)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -6,11 +6,9 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"context"
|
"context"
|
||||||
"io"
|
"io"
|
||||||
"strconv"
|
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/docker/docker/api/types/container"
|
"github.com/docker/docker/api/types"
|
||||||
dockerclient "github.com/docker/docker/client"
|
dockerclient "github.com/docker/docker/client"
|
||||||
"github.com/docker/docker/pkg/stdcopy"
|
"github.com/docker/docker/pkg/stdcopy"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
@@ -26,26 +24,25 @@ func NewDockerLogStreamer(client *dockerclient.Client) *DockerLogStreamer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *DockerLogStreamer) Start(ctx context.Context, server *model.Server, handleLine func(string)) error {
|
func (s *DockerLogStreamer) Start(ctx context.Context, server *model.Server, handleLine func(string)) error {
|
||||||
s.Stop(server.ID)
|
if _, exists := s.cancels.Load(server.ID); exists {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
if server.ContainerID == "" {
|
if server.ContainerID == "" {
|
||||||
logging.Warn("DockerLogStreamer.Start: no container ID for server %s, skipping", server.ID)
|
logging.Warn("DockerLogStreamer.Start: no container ID for server %s, skipping", server.ID)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
since := time.Now().UTC().Format(time.RFC3339)
|
|
||||||
streamCtx, cancel := context.WithCancel(ctx)
|
streamCtx, cancel := context.WithCancel(ctx)
|
||||||
s.cancels.Store(server.ID, cancel)
|
s.cancels.Store(server.ID, cancel)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
defer s.cancels.Delete(server.ID)
|
defer s.cancels.Delete(server.ID)
|
||||||
|
|
||||||
rc, err := s.client.ContainerLogs(streamCtx, server.ContainerID, container.LogsOptions{
|
rc, err := s.client.ContainerLogs(streamCtx, server.ContainerID, types.ContainerLogsOptions{
|
||||||
ShowStdout: true,
|
ShowStdout: true,
|
||||||
ShowStderr: true,
|
ShowStderr: true,
|
||||||
Follow: true,
|
Follow: true,
|
||||||
Timestamps: false,
|
Timestamps: false,
|
||||||
Since: since,
|
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Error("DockerLogStreamer: failed to attach to container %s: %v", server.ContainerID[:12], err)
|
logging.Error("DockerLogStreamer: failed to attach to container %s: %v", server.ContainerID[:12], err)
|
||||||
@@ -75,34 +72,3 @@ func (s *DockerLogStreamer) Stop(serverID uuid.UUID) {
|
|||||||
v.(context.CancelFunc)()
|
v.(context.CancelFunc)()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *DockerLogStreamer) GetLastLines(ctx context.Context, server *model.Server, n int) ([]string, error) {
|
|
||||||
if n <= 0 || server.ContainerID == "" {
|
|
||||||
return []string{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
rc, err := s.client.ContainerLogs(ctx, server.ContainerID, container.LogsOptions{
|
|
||||||
ShowStdout: true,
|
|
||||||
ShowStderr: true,
|
|
||||||
Tail: strconv.Itoa(n),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rc.Close()
|
|
||||||
|
|
||||||
pr, pw := io.Pipe()
|
|
||||||
go func() {
|
|
||||||
defer pw.Close()
|
|
||||||
if _, err := stdcopy.StdCopy(pw, pw, rc); err != nil && err != io.EOF {
|
|
||||||
logging.Warn("DockerLogStreamer.GetLastLines: stdcopy error for %s: %v", server.ServiceName, err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var lines []string
|
|
||||||
scanner := bufio.NewScanner(pr)
|
|
||||||
for scanner.Scan() {
|
|
||||||
lines = append(lines, scanner.Text())
|
|
||||||
}
|
|
||||||
return lines, scanner.Err()
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/docker/docker/api/types"
|
||||||
"github.com/docker/docker/api/types/container"
|
"github.com/docker/docker/api/types/container"
|
||||||
"github.com/docker/docker/api/types/filters"
|
"github.com/docker/docker/api/types/filters"
|
||||||
dockerclient "github.com/docker/docker/client"
|
dockerclient "github.com/docker/docker/client"
|
||||||
@@ -32,25 +33,23 @@ func NewDockerRuntime(client *dockerclient.Client, repo *repository.ServerReposi
|
|||||||
|
|
||||||
func (r *DockerRuntime) Create(ctx context.Context, server *model.Server) error {
|
func (r *DockerRuntime) Create(ctx context.Context, server *model.Server) error {
|
||||||
image := env.GetACCImage()
|
image := env.GetACCImage()
|
||||||
// ACC uses the same port number for both TCP (client connections) and UDP (car positions/ping).
|
|
||||||
portStr := strconv.Itoa(server.Port)
|
portStr := strconv.Itoa(server.Port)
|
||||||
|
natPort, err := nat.NewPort("tcp", portStr)
|
||||||
natTCP, err := nat.NewPort("tcp", portStr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("invalid port %d: %v", server.Port, err)
|
return fmt.Errorf("invalid port %d: %v", server.Port, err)
|
||||||
}
|
}
|
||||||
natUDP, err := nat.NewPort("udp", portStr)
|
natPortUDP, err := nat.NewPort("udp", portStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("invalid port %d: %v", server.Port, err)
|
return fmt.Errorf("invalid udp port %d: %v", server.Port, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
portBindings := nat.PortMap{
|
portBindings := nat.PortMap{
|
||||||
natTCP: []nat.PortBinding{{HostPort: portStr}},
|
natPort: []nat.PortBinding{{HostPort: portStr}},
|
||||||
natUDP: []nat.PortBinding{{HostPort: portStr}},
|
natPortUDP: []nat.PortBinding{{HostPort: portStr}},
|
||||||
}
|
}
|
||||||
exposedPorts := nat.PortSet{
|
exposedPorts := nat.PortSet{
|
||||||
natTCP: struct{}{},
|
natPort: struct{}{},
|
||||||
natUDP: struct{}{},
|
natPortUDP: struct{}{},
|
||||||
}
|
}
|
||||||
|
|
||||||
containerBase := env.GetACCServersPath()
|
containerBase := env.GetACCServersPath()
|
||||||
@@ -62,24 +61,17 @@ func (r *DockerRuntime) Create(ctx context.Context, server *model.Server) error
|
|||||||
fmt.Sprintf("%s:/acc/game:rw", hostServerPath),
|
fmt.Sprintf("%s:/acc/game:rw", hostServerPath),
|
||||||
}
|
}
|
||||||
|
|
||||||
hostConfig := &container.HostConfig{
|
|
||||||
Binds: binds,
|
|
||||||
PortBindings: portBindings,
|
|
||||||
RestartPolicy: container.RestartPolicy{Name: "unless-stopped"},
|
|
||||||
// NET_RAW is required for tcpdump packet capture in debug mode (DEBUG_MODE=1).
|
|
||||||
CapAdd: []string{"NET_RAW"},
|
|
||||||
}
|
|
||||||
if cpuset := env.GetACCCpuset(); cpuset != "" {
|
|
||||||
hostConfig.CpusetCpus = cpuset
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := r.client.ContainerCreate(ctx, &container.Config{
|
resp, err := r.client.ContainerCreate(ctx, &container.Config{
|
||||||
Image: image,
|
Image: image,
|
||||||
ExposedPorts: exposedPorts,
|
ExposedPorts: exposedPorts,
|
||||||
Env: []string{
|
Env: []string{
|
||||||
fmt.Sprintf("SERVER_PORT=%d", server.Port),
|
fmt.Sprintf("SERVER_PORT=%d", server.Port),
|
||||||
},
|
},
|
||||||
}, hostConfig, nil, nil, server.ServiceName)
|
}, &container.HostConfig{
|
||||||
|
Binds: binds,
|
||||||
|
PortBindings: portBindings,
|
||||||
|
RestartPolicy: container.RestartPolicy{Name: "unless-stopped"},
|
||||||
|
}, nil, nil, server.ServiceName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to create container %s: %v", server.ServiceName, err)
|
return fmt.Errorf("failed to create container %s: %v", server.ServiceName, err)
|
||||||
}
|
}
|
||||||
@@ -98,7 +90,7 @@ func (r *DockerRuntime) Delete(ctx context.Context, serverID uuid.UUID) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
err = r.client.ContainerRemove(ctx, containerID, container.RemoveOptions{
|
err = r.client.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{
|
||||||
Force: true,
|
Force: true,
|
||||||
RemoveVolumes: false,
|
RemoveVolumes: false,
|
||||||
})
|
})
|
||||||
@@ -110,20 +102,11 @@ func (r *DockerRuntime) Delete(ctx context.Context, serverID uuid.UUID) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *DockerRuntime) Start(ctx context.Context, serverID uuid.UUID) (string, error) {
|
func (r *DockerRuntime) Start(ctx context.Context, serverID uuid.UUID) (string, error) {
|
||||||
server, err := r.repo.GetByID(ctx, serverID)
|
containerID, err := r.resolveContainerID(ctx, serverID)
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed to look up server %s: %v", serverID, err)
|
|
||||||
}
|
|
||||||
if server == nil {
|
|
||||||
return "", fmt.Errorf("server %s not found", serverID)
|
|
||||||
}
|
|
||||||
|
|
||||||
containerID, err := r.ensureContainer(ctx, server)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
if err := r.client.ContainerStart(ctx, containerID, types.ContainerStartOptions{}); err != nil {
|
||||||
if err := r.client.ContainerStart(ctx, containerID, container.StartOptions{}); err != nil {
|
|
||||||
return "", fmt.Errorf("failed to start container: %v", err)
|
return "", fmt.Errorf("failed to start container: %v", err)
|
||||||
}
|
}
|
||||||
return model.StatusRunning.String(), nil
|
return model.StatusRunning.String(), nil
|
||||||
@@ -141,44 +124,16 @@ func (r *DockerRuntime) Stop(ctx context.Context, serverID uuid.UUID) (string, e
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *DockerRuntime) Restart(ctx context.Context, serverID uuid.UUID) (string, error) {
|
func (r *DockerRuntime) Restart(ctx context.Context, serverID uuid.UUID) (string, error) {
|
||||||
server, err := r.repo.GetByID(ctx, serverID)
|
containerID, err := r.resolveContainerID(ctx, serverID)
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed to look up server %s: %v", serverID, err)
|
|
||||||
}
|
|
||||||
if server == nil {
|
|
||||||
return "", fmt.Errorf("server %s not found", serverID)
|
|
||||||
}
|
|
||||||
|
|
||||||
containerID, err := r.ensureContainer(ctx, server)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.client.ContainerRestart(ctx, containerID, container.StopOptions{}); err != nil {
|
if err := r.client.ContainerRestart(ctx, containerID, container.StopOptions{}); err != nil {
|
||||||
return "", fmt.Errorf("failed to restart container: %v", err)
|
return "", fmt.Errorf("failed to restart container: %v", err)
|
||||||
}
|
}
|
||||||
return model.StatusRunning.String(), nil
|
return model.StatusRunning.String(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ensureContainer returns the container ID for a server, recreating the container
|
|
||||||
// from the server's current DB record if it no longer exists in Docker.
|
|
||||||
func (r *DockerRuntime) ensureContainer(ctx context.Context, server *model.Server) (string, error) {
|
|
||||||
if server.ContainerID != "" {
|
|
||||||
if _, err := r.client.ContainerInspect(ctx, server.ContainerID); err == nil {
|
|
||||||
return server.ContainerID, nil
|
|
||||||
}
|
|
||||||
logging.Info("Container %s for server %s no longer exists, recreating", server.ContainerID[:min(12, len(server.ContainerID))], server.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := r.Create(ctx, server); err != nil {
|
|
||||||
return "", fmt.Errorf("failed to recreate container: %v", err)
|
|
||||||
}
|
|
||||||
if err := r.repo.Update(ctx, server); err != nil {
|
|
||||||
return "", fmt.Errorf("container recreated but failed to persist container ID: %v", err)
|
|
||||||
}
|
|
||||||
return server.ContainerID, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *DockerRuntime) Status(ctx context.Context, serverID uuid.UUID) (string, error) {
|
func (r *DockerRuntime) Status(ctx context.Context, serverID uuid.UUID) (string, error) {
|
||||||
server, err := r.repo.GetByID(ctx, serverID)
|
server, err := r.repo.GetByID(ctx, serverID)
|
||||||
if err != nil || server == nil {
|
if err != nil || server == nil {
|
||||||
@@ -213,7 +168,7 @@ func (r *DockerRuntime) resolveContainerID(ctx context.Context, serverID uuid.UU
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *DockerRuntime) findContainerByName(ctx context.Context, name string) (string, error) {
|
func (r *DockerRuntime) findContainerByName(ctx context.Context, name string) (string, error) {
|
||||||
containers, err := r.client.ContainerList(ctx, container.ListOptions{
|
containers, err := r.client.ContainerList(ctx, types.ContainerListOptions{
|
||||||
All: true,
|
All: true,
|
||||||
Filters: filters.NewArgs(filters.Arg("name", "/"+name)),
|
Filters: filters.NewArgs(filters.Arg("name", "/"+name)),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -3,9 +3,7 @@ package service
|
|||||||
import (
|
import (
|
||||||
"acc-server-manager/local/model"
|
"acc-server-manager/local/model"
|
||||||
"acc-server-manager/local/utl/tracking"
|
"acc-server-manager/local/utl/tracking"
|
||||||
"bufio"
|
|
||||||
"context"
|
"context"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
@@ -38,40 +36,3 @@ func (s *FileLogStreamer) Stop(serverID uuid.UUID) {
|
|||||||
v.(*tracking.LogTailer).Stop()
|
v.(*tracking.LogTailer).Stop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *FileLogStreamer) GetLastLines(_ context.Context, server *model.Server, n int) ([]string, error) {
|
|
||||||
if n <= 0 {
|
|
||||||
return []string{}, nil
|
|
||||||
}
|
|
||||||
logPath := filepath.Join(server.GetLogPath(), "server.log")
|
|
||||||
f, err := os.Open(logPath)
|
|
||||||
if err != nil {
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
return []string{}, nil
|
|
||||||
}
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
|
|
||||||
ring := make([]string, n)
|
|
||||||
head := 0
|
|
||||||
count := 0
|
|
||||||
scanner := bufio.NewScanner(f)
|
|
||||||
for scanner.Scan() {
|
|
||||||
ring[head] = scanner.Text()
|
|
||||||
head = (head + 1) % n
|
|
||||||
if count < n {
|
|
||||||
count++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := scanner.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if count < n {
|
|
||||||
return ring[:count], nil
|
|
||||||
}
|
|
||||||
out := make([]string, n)
|
|
||||||
copy(out, ring[head:])
|
|
||||||
copy(out[n-head:], ring[:head])
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package service
|
|||||||
import (
|
import (
|
||||||
"acc-server-manager/local/model"
|
"acc-server-manager/local/model"
|
||||||
"acc-server-manager/local/repository"
|
"acc-server-manager/local/repository"
|
||||||
"acc-server-manager/local/utl/logging"
|
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
@@ -12,11 +11,10 @@ import (
|
|||||||
|
|
||||||
type LeaderboardService struct {
|
type LeaderboardService struct {
|
||||||
repo *repository.LeaderboardRepository
|
repo *repository.LeaderboardRepository
|
||||||
activityLog *ActivityLogService
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewLeaderboardService(repo *repository.LeaderboardRepository, activityLog *ActivityLogService) *LeaderboardService {
|
func NewLeaderboardService(repo *repository.LeaderboardRepository) *LeaderboardService {
|
||||||
return &LeaderboardService{repo: repo, activityLog: activityLog}
|
return &LeaderboardService{repo: repo}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns the leaderboard for a server.
|
// Get returns the leaderboard for a server.
|
||||||
@@ -25,7 +23,7 @@ func (s *LeaderboardService) Get(ctx context.Context, serverID uuid.UUID) (*mode
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update replaces the leaderboard for a server.
|
// Update replaces the leaderboard for a server.
|
||||||
func (s *LeaderboardService) Update(ctx context.Context, serverID uuid.UUID, lb *model.Leaderboard, actorID, actorUsername string) (*model.Leaderboard, error) {
|
func (s *LeaderboardService) Update(ctx context.Context, serverID uuid.UUID, lb *model.Leaderboard) (*model.Leaderboard, error) {
|
||||||
if lb == nil {
|
if lb == nil {
|
||||||
return nil, fmt.Errorf("input is required")
|
return nil, fmt.Errorf("input is required")
|
||||||
}
|
}
|
||||||
@@ -35,25 +33,5 @@ func (s *LeaderboardService) Update(ctx context.Context, serverID uuid.UUID, lb
|
|||||||
for i := range lb.Races {
|
for i := range lb.Races {
|
||||||
lb.Races[i].Position = i
|
lb.Races[i].Position = i
|
||||||
}
|
}
|
||||||
result, err := s.repo.FullReplace(ctx, serverID, lb)
|
return s.repo.FullReplace(ctx, serverID, lb)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
driverCount := len(lb.Drivers)
|
|
||||||
raceCount := len(lb.Races)
|
|
||||||
details := fmt.Sprintf(`{"driver_count":%d,"race_count":%d}`, driverCount, raceCount)
|
|
||||||
go func() {
|
|
||||||
if logErr := s.activityLog.Log(context.Background(), &model.ActivityLog{
|
|
||||||
ServerID: &serverID,
|
|
||||||
UserID: actorID,
|
|
||||||
Username: actorUsername,
|
|
||||||
Action: model.ActionLeaderboardUpdate,
|
|
||||||
Details: details,
|
|
||||||
}); logErr != nil {
|
|
||||||
logging.Error("Failed to log leaderboard update: %v", logErr)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ const (
|
|||||||
type ServerService struct {
|
type ServerService struct {
|
||||||
repository *repository.ServerRepository
|
repository *repository.ServerRepository
|
||||||
stateHistoryRepo *repository.StateHistoryRepository
|
stateHistoryRepo *repository.StateHistoryRepository
|
||||||
activityLogRepo *repository.ActivityLogRepository
|
|
||||||
apiService *ServiceControlService
|
apiService *ServiceControlService
|
||||||
configService *ConfigService
|
configService *ConfigService
|
||||||
steamService *SteamService
|
steamService *SteamService
|
||||||
@@ -48,31 +47,15 @@ type pendingState struct {
|
|||||||
|
|
||||||
func (s *ServerService) ensureLogTailing(server *model.Server, instance *tracking.AccServerInstance) {
|
func (s *ServerService) ensureLogTailing(server *model.Server, instance *tracking.AccServerInstance) {
|
||||||
go func() {
|
go func() {
|
||||||
handleFn := func(line string) {
|
if err := s.logStreamer.Start(context.Background(), server, instance.HandleLogLine); err != nil {
|
||||||
instance.HandleLogLine(line)
|
|
||||||
s.webSocketService.BroadcastLogLine(server.ID, line)
|
|
||||||
}
|
|
||||||
if err := s.logStreamer.Start(context.Background(), server, handleFn); err != nil {
|
|
||||||
logging.Error("Failed to start log streaming for server %s: %v", server.ID, err)
|
logging.Error("Failed to start log streaming for server %s: %v", server.ID, err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *ServerService) GetLastLogLines(ctx *fiber.Ctx, serverID uuid.UUID, n int) ([]string, error) {
|
|
||||||
server, err := s.repository.GetByID(ctx.UserContext(), serverID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if n <= 0 {
|
|
||||||
n = 100
|
|
||||||
}
|
|
||||||
return s.logStreamer.GetLastLines(ctx.UserContext(), server, n)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewServerService(
|
func NewServerService(
|
||||||
repository *repository.ServerRepository,
|
repository *repository.ServerRepository,
|
||||||
stateHistoryRepo *repository.StateHistoryRepository,
|
stateHistoryRepo *repository.StateHistoryRepository,
|
||||||
activityLogRepo *repository.ActivityLogRepository,
|
|
||||||
apiService *ServiceControlService,
|
apiService *ServiceControlService,
|
||||||
configService *ConfigService,
|
configService *ConfigService,
|
||||||
steamService *SteamService,
|
steamService *SteamService,
|
||||||
@@ -85,7 +68,6 @@ func NewServerService(
|
|||||||
service := &ServerService{
|
service := &ServerService{
|
||||||
repository: repository,
|
repository: repository,
|
||||||
stateHistoryRepo: stateHistoryRepo,
|
stateHistoryRepo: stateHistoryRepo,
|
||||||
activityLogRepo: activityLogRepo,
|
|
||||||
apiService: apiService,
|
apiService: apiService,
|
||||||
configService: configService,
|
configService: configService,
|
||||||
steamService: steamService,
|
steamService: steamService,
|
||||||
@@ -284,16 +266,6 @@ func (s *ServerService) GetAll(ctx *fiber.Ctx, filter *model.ServerFilter) (*[]m
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Collect server IDs for a single last-activity lookup.
|
|
||||||
serverIDs := make([]uuid.UUID, len(*servers))
|
|
||||||
for i, srv := range *servers {
|
|
||||||
serverIDs[i] = srv.ID
|
|
||||||
}
|
|
||||||
lastActivities, laErr := s.activityLogRepo.GetLastActivityByServerIDs(ctx.UserContext(), serverIDs)
|
|
||||||
if laErr != nil {
|
|
||||||
logging.Error("Failed to get last activities for server list: %v", laErr)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := range *servers {
|
for i := range *servers {
|
||||||
server := &(*servers)[i]
|
server := &(*servers)[i]
|
||||||
status, err := s.apiService.GetCachedStatus(server.ServiceName)
|
status, err := s.apiService.GetCachedStatus(server.ServiceName)
|
||||||
@@ -310,11 +282,6 @@ func (s *ServerService) GetAll(ctx *fiber.Ctx, filter *model.ServerFilter) (*[]m
|
|||||||
server.State = serverInstance.State
|
server.State = serverInstance.State
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if lastActivities != nil {
|
|
||||||
if info, ok := lastActivities[server.ID]; ok {
|
|
||||||
server.LastActivity = info
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return servers, nil
|
return servers, nil
|
||||||
@@ -436,10 +403,6 @@ func (s *ServerService) createServerBackground(ctx context.Context, server *mode
|
|||||||
return "", fmt.Errorf("failed to update server configuration: %v", err)
|
return "", fmt.Errorf("failed to update server configuration: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := s.configService.SetServerName(server, server.Name); err != nil {
|
|
||||||
logging.Error("Failed to set server name in config: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return fmt.Sprintf("Server configuration generated (Port: %d)", serverPort), nil
|
return fmt.Sprintf("Server configuration generated (Port: %d)", serverPort), nil
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -611,17 +574,10 @@ func (s *ServerService) updateServerPort(server *model.Server, port int) error {
|
|||||||
|
|
||||||
config.TcpPort = model.IntString(port)
|
config.TcpPort = model.IntString(port)
|
||||||
config.UdpPort = model.IntString(port)
|
config.UdpPort = model.IntString(port)
|
||||||
config.RegisterToLobby = model.IntString(1)
|
|
||||||
|
|
||||||
if err := s.configService.SaveConfiguration(server, config); err != nil {
|
if err := s.configService.SaveConfiguration(server, config); err != nil {
|
||||||
return fmt.Errorf("failed to save server configuration: %v", err)
|
return fmt.Errorf("failed to save server configuration: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if env.IsDockerPlatform() {
|
|
||||||
if err := s.configService.SetIgnorePrematureDisconnects(server, 0); err != nil {
|
|
||||||
logging.Error("Failed to set ignorePrematureDisconnects for Docker server: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ func InitializeServices(c *dig.Container) {
|
|||||||
|
|
||||||
logging.Debug("Registering services")
|
logging.Debug("Registering services")
|
||||||
c.Provide(NewSteamService)
|
c.Provide(NewSteamService)
|
||||||
c.Provide(NewActivityLogService)
|
|
||||||
c.Provide(NewServerService)
|
c.Provide(NewServerService)
|
||||||
c.Provide(NewStateHistoryService)
|
c.Provide(NewStateHistoryService)
|
||||||
c.Provide(NewServiceControlService)
|
c.Provide(NewServiceControlService)
|
||||||
@@ -32,7 +31,6 @@ func InitializeServices(c *dig.Container) {
|
|||||||
c.Provide(NewMembershipService)
|
c.Provide(NewMembershipService)
|
||||||
c.Provide(NewWebSocketService)
|
c.Provide(NewWebSocketService)
|
||||||
c.Provide(NewLeaderboardService)
|
c.Provide(NewLeaderboardService)
|
||||||
c.Provide(NewConfigPresetService)
|
|
||||||
|
|
||||||
// Always provide the PortPoolManager; in Windows mode it seeds from an
|
// Always provide the PortPoolManager; in Windows mode it seeds from an
|
||||||
// empty result set and sits idle.
|
// empty result set and sits idle.
|
||||||
@@ -100,7 +98,4 @@ func registerDockerProviders(c *dig.Container) {
|
|||||||
c.Provide(func(client *dockerclient.Client) platform.LogStreamer {
|
c.Provide(func(client *dockerclient.Client) platform.LogStreamer {
|
||||||
return NewDockerLogStreamer(client)
|
return NewDockerLogStreamer(client)
|
||||||
})
|
})
|
||||||
|
|
||||||
c.Provide(NewSystemService)
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ type ServiceControlService struct {
|
|||||||
repository *repository.ServiceControlRepository
|
repository *repository.ServiceControlRepository
|
||||||
serverRepository *repository.ServerRepository
|
serverRepository *repository.ServerRepository
|
||||||
serverService *ServerService
|
serverService *ServerService
|
||||||
activityLog *ActivityLogService
|
|
||||||
statusCache *model.ServerStatusCache
|
statusCache *model.ServerStatusCache
|
||||||
runtime platform.ServerRuntime
|
runtime platform.ServerRuntime
|
||||||
}
|
}
|
||||||
@@ -24,13 +23,11 @@ func NewServiceControlService(
|
|||||||
repository *repository.ServiceControlRepository,
|
repository *repository.ServiceControlRepository,
|
||||||
serverRepository *repository.ServerRepository,
|
serverRepository *repository.ServerRepository,
|
||||||
runtime platform.ServerRuntime,
|
runtime platform.ServerRuntime,
|
||||||
activityLog *ActivityLogService,
|
|
||||||
) *ServiceControlService {
|
) *ServiceControlService {
|
||||||
return &ServiceControlService{
|
return &ServiceControlService{
|
||||||
repository: repository,
|
repository: repository,
|
||||||
serverRepository: serverRepository,
|
serverRepository: serverRepository,
|
||||||
runtime: runtime,
|
runtime: runtime,
|
||||||
activityLog: activityLog,
|
|
||||||
statusCache: model.NewServerStatusCache(model.CacheConfig{
|
statusCache: model.NewServerStatusCache(model.CacheConfig{
|
||||||
ExpirationTime: 30 * time.Second,
|
ExpirationTime: 30 * time.Second,
|
||||||
ThrottleTime: 5 * time.Second,
|
ThrottleTime: 5 * time.Second,
|
||||||
@@ -39,28 +36,6 @@ func NewServiceControlService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// getServerFromCtx resolves the server from ctx locals (serverId or service name).
|
|
||||||
func (as *ServiceControlService) getServerFromCtx(ctx *fiber.Ctx) (*model.Server, error) {
|
|
||||||
serviceName, ok := ctx.Locals("service").(string)
|
|
||||||
if !ok || serviceName == "" {
|
|
||||||
serverId, ok2 := ctx.Locals("serverId").(string)
|
|
||||||
if !ok2 || serverId == "" {
|
|
||||||
return nil, errors.New("service name missing")
|
|
||||||
}
|
|
||||||
return as.serverRepository.GetByID(ctx.UserContext(), serverId)
|
|
||||||
}
|
|
||||||
return as.serverRepository.GetFirstByServiceName(ctx.UserContext(), serviceName)
|
|
||||||
}
|
|
||||||
|
|
||||||
func extractActor(ctx *fiber.Ctx) (actorID, actorUsername string) {
|
|
||||||
actorID, _ = ctx.Locals("userID").(string)
|
|
||||||
actorUsername, _ = ctx.Locals("actorUsername").(string)
|
|
||||||
if actorUsername == "" {
|
|
||||||
actorUsername = "system"
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (as *ServiceControlService) SetServerService(serverService *ServerService) {
|
func (as *ServiceControlService) SetServerService(serverService *ServerService) {
|
||||||
as.serverService = serverService
|
as.serverService = serverService
|
||||||
}
|
}
|
||||||
@@ -86,11 +61,10 @@ func (as *ServiceControlService) GetStatus(ctx *fiber.Ctx) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (as *ServiceControlService) ServiceControlStartServer(ctx *fiber.Ctx) (string, error) {
|
func (as *ServiceControlService) ServiceControlStartServer(ctx *fiber.Ctx) (string, error) {
|
||||||
server, err := as.getServerFromCtx(ctx)
|
serviceName, err := as.GetServiceName(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
serviceName := server.ServiceName
|
|
||||||
|
|
||||||
as.statusCache.UpdateStatus(serviceName, model.StatusStarting)
|
as.statusCache.UpdateStatus(serviceName, model.StatusStarting)
|
||||||
|
|
||||||
@@ -105,29 +79,14 @@ func (as *ServiceControlService) ServiceControlStartServer(ctx *fiber.Ctx) (stri
|
|||||||
|
|
||||||
status := model.ParseServiceStatus(statusStr)
|
status := model.ParseServiceStatus(statusStr)
|
||||||
as.statusCache.UpdateStatus(serviceName, status)
|
as.statusCache.UpdateStatus(serviceName, status)
|
||||||
|
|
||||||
if as.activityLog != nil {
|
|
||||||
actorID, actorUsername := extractActor(ctx)
|
|
||||||
go func() {
|
|
||||||
_ = as.activityLog.Log(context.Background(), &model.ActivityLog{
|
|
||||||
ServerID: &server.ID,
|
|
||||||
UserID: actorID,
|
|
||||||
Username: actorUsername,
|
|
||||||
Action: model.ActionServerStart,
|
|
||||||
Details: `{"service":"` + serviceName + `"}`,
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
return status.String(), nil
|
return status.String(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (as *ServiceControlService) ServiceControlStopServer(ctx *fiber.Ctx) (string, error) {
|
func (as *ServiceControlService) ServiceControlStopServer(ctx *fiber.Ctx) (string, error) {
|
||||||
server, err := as.getServerFromCtx(ctx)
|
serviceName, err := as.GetServiceName(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
serviceName := server.ServiceName
|
|
||||||
|
|
||||||
as.statusCache.UpdateStatus(serviceName, model.StatusStopping)
|
as.statusCache.UpdateStatus(serviceName, model.StatusStopping)
|
||||||
|
|
||||||
@@ -142,29 +101,14 @@ func (as *ServiceControlService) ServiceControlStopServer(ctx *fiber.Ctx) (strin
|
|||||||
|
|
||||||
status := model.ParseServiceStatus(statusStr)
|
status := model.ParseServiceStatus(statusStr)
|
||||||
as.statusCache.UpdateStatus(serviceName, status)
|
as.statusCache.UpdateStatus(serviceName, status)
|
||||||
|
|
||||||
if as.activityLog != nil {
|
|
||||||
actorID, actorUsername := extractActor(ctx)
|
|
||||||
go func() {
|
|
||||||
_ = as.activityLog.Log(context.Background(), &model.ActivityLog{
|
|
||||||
ServerID: &server.ID,
|
|
||||||
UserID: actorID,
|
|
||||||
Username: actorUsername,
|
|
||||||
Action: model.ActionServerStop,
|
|
||||||
Details: `{"service":"` + serviceName + `"}`,
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
return status.String(), nil
|
return status.String(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (as *ServiceControlService) ServiceControlRestartServer(ctx *fiber.Ctx) (string, error) {
|
func (as *ServiceControlService) ServiceControlRestartServer(ctx *fiber.Ctx) (string, error) {
|
||||||
server, err := as.getServerFromCtx(ctx)
|
serviceName, err := as.GetServiceName(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
serviceName := server.ServiceName
|
|
||||||
|
|
||||||
as.statusCache.UpdateStatus(serviceName, model.StatusRestarting)
|
as.statusCache.UpdateStatus(serviceName, model.StatusRestarting)
|
||||||
|
|
||||||
@@ -179,20 +123,6 @@ func (as *ServiceControlService) ServiceControlRestartServer(ctx *fiber.Ctx) (st
|
|||||||
|
|
||||||
status := model.ParseServiceStatus(statusStr)
|
status := model.ParseServiceStatus(statusStr)
|
||||||
as.statusCache.UpdateStatus(serviceName, status)
|
as.statusCache.UpdateStatus(serviceName, status)
|
||||||
|
|
||||||
if as.activityLog != nil {
|
|
||||||
actorID, actorUsername := extractActor(ctx)
|
|
||||||
go func() {
|
|
||||||
_ = as.activityLog.Log(context.Background(), &model.ActivityLog{
|
|
||||||
ServerID: &server.ID,
|
|
||||||
UserID: actorID,
|
|
||||||
Username: actorUsername,
|
|
||||||
Action: model.ActionServerRestart,
|
|
||||||
Details: `{"service":"` + serviceName + `"}`,
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
return status.String(), nil
|
return status.String(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,112 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"acc-server-manager/local/model"
|
|
||||||
"acc-server-manager/local/platform"
|
|
||||||
"acc-server-manager/local/repository"
|
|
||||||
"acc-server-manager/local/utl/env"
|
|
||||||
"acc-server-manager/local/utl/logging"
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/docker/docker/api/types/container"
|
|
||||||
dockerclient "github.com/docker/docker/client"
|
|
||||||
)
|
|
||||||
|
|
||||||
type SystemService struct {
|
|
||||||
dockerClient *dockerclient.Client
|
|
||||||
repo *repository.ServerRepository
|
|
||||||
runtime platform.ServerRuntime
|
|
||||||
serverService *ServerService
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSystemService(
|
|
||||||
dockerClient *dockerclient.Client,
|
|
||||||
repo *repository.ServerRepository,
|
|
||||||
runtime platform.ServerRuntime,
|
|
||||||
serverService *ServerService,
|
|
||||||
) *SystemService {
|
|
||||||
return &SystemService{
|
|
||||||
dockerClient: dockerClient,
|
|
||||||
repo: repo,
|
|
||||||
runtime: runtime,
|
|
||||||
serverService: serverService,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SystemService) MigrateImage(ctx context.Context, stopRunning bool) (*model.MigrationResult, error) {
|
|
||||||
image := env.GetACCImage()
|
|
||||||
|
|
||||||
servers, err := s.repo.GetAll(ctx, &model.ServerFilter{})
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to list servers: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
result := &model.MigrationResult{Image: image}
|
|
||||||
|
|
||||||
for _, server := range *servers {
|
|
||||||
statusStr, _ := s.runtime.Status(ctx, server.ID)
|
|
||||||
isRunning := statusStr == model.StatusRunning.String()
|
|
||||||
|
|
||||||
if isRunning && !stopRunning {
|
|
||||||
result.Skipped = append(result.Skipped, model.ServerMigrationEntry{
|
|
||||||
ID: server.ID.String(),
|
|
||||||
Name: server.Name,
|
|
||||||
WasRunning: true,
|
|
||||||
})
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
entry := model.ServerMigrationEntry{
|
|
||||||
ID: server.ID.String(),
|
|
||||||
Name: server.Name,
|
|
||||||
WasRunning: isRunning,
|
|
||||||
}
|
|
||||||
|
|
||||||
if isRunning {
|
|
||||||
if _, err := s.runtime.Stop(ctx, server.ID); err != nil {
|
|
||||||
result.Failed = append(result.Failed, model.ServerMigrationError{
|
|
||||||
ID: server.ID.String(),
|
|
||||||
Name: server.Name,
|
|
||||||
Error: fmt.Sprintf("stop failed: %v", err),
|
|
||||||
})
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if server.ContainerID != "" {
|
|
||||||
if err := s.dockerClient.ContainerRemove(ctx, server.ContainerID, container.RemoveOptions{Force: true}); err != nil {
|
|
||||||
logging.Warn("Failed to remove container %s for server %s: %v", server.ContainerID, server.ID, err)
|
|
||||||
}
|
|
||||||
server.ContainerID = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.runtime.Create(ctx, &server); err != nil {
|
|
||||||
result.Failed = append(result.Failed, model.ServerMigrationError{
|
|
||||||
ID: server.ID.String(),
|
|
||||||
Name: server.Name,
|
|
||||||
Error: fmt.Sprintf("recreate failed: %v", err),
|
|
||||||
})
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if err := s.repo.Update(ctx, &server); err != nil {
|
|
||||||
logging.Warn("Failed to persist new ContainerID for server %s: %v", server.ID, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if isRunning {
|
|
||||||
if _, err := s.runtime.Start(ctx, server.ID); err != nil {
|
|
||||||
result.Failed = append(result.Failed, model.ServerMigrationError{
|
|
||||||
ID: server.ID.String(),
|
|
||||||
Name: server.Name,
|
|
||||||
Error: fmt.Sprintf("restart failed: %v", err),
|
|
||||||
})
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
s.serverService.StartAccServerRuntime(&server)
|
|
||||||
}
|
|
||||||
|
|
||||||
result.Migrated = append(result.Migrated, entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
@@ -103,16 +103,6 @@ func (ws *WebSocketService) BroadcastError(serverID uuid.UUID, error string, det
|
|||||||
ws.broadcastToServer(serverID, wsMsg)
|
ws.broadcastToServer(serverID, wsMsg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ws *WebSocketService) BroadcastLogLine(serverID uuid.UUID, line string) {
|
|
||||||
msg := model.WebSocketMessage{
|
|
||||||
Type: model.MessageTypeLogLine,
|
|
||||||
ServerID: &serverID,
|
|
||||||
Timestamp: time.Now().Unix(),
|
|
||||||
Data: model.LogLineMessage{Line: line},
|
|
||||||
}
|
|
||||||
ws.broadcastToServer(serverID, msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WebSocketService) BroadcastComplete(serverID uuid.UUID, success bool, message string) {
|
func (ws *WebSocketService) BroadcastComplete(serverID uuid.UUID, success bool, message string) {
|
||||||
completeMsg := model.CompleteMessage{
|
completeMsg := model.CompleteMessage{
|
||||||
ServerID: serverID,
|
ServerID: serverID,
|
||||||
|
|||||||
@@ -28,10 +28,6 @@ type RouteGroups struct {
|
|||||||
WebSocket fiber.Router
|
WebSocket fiber.Router
|
||||||
Leaderboard fiber.Router
|
Leaderboard fiber.Router
|
||||||
Steam fiber.Router
|
Steam fiber.Router
|
||||||
ActivityLog fiber.Router
|
|
||||||
Groups fiber.Router
|
|
||||||
Log fiber.Router
|
|
||||||
Presets fiber.Router
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func CheckError(err error) {
|
func CheckError(err error) {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
Version = "0.13.1"
|
Version = "0.10.7"
|
||||||
Prefix = "v1"
|
Prefix = "v1"
|
||||||
Secret string
|
Secret string
|
||||||
SecretCode string
|
SecretCode string
|
||||||
|
|||||||
@@ -54,8 +54,6 @@ func Migrate(db *gorm.DB) {
|
|||||||
&model.LeaderboardRace{},
|
&model.LeaderboardRace{},
|
||||||
&model.LeaderboardResult{},
|
&model.LeaderboardResult{},
|
||||||
&model.LeaderboardPointRow{},
|
&model.LeaderboardPointRow{},
|
||||||
&model.ActivityLog{},
|
|
||||||
&model.ConfigPreset{},
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -82,14 +80,6 @@ func runMigrations(db *gorm.DB) {
|
|||||||
logging.Error("Failed to run platform columns migration: %v", err)
|
logging.Error("Failed to run platform columns migration: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := migrations.RunAddActivityLogMigration(db); err != nil {
|
|
||||||
logging.Error("Failed to run activity log migration: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := migrations.RunAddConfigPresetsMigration(db); err != nil {
|
|
||||||
logging.Error("Failed to run config presets migration: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
logging.Info("Custom database migrations completed")
|
logging.Info("Custom database migrations completed")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
4
local/utl/env/env.go
vendored
4
local/utl/env/env.go
vendored
@@ -65,10 +65,6 @@ func GetACCServersPath() string {
|
|||||||
return DefaultACCServersPath
|
return DefaultACCServersPath
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetACCCpuset() string {
|
|
||||||
return os.Getenv("ACC_CPUSET")
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetACCServersHostPath() string {
|
func GetACCServersHostPath() string {
|
||||||
if p := os.Getenv("ACC_SERVERS_HOST_PATH"); p != "" {
|
if p := os.Getenv("ACC_SERVERS_HOST_PATH"); p != "" {
|
||||||
return p
|
return p
|
||||||
|
|||||||
@@ -1,116 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# migrate-wine.sh — Pull the latest acc-wine image and migrate all server containers.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# ./scripts/migrate-wine.sh -u <username> -p <password> -b <base_url> [--stop-running]
|
|
||||||
#
|
|
||||||
# Options:
|
|
||||||
# -u, --username API username
|
|
||||||
# -p, --password API password
|
|
||||||
# -b, --base-url Base URL of the manager (e.g. http://192.168.0.177:3000)
|
|
||||||
# --stop-running Also migrate currently running servers (stop → migrate → restart)
|
|
||||||
#
|
|
||||||
# Examples:
|
|
||||||
# ./scripts/migrate-wine.sh -u admin -p secret -b http://192.168.0.177:3000
|
|
||||||
# ./scripts/migrate-wine.sh -u admin -p secret -b http://192.168.0.177:3000 --stop-running
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# ── Argument parsing ────────────────────────────────────────────────────────────
|
|
||||||
USERNAME=""
|
|
||||||
PASSWORD=""
|
|
||||||
BASE_URL=""
|
|
||||||
STOP_RUNNING=false
|
|
||||||
|
|
||||||
usage() {
|
|
||||||
grep '^#' "$0" | sed 's/^# \{0,1\}//' | tail -n +2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
while [[ $# -gt 0 ]]; do
|
|
||||||
case "$1" in
|
|
||||||
-u|--username) USERNAME="$2"; shift 2 ;;
|
|
||||||
-p|--password) PASSWORD="$2"; shift 2 ;;
|
|
||||||
-b|--base-url) BASE_URL="$2"; shift 2 ;;
|
|
||||||
--stop-running) STOP_RUNNING=true; shift ;;
|
|
||||||
-h|--help) usage ;;
|
|
||||||
*) echo "Unknown option: $1"; usage ;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
[[ -z "$USERNAME" ]] && { echo "Error: --username is required"; usage; }
|
|
||||||
[[ -z "$PASSWORD" ]] && { echo "Error: --password is required"; usage; }
|
|
||||||
[[ -z "$BASE_URL" ]] && { echo "Error: --base-url is required"; usage; }
|
|
||||||
|
|
||||||
BASE_URL="${BASE_URL%/}" # strip trailing slash
|
|
||||||
BASE_URL="${BASE_URL/#http:\/\//https://}" # upgrade http → https
|
|
||||||
|
|
||||||
# ── Check dependencies ──────────────────────────────────────────────────────────
|
|
||||||
for cmd in curl jq; do
|
|
||||||
command -v "$cmd" &>/dev/null || { echo "Error: '$cmd' is required but not installed."; exit 1; }
|
|
||||||
done
|
|
||||||
|
|
||||||
# ── Login ───────────────────────────────────────────────────────────────────────
|
|
||||||
echo "Logging in as '$USERNAME'..."
|
|
||||||
|
|
||||||
LOGIN_RESPONSE=$(curl -sL --post301 --post302 -X POST "${BASE_URL}/v1/auth/login" \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-d "$(jq -n --arg u "$USERNAME" --arg p "$PASSWORD" '{username: $u, password: $p}')")
|
|
||||||
|
|
||||||
TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.token // empty' 2>/dev/null || true)
|
|
||||||
if [[ -z "$TOKEN" ]]; then
|
|
||||||
echo "Error: Login failed — no token in response."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "Login successful."
|
|
||||||
|
|
||||||
# ── Migrate ─────────────────────────────────────────────────────────────────────
|
|
||||||
echo "Starting image migration (stopRunning=${STOP_RUNNING})..."
|
|
||||||
|
|
||||||
MIGRATE_RESPONSE=$(curl -sL --post301 --post302 -X POST "${BASE_URL}/v1/system/migrate-image" \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-H "Authorization: Bearer ${TOKEN}" \
|
|
||||||
-d "{\"stopRunning\":${STOP_RUNNING}}")
|
|
||||||
|
|
||||||
# ── Results ──────────────────────────────────────────────────────────────────────
|
|
||||||
SERVER_ERROR=$(echo "$MIGRATE_RESPONSE" | jq -r '.error // empty' 2>/dev/null || true)
|
|
||||||
if [[ -n "$SERVER_ERROR" ]]; then
|
|
||||||
echo "Error: Migration failed — $SERVER_ERROR"
|
|
||||||
echo "Full response: $MIGRATE_RESPONSE"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
IMAGE=$(echo "$MIGRATE_RESPONSE" | jq -r '.image')
|
|
||||||
MIGRATED=$(echo "$MIGRATE_RESPONSE" | jq -r '.migrated | length')
|
|
||||||
SKIPPED=$(echo "$MIGRATE_RESPONSE" | jq -r '.skipped | length')
|
|
||||||
FAILED=$(echo "$MIGRATE_RESPONSE" | jq -r '.failed | length')
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "Image: ${IMAGE}"
|
|
||||||
echo "────────────────────────────────"
|
|
||||||
printf " Migrated : %s\n" "$MIGRATED"
|
|
||||||
printf " Skipped : %s\n" "$SKIPPED"
|
|
||||||
printf " Failed : %s\n" "$FAILED"
|
|
||||||
echo "────────────────────────────────"
|
|
||||||
|
|
||||||
if [[ "$MIGRATED" -gt 0 ]]; then
|
|
||||||
echo ""
|
|
||||||
echo "Migrated servers:"
|
|
||||||
echo "$MIGRATE_RESPONSE" | jq -r '.migrated[] | " - \(.name) (wasRunning: \(.wasRunning))"'
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "$SKIPPED" -gt 0 ]]; then
|
|
||||||
echo ""
|
|
||||||
echo "Skipped (running, use --stop-running to include):"
|
|
||||||
echo "$MIGRATE_RESPONSE" | jq -r '.skipped[] | " - \(.name)"'
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "$FAILED" -gt 0 ]]; then
|
|
||||||
echo ""
|
|
||||||
echo "Failed:"
|
|
||||||
echo "$MIGRATE_RESPONSE" | jq -r '.failed[] | " - \(.name): \(.error)"'
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "Done."
|
|
||||||
@@ -109,7 +109,7 @@ func createTestData(t *testing.T, tempDir string) *TestData {
|
|||||||
configFiles := map[string]string{
|
configFiles := map[string]string{
|
||||||
"configuration.json": `{
|
"configuration.json": `{
|
||||||
"udpPort": "9231",
|
"udpPort": "9231",
|
||||||
"tcpPort": "9231",
|
"tcpPort": "9232",
|
||||||
"maxConnections": "30",
|
"maxConnections": "30",
|
||||||
"lanDiscovery": "1",
|
"lanDiscovery": "1",
|
||||||
"registerToLobby": "1",
|
"registerToLobby": "1",
|
||||||
@@ -198,7 +198,7 @@ func createTestData(t *testing.T, tempDir string) *TestData {
|
|||||||
|
|
||||||
sampleConfig := &model.Configuration{
|
sampleConfig := &model.Configuration{
|
||||||
UdpPort: model.IntString(9231),
|
UdpPort: model.IntString(9231),
|
||||||
TcpPort: model.IntString(9231),
|
TcpPort: model.IntString(9232),
|
||||||
MaxConnections: model.IntString(30),
|
MaxConnections: model.IntString(30),
|
||||||
LanDiscovery: model.IntString(1),
|
LanDiscovery: model.IntString(1),
|
||||||
RegisterToLobby: model.IntString(1),
|
RegisterToLobby: model.IntString(1),
|
||||||
|
|||||||
@@ -294,7 +294,7 @@ func TestController_ConfigurationModel_JSONSerialization(t *testing.T) {
|
|||||||
app.Get("/config", func(c *fiber.Ctx) error {
|
app.Get("/config", func(c *fiber.Ctx) error {
|
||||||
config := &model.Configuration{
|
config := &model.Configuration{
|
||||||
UdpPort: model.IntString(9231),
|
UdpPort: model.IntString(9231),
|
||||||
TcpPort: model.IntString(9231),
|
TcpPort: model.IntString(9232),
|
||||||
MaxConnections: model.IntString(30),
|
MaxConnections: model.IntString(30),
|
||||||
LanDiscovery: model.IntString(1),
|
LanDiscovery: model.IntString(1),
|
||||||
RegisterToLobby: model.IntString(1),
|
RegisterToLobby: model.IntString(1),
|
||||||
@@ -316,7 +316,7 @@ func TestController_ConfigurationModel_JSONSerialization(t *testing.T) {
|
|||||||
tests.AssertNoError(t, err)
|
tests.AssertNoError(t, err)
|
||||||
|
|
||||||
tests.AssertEqual(t, model.IntString(9231), response.UdpPort)
|
tests.AssertEqual(t, model.IntString(9231), response.UdpPort)
|
||||||
tests.AssertEqual(t, model.IntString(9231), response.TcpPort)
|
tests.AssertEqual(t, model.IntString(9232), response.TcpPort)
|
||||||
tests.AssertEqual(t, model.IntString(30), response.MaxConnections)
|
tests.AssertEqual(t, model.IntString(30), response.MaxConnections)
|
||||||
tests.AssertEqual(t, model.IntString(1), response.LanDiscovery)
|
tests.AssertEqual(t, model.IntString(1), response.LanDiscovery)
|
||||||
tests.AssertEqual(t, model.IntString(1), response.RegisterToLobby)
|
tests.AssertEqual(t, model.IntString(1), response.RegisterToLobby)
|
||||||
|
|||||||
@@ -464,7 +464,7 @@ func TestServerConfigCache_Configuration(t *testing.T) {
|
|||||||
serverID := uuid.New().String()
|
serverID := uuid.New().String()
|
||||||
configuration := model.Configuration{
|
configuration := model.Configuration{
|
||||||
UdpPort: model.IntString(9231),
|
UdpPort: model.IntString(9231),
|
||||||
TcpPort: model.IntString(9231),
|
TcpPort: model.IntString(9232),
|
||||||
MaxConnections: model.IntString(30),
|
MaxConnections: model.IntString(30),
|
||||||
LanDiscovery: model.IntString(1),
|
LanDiscovery: model.IntString(1),
|
||||||
RegisterToLobby: model.IntString(1),
|
RegisterToLobby: model.IntString(1),
|
||||||
|
|||||||
@@ -20,14 +20,14 @@ func TestConfigService_GetConfiguration_ValidFile(t *testing.T) {
|
|||||||
|
|
||||||
configRepo := repository.NewConfigRepository(helper.DB)
|
configRepo := repository.NewConfigRepository(helper.DB)
|
||||||
serverRepo := repository.NewServerRepository(helper.DB)
|
serverRepo := repository.NewServerRepository(helper.DB)
|
||||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
configService := service.NewConfigService(configRepo, serverRepo)
|
||||||
|
|
||||||
config, err := configService.GetConfiguration(helper.TestData.Server)
|
config, err := configService.GetConfiguration(helper.TestData.Server)
|
||||||
tests.AssertNoError(t, err)
|
tests.AssertNoError(t, err)
|
||||||
tests.AssertNotNil(t, config)
|
tests.AssertNotNil(t, config)
|
||||||
|
|
||||||
tests.AssertEqual(t, model.IntString(9231), config.UdpPort)
|
tests.AssertEqual(t, model.IntString(9231), config.UdpPort)
|
||||||
tests.AssertEqual(t, model.IntString(9231), config.TcpPort)
|
tests.AssertEqual(t, model.IntString(9232), config.TcpPort)
|
||||||
tests.AssertEqual(t, model.IntString(30), config.MaxConnections)
|
tests.AssertEqual(t, model.IntString(30), config.MaxConnections)
|
||||||
tests.AssertEqual(t, model.IntString(1), config.LanDiscovery)
|
tests.AssertEqual(t, model.IntString(1), config.LanDiscovery)
|
||||||
tests.AssertEqual(t, model.IntString(1), config.RegisterToLobby)
|
tests.AssertEqual(t, model.IntString(1), config.RegisterToLobby)
|
||||||
@@ -43,7 +43,7 @@ func TestConfigService_GetEventConfig_ValidFile(t *testing.T) {
|
|||||||
|
|
||||||
configRepo := repository.NewConfigRepository(helper.DB)
|
configRepo := repository.NewConfigRepository(helper.DB)
|
||||||
serverRepo := repository.NewServerRepository(helper.DB)
|
serverRepo := repository.NewServerRepository(helper.DB)
|
||||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
configService := service.NewConfigService(configRepo, serverRepo)
|
||||||
|
|
||||||
eventConfig, err := configService.GetEventConfig(helper.TestData.Server)
|
eventConfig, err := configService.GetEventConfig(helper.TestData.Server)
|
||||||
tests.AssertNoError(t, err)
|
tests.AssertNoError(t, err)
|
||||||
@@ -73,7 +73,7 @@ func TestConfigService_SaveConfiguration_Success(t *testing.T) {
|
|||||||
|
|
||||||
configRepo := repository.NewConfigRepository(helper.DB)
|
configRepo := repository.NewConfigRepository(helper.DB)
|
||||||
serverRepo := repository.NewServerRepository(helper.DB)
|
serverRepo := repository.NewServerRepository(helper.DB)
|
||||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
configService := service.NewConfigService(configRepo, serverRepo)
|
||||||
|
|
||||||
newConfig := &model.Configuration{
|
newConfig := &model.Configuration{
|
||||||
UdpPort: model.IntString(9999),
|
UdpPort: model.IntString(9999),
|
||||||
@@ -115,14 +115,14 @@ func TestConfigService_LoadConfigs_Success(t *testing.T) {
|
|||||||
|
|
||||||
configRepo := repository.NewConfigRepository(helper.DB)
|
configRepo := repository.NewConfigRepository(helper.DB)
|
||||||
serverRepo := repository.NewServerRepository(helper.DB)
|
serverRepo := repository.NewServerRepository(helper.DB)
|
||||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
configService := service.NewConfigService(configRepo, serverRepo)
|
||||||
|
|
||||||
configs, err := configService.LoadConfigs(helper.TestData.Server)
|
configs, err := configService.LoadConfigs(helper.TestData.Server)
|
||||||
tests.AssertNoError(t, err)
|
tests.AssertNoError(t, err)
|
||||||
tests.AssertNotNil(t, configs)
|
tests.AssertNotNil(t, configs)
|
||||||
|
|
||||||
tests.AssertEqual(t, model.IntString(9231), configs.Configuration.UdpPort)
|
tests.AssertEqual(t, model.IntString(9231), configs.Configuration.UdpPort)
|
||||||
tests.AssertEqual(t, model.IntString(9231), configs.Configuration.TcpPort)
|
tests.AssertEqual(t, model.IntString(9232), configs.Configuration.TcpPort)
|
||||||
tests.AssertEqual(t, "Test ACC Server", configs.Settings.ServerName)
|
tests.AssertEqual(t, "Test ACC Server", configs.Settings.ServerName)
|
||||||
tests.AssertEqual(t, "admin123", configs.Settings.AdminPassword)
|
tests.AssertEqual(t, "admin123", configs.Settings.AdminPassword)
|
||||||
tests.AssertEqual(t, "spa", configs.Event.Track)
|
tests.AssertEqual(t, "spa", configs.Event.Track)
|
||||||
@@ -142,7 +142,7 @@ func TestConfigService_MalformedJSON(t *testing.T) {
|
|||||||
|
|
||||||
configRepo := repository.NewConfigRepository(helper.DB)
|
configRepo := repository.NewConfigRepository(helper.DB)
|
||||||
serverRepo := repository.NewServerRepository(helper.DB)
|
serverRepo := repository.NewServerRepository(helper.DB)
|
||||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
configService := service.NewConfigService(configRepo, serverRepo)
|
||||||
|
|
||||||
config, err := configService.GetConfiguration(helper.TestData.Server)
|
config, err := configService.GetConfiguration(helper.TestData.Server)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -245,7 +245,7 @@ func TestConfigService_Caching_Configuration(t *testing.T) {
|
|||||||
|
|
||||||
configRepo := repository.NewConfigRepository(helper.DB)
|
configRepo := repository.NewConfigRepository(helper.DB)
|
||||||
serverRepo := repository.NewServerRepository(helper.DB)
|
serverRepo := repository.NewServerRepository(helper.DB)
|
||||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
configService := service.NewConfigService(configRepo, serverRepo)
|
||||||
|
|
||||||
config1, err := configService.GetConfiguration(helper.TestData.Server)
|
config1, err := configService.GetConfiguration(helper.TestData.Server)
|
||||||
tests.AssertNoError(t, err)
|
tests.AssertNoError(t, err)
|
||||||
@@ -264,7 +264,7 @@ func TestConfigService_Caching_Configuration(t *testing.T) {
|
|||||||
tests.AssertNotNil(t, config2)
|
tests.AssertNotNil(t, config2)
|
||||||
|
|
||||||
tests.AssertEqual(t, model.IntString(9231), config2.UdpPort)
|
tests.AssertEqual(t, model.IntString(9231), config2.UdpPort)
|
||||||
tests.AssertEqual(t, model.IntString(9231), config2.TcpPort)
|
tests.AssertEqual(t, model.IntString(9232), config2.TcpPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConfigService_Caching_EventConfig(t *testing.T) {
|
func TestConfigService_Caching_EventConfig(t *testing.T) {
|
||||||
@@ -276,7 +276,7 @@ func TestConfigService_Caching_EventConfig(t *testing.T) {
|
|||||||
|
|
||||||
configRepo := repository.NewConfigRepository(helper.DB)
|
configRepo := repository.NewConfigRepository(helper.DB)
|
||||||
serverRepo := repository.NewServerRepository(helper.DB)
|
serverRepo := repository.NewServerRepository(helper.DB)
|
||||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
configService := service.NewConfigService(configRepo, serverRepo)
|
||||||
|
|
||||||
event1, err := configService.GetEventConfig(helper.TestData.Server)
|
event1, err := configService.GetEventConfig(helper.TestData.Server)
|
||||||
tests.AssertNoError(t, err)
|
tests.AssertNoError(t, err)
|
||||||
|
|||||||
Reference in New Issue
Block a user