Compare commits

..

9 Commits

Author SHA1 Message Date
85c5874bc7 update container port mapping 2026-03-22 13:23:35 +01:00
4441524447 fix acc server container restarting 2026-03-22 13:23:35 +01:00
c03234d339 update server app path to host's 2026-03-22 13:23:35 +01:00
d4b16d80f3 resolve server creation issues 2026-03-22 13:23:35 +01:00
9172f0256f add docker specifics 2026-03-22 13:23:35 +01:00
beb9b479df add platform interface according to env 2026-03-22 13:23:35 +01:00
4aa67db3fd add docker specific columns to server table 2026-03-22 13:23:35 +01:00
747adc77a5 version bump
Some checks failed
Release and Deploy / deploy (push) Has been skipped
Release and Deploy / build (push) Failing after 6m7s
2026-03-22 12:24:54 +01:00
c9a32e8889 feat: batch update config endpoint 2026-03-22 12:16:40 +01:00
13 changed files with 265 additions and 37 deletions

View File

@@ -13,7 +13,7 @@ services:
DB_NAME: /data/db/acc.db
STEAMCMD_LINUX_PATH: /usr/games/steamcmd
PORT_POOL_MIN: "9600"
PORT_POOL_MAX: "9700"
PORT_POOL_MAX: "9699"
ACC_IMAGE: acc-wine:latest
ACC_SERVERS_PATH: /data/servers
ACC_SERVERS_HOST_PATH: /opt/acc-servers

View File

@@ -1,6 +1,5 @@
# ACC Server container: Wine + accServer.exe
# 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.
# Game files are bind-mounted from the host at /acc/game.
FROM debian:bookworm-slim
# Install Wine, Xvfb (headless display for Wine), and minimal runtime deps.
@@ -12,13 +11,17 @@ RUN dpkg --add-architecture i386 && \
wine64 \
xvfb \
ca-certificates \
tcpdump \
&& \
rm -rf /var/lib/apt/lists/*
# Create a non-root user for running the server.
RUN useradd -ms /bin/bash accserver
RUN mkdir -p /tmp/.X11-unix && chmod 1777 /tmp/.X11-unix
WORKDIR /home/accserver
WORKDIR /root
ENV WINEARCH=win64
ENV WINEPREFIX=/root/.wine
ENV WINEDEBUG=-all
# Copy entrypoint script.
COPY entrypoint.sh /entrypoint.sh
@@ -27,13 +30,6 @@ RUN chmod +x /entrypoint.sh
# Bind-mounted by DockerRuntime.Create: per-server game install (rw)
VOLUME ["/acc/game"]
# Default server port — overridden at runtime via SERVER_PORT env var.
ENV SERVER_PORT=9600
ENV WINEDEBUG=-all
ENV DISPLAY=:99
EXPOSE ${SERVER_PORT}/tcp
EXPOSE ${SERVER_PORT}/udp
USER accserver
ENTRYPOINT ["/entrypoint.sh"]

View File

@@ -1,16 +1,78 @@
#!/bin/bash
set -e
Xvfb :99 -screen 0 1024x768x16 &
DISPLAY_NUM=$((SERVER_PORT % 1000 + 100))
export DISPLAY=:${DISPLAY_NUM}
rm -f /tmp/.X${DISPLAY_NUM}-lock /tmp/.X11-unix/X${DISPLAY_NUM} 2>/dev/null || true
Xvfb ${DISPLAY} -screen 0 1024x768x16 -nolisten tcp &
XVFB_PID=$!
TCPDUMP_PID=""
cleanup() {
echo "Stopping ACC server..."
kill $XVFB_PID 2>/dev/null || true
[ -n "${TCPDUMP_PID}" ] && kill "${TCPDUMP_PID}" 2>/dev/null || true
kill "${XVFB_PID}" 2>/dev/null || true
}
trap cleanup SIGTERM SIGINT
trap cleanup SIGTERM SIGINT EXIT
echo "Starting ACC server on port ${SERVER_PORT}..."
# Initialize Wine prefix (no-op if already done)
wineboot -u 2>/dev/null
exec wine /acc/game/accServer.exe \
-port "${SERVER_PORT}"
mkdir -p /acc/game/log
# ─── Debug mode ───────────────────────────────────────────────────────────────
# Set DEBUG_MODE=1 on the container to enable extra diagnostics:
#
# docker run -e DEBUG_MODE=1 ...
# or in docker-compose:
# environment:
# DEBUG_MODE: "1"
#
# Produces:
# /acc/game/log/tcpdump_<port>.pcap — raw packet capture (open in Wireshark)
# /acc/game/log/wine_debug.log — Wine debug output
# Stderr: Wine version, WINEDEBUG channel, prefix state
#
# You can also override which Wine debug channels are enabled:
# WINEDEBUG_CHANNELS="+loaddll,+seh,+relay" (relay is very verbose)
# ─────────────────────────────────────────────────────────────────────────────
if [ "${DEBUG_MODE:-0}" = "1" ]; then
echo "[debug] Debug mode enabled for port ${SERVER_PORT}"
echo "[debug] Wine: $(wine --version 2>/dev/null || echo unknown)"
echo "[debug] WINEPREFIX: ${WINEPREFIX}"
# Configure Wine debug channels (default: loader + exception + module info)
export WINEDEBUG="${WINEDEBUG_CHANNELS:-+loaddll,+module,+seh,+ntdll}"
echo "[debug] WINEDEBUG=${WINEDEBUG}"
# Start packet capture on the server port — captures both TCP and UDP.
# The pcap file records every byte Kunos sends/receives so you can inspect
# the 2-byte "pakSizeMax" packet and anything that follows.
#
# NOTE: requires CAP_NET_RAW capability on the container:
# docker-compose: cap_add: [NET_RAW]
# docker run: --cap-add=NET_RAW
# Without it tcpdump will be skipped (no crash, just no capture).
CAPTURE_FILE="/acc/game/log/tcpdump_${SERVER_PORT}.pcap"
echo "[debug] Starting packet capture → ${CAPTURE_FILE}"
echo "[debug] (requires cap_add: [NET_RAW] in docker-compose — will exit silently if missing)"
tcpdump -i any -nn -s 0 -w "${CAPTURE_FILE}" \
"port ${SERVER_PORT}" 2>/acc/game/log/tcpdump.err &
TCPDUMP_PID=$!
# Redirect Wine debug output to a log file (Wine writes to stderr).
WINE_LOG="/acc/game/log/wine_debug.log"
echo "[debug] Wine debug log → ${WINE_LOG}"
echo "Starting ACC server on port ${SERVER_PORT} (DEBUG)..."
cd /acc/game
exec wine /acc/game/accServer.exe 2>"${WINE_LOG}"
else
# Production: suppress all Wine debug output.
export WINEDEBUG=-all
echo "Starting ACC server on port ${SERVER_PORT}..."
cd /acc/game
exec wine /acc/game/accServer.exe
fi

View File

@@ -2,6 +2,7 @@ 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"
@@ -34,6 +35,7 @@ func NewConfigController(as *service.ConfigService, routeGroups *common.RouteGro
configGroup := routeGroups.Config
configGroup.Use(auth.Authenticate)
configGroup.Patch("/", ac.UpdateAllConfigs)
configGroup.Put("/:file", ac.UpdateConfig)
configGroup.Get("/:file", ac.GetConfig)
configGroup.Get("/", ac.GetConfigs)
@@ -41,6 +43,54 @@ func NewConfigController(as *service.ConfigService, routeGroups *common.RouteGro
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
//
// @Summary Update server configuration file

View File

@@ -40,6 +40,14 @@ type Configurations struct {
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 {
ServerName string `json:"serverName"`
AdminPassword string `json:"adminPassword"`

View File

@@ -91,6 +91,62 @@ func (as *ConfigService) SetServerService(serverService *ServerService) {
// context.Context: Application context
// Returns:
// 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},
}
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
}
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 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) {
serverID := ctx.Locals("serverId").(string)
configFile := ctx.Params("file")
@@ -420,6 +476,14 @@ func (as *ConfigService) GetConfiguration(server *model.Server) (*model.Configur
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 {
configMap := make(map[string]interface{})
configBytes, err := json.Marshal(config)

View File

@@ -33,23 +33,25 @@ func NewDockerRuntime(client *dockerclient.Client, repo *repository.ServerReposi
func (r *DockerRuntime) Create(ctx context.Context, server *model.Server) error {
image := env.GetACCImage()
// ACC uses the same port number for both TCP (client connections) and UDP (car positions/ping).
portStr := strconv.Itoa(server.Port)
natPort, err := nat.NewPort("tcp", portStr)
natTCP, err := nat.NewPort("tcp", portStr)
if err != nil {
return fmt.Errorf("invalid port %d: %v", server.Port, err)
}
natPortUDP, err := nat.NewPort("udp", portStr)
natUDP, err := nat.NewPort("udp", portStr)
if err != nil {
return fmt.Errorf("invalid udp port %d: %v", server.Port, err)
return fmt.Errorf("invalid port %d: %v", server.Port, err)
}
portBindings := nat.PortMap{
natPort: []nat.PortBinding{{HostPort: portStr}},
natPortUDP: []nat.PortBinding{{HostPort: portStr}},
natTCP: []nat.PortBinding{{HostPort: portStr}},
natUDP: []nat.PortBinding{{HostPort: portStr}},
}
exposedPorts := nat.PortSet{
natPort: struct{}{},
natPortUDP: struct{}{},
natTCP: struct{}{},
natUDP: struct{}{},
}
containerBase := env.GetACCServersPath()
@@ -71,6 +73,8 @@ func (r *DockerRuntime) Create(ctx context.Context, server *model.Server) error
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"},
}, nil, nil, server.ServiceName)
if err != nil {
return fmt.Errorf("failed to create container %s: %v", server.ServiceName, err)
@@ -102,10 +106,19 @@ func (r *DockerRuntime) Delete(ctx context.Context, serverID uuid.UUID) error {
}
func (r *DockerRuntime) Start(ctx context.Context, serverID uuid.UUID) (string, error) {
containerID, err := r.resolveContainerID(ctx, serverID)
server, err := r.repo.GetByID(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 {
return "", err
}
if err := r.client.ContainerStart(ctx, containerID, types.ContainerStartOptions{}); err != nil {
return "", fmt.Errorf("failed to start container: %v", err)
}
@@ -124,16 +137,44 @@ func (r *DockerRuntime) Stop(ctx context.Context, serverID uuid.UUID) (string, e
}
func (r *DockerRuntime) Restart(ctx context.Context, serverID uuid.UUID) (string, error) {
containerID, err := r.resolveContainerID(ctx, serverID)
server, err := r.repo.GetByID(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 {
return "", err
}
if err := r.client.ContainerRestart(ctx, containerID, container.StopOptions{}); err != nil {
return "", fmt.Errorf("failed to restart container: %v", err)
}
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) {
server, err := r.repo.GetByID(ctx, serverID)
if err != nil || server == nil {

View File

@@ -574,10 +574,17 @@ func (s *ServerService) updateServerPort(server *model.Server, port int) error {
config.TcpPort = model.IntString(port)
config.UdpPort = model.IntString(port)
config.RegisterToLobby = model.IntString(1)
if err := s.configService.SaveConfiguration(server, config); err != nil {
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
}

View File

@@ -8,7 +8,7 @@ import (
)
var (
Version = "0.10.7"
Version = "0.12.3"
Prefix = "v1"
Secret string
SecretCode string

View File

@@ -109,7 +109,7 @@ func createTestData(t *testing.T, tempDir string) *TestData {
configFiles := map[string]string{
"configuration.json": `{
"udpPort": "9231",
"tcpPort": "9232",
"tcpPort": "9231",
"maxConnections": "30",
"lanDiscovery": "1",
"registerToLobby": "1",
@@ -198,7 +198,7 @@ func createTestData(t *testing.T, tempDir string) *TestData {
sampleConfig := &model.Configuration{
UdpPort: model.IntString(9231),
TcpPort: model.IntString(9232),
TcpPort: model.IntString(9231),
MaxConnections: model.IntString(30),
LanDiscovery: model.IntString(1),
RegisterToLobby: model.IntString(1),

View File

@@ -294,7 +294,7 @@ func TestController_ConfigurationModel_JSONSerialization(t *testing.T) {
app.Get("/config", func(c *fiber.Ctx) error {
config := &model.Configuration{
UdpPort: model.IntString(9231),
TcpPort: model.IntString(9232),
TcpPort: model.IntString(9231),
MaxConnections: model.IntString(30),
LanDiscovery: model.IntString(1),
RegisterToLobby: model.IntString(1),
@@ -316,7 +316,7 @@ func TestController_ConfigurationModel_JSONSerialization(t *testing.T) {
tests.AssertNoError(t, err)
tests.AssertEqual(t, model.IntString(9231), response.UdpPort)
tests.AssertEqual(t, model.IntString(9232), response.TcpPort)
tests.AssertEqual(t, model.IntString(9231), response.TcpPort)
tests.AssertEqual(t, model.IntString(30), response.MaxConnections)
tests.AssertEqual(t, model.IntString(1), response.LanDiscovery)
tests.AssertEqual(t, model.IntString(1), response.RegisterToLobby)

View File

@@ -464,7 +464,7 @@ func TestServerConfigCache_Configuration(t *testing.T) {
serverID := uuid.New().String()
configuration := model.Configuration{
UdpPort: model.IntString(9231),
TcpPort: model.IntString(9232),
TcpPort: model.IntString(9231),
MaxConnections: model.IntString(30),
LanDiscovery: model.IntString(1),
RegisterToLobby: model.IntString(1),

View File

@@ -27,7 +27,7 @@ func TestConfigService_GetConfiguration_ValidFile(t *testing.T) {
tests.AssertNotNil(t, config)
tests.AssertEqual(t, model.IntString(9231), config.UdpPort)
tests.AssertEqual(t, model.IntString(9232), config.TcpPort)
tests.AssertEqual(t, model.IntString(9231), config.TcpPort)
tests.AssertEqual(t, model.IntString(30), config.MaxConnections)
tests.AssertEqual(t, model.IntString(1), config.LanDiscovery)
tests.AssertEqual(t, model.IntString(1), config.RegisterToLobby)
@@ -122,7 +122,7 @@ func TestConfigService_LoadConfigs_Success(t *testing.T) {
tests.AssertNotNil(t, configs)
tests.AssertEqual(t, model.IntString(9231), configs.Configuration.UdpPort)
tests.AssertEqual(t, model.IntString(9232), configs.Configuration.TcpPort)
tests.AssertEqual(t, model.IntString(9231), configs.Configuration.TcpPort)
tests.AssertEqual(t, "Test ACC Server", configs.Settings.ServerName)
tests.AssertEqual(t, "admin123", configs.Settings.AdminPassword)
tests.AssertEqual(t, "spa", configs.Event.Track)
@@ -264,7 +264,7 @@ func TestConfigService_Caching_Configuration(t *testing.T) {
tests.AssertNotNil(t, config2)
tests.AssertEqual(t, model.IntString(9231), config2.UdpPort)
tests.AssertEqual(t, model.IntString(9232), config2.TcpPort)
tests.AssertEqual(t, model.IntString(9231), config2.TcpPort)
}
func TestConfigService_Caching_EventConfig(t *testing.T) {