Compare commits
11 Commits
99d7e5fdc9
...
feature/ac
| Author | SHA1 | Date | |
|---|---|---|---|
| 14aa8a84e5 | |||
| e96b8bca12 | |||
| 85c5874bc7 | |||
| 4441524447 | |||
| c03234d339 | |||
| d4b16d80f3 | |||
| 9172f0256f | |||
| beb9b479df | |||
| 4aa67db3fd | |||
| 747adc77a5 | |||
| c9a32e8889 |
@@ -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
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -34,6 +34,8 @@ func Init(di *dig.Container, app *fiber.App) {
|
||||
WebSocket: groups.Group("/ws"),
|
||||
Leaderboard: serverIdGroup.Group("/leaderboard"),
|
||||
Steam: groups.Group("/steam"),
|
||||
ActivityLog: serverIdGroup.Group("/activity-log"),
|
||||
Groups: groups,
|
||||
}
|
||||
|
||||
accessKeyMiddleware := middleware.NewAccessKeyMiddleware()
|
||||
|
||||
72
local/controller/activity_log.go
Normal file
72
local/controller/activity_log.go
Normal file
@@ -0,0 +1,72 @@
|
||||
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(),
|
||||
}
|
||||
|
||||
// Per-server activity log: GET /server/:id/activity-log
|
||||
routeGroups.ActivityLog.Use(auth.Authenticate)
|
||||
routeGroups.ActivityLog.Get("/", ac.GetServerLogs)
|
||||
|
||||
// Global activity log: GET /activity-log (admin use)
|
||||
routeGroups.Groups.Group("/activity-log").Use(auth.Authenticate).Get("/", ac.GetAllLogs)
|
||||
|
||||
return ac
|
||||
}
|
||||
|
||||
// GetServerLogs returns activity logs for a specific server.
|
||||
//
|
||||
// @Summary Return activity logs for a server
|
||||
// @Tags ActivityLog
|
||||
// @Success 200 {array} model.ActivityLog
|
||||
// @Router /server/{id}/activity-log [get]
|
||||
func (ac *ActivityLogController) GetServerLogs(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)
|
||||
}
|
||||
|
||||
// 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,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
|
||||
|
||||
@@ -69,4 +69,9 @@ func InitializeControllers(c *dig.Container) {
|
||||
if err != nil {
|
||||
logging.Panic("unable to initialize steam controller")
|
||||
}
|
||||
|
||||
err = c.Invoke(NewActivityLogController)
|
||||
if err != nil {
|
||||
logging.Panic("unable to initialize activity log controller")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
|
||||
type LeaderboardController struct {
|
||||
service *service.LeaderboardService
|
||||
errorHandler *error_handler.ControllerErrorHandler
|
||||
@@ -60,7 +61,14 @@ func (lc *LeaderboardController) Update(c *fiber.Ctx) error {
|
||||
return lc.errorHandler.HandleParsingError(c, err)
|
||||
}
|
||||
|
||||
data, err := lc.service.Update(c.UserContext(), serverID, &input)
|
||||
userInfo, _ := c.Locals("userInfo").(*middleware.CachedUserInfo)
|
||||
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 {
|
||||
return lc.errorHandler.HandleServiceError(c, err)
|
||||
}
|
||||
|
||||
@@ -115,6 +115,7 @@ func (m *AuthMiddleware) AuthenticateWithHandler(jwtHandler *jwt.JWTHandler, isO
|
||||
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()}
|
||||
ctx.Locals("userID", userInfo.UserID)
|
||||
ctx.Locals("actorUsername", userInfo.Username)
|
||||
ctx.Locals("userInfo", userInfo)
|
||||
ctx.Locals("authTime", time.Now())
|
||||
} else {
|
||||
@@ -127,6 +128,7 @@ func (m *AuthMiddleware) AuthenticateWithHandler(jwtHandler *jwt.JWTHandler, isO
|
||||
}
|
||||
|
||||
ctx.Locals("userID", claims.UserID)
|
||||
ctx.Locals("actorUsername", userInfo.Username)
|
||||
ctx.Locals("userInfo", userInfo)
|
||||
ctx.Locals("authTime", time.Now())
|
||||
}
|
||||
|
||||
33
local/migrations/006_add_activity_log.go
Normal file
33
local/migrations/006_add_activity_log.go
Normal file
@@ -0,0 +1,33 @@
|
||||
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
|
||||
}
|
||||
81
local/model/activity_log.go
Normal file
81
local/model/activity_log.go
Normal file
@@ -0,0 +1,81 @@
|
||||
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"
|
||||
)
|
||||
|
||||
type ActivityLog struct {
|
||||
ID uuid.UUID `json:"id" gorm:"type:uuid;primary_key;"`
|
||||
ServerID uuid.UUID `json:"serverId" gorm:"not null;type:uuid;index"`
|
||||
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
|
||||
ServerBasedFilter
|
||||
DateRangeFilter
|
||||
UserID string `query:"user_id"`
|
||||
Action ActionType `query:"action"`
|
||||
}
|
||||
|
||||
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,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"`
|
||||
|
||||
@@ -35,18 +35,19 @@ func (s *Server) ToServerAPI() *ServerAPI {
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;" json:"id"`
|
||||
Name string `gorm:"not null" json:"name"`
|
||||
Status ServiceStatus `json:"status" gorm:"-"`
|
||||
IP string `gorm:"not null" json:"-"`
|
||||
Port int `gorm:"not null" json:"-"`
|
||||
Path string `gorm:"not null" json:"path"`
|
||||
ServiceName string `gorm:"not null" json:"serviceName"`
|
||||
Platform string `gorm:"not null;default:'windows'" json:"platform"`
|
||||
ContainerID string `gorm:"default:''" json:"-"`
|
||||
State *ServerState `gorm:"-" json:"state"`
|
||||
DateCreated time.Time `json:"dateCreated"`
|
||||
FromSteamCMD bool `gorm:"not null; default:true" json:"-"`
|
||||
ID uuid.UUID `gorm:"type:uuid;primary_key;" json:"id"`
|
||||
Name string `gorm:"not null" json:"name"`
|
||||
Status ServiceStatus `json:"status" gorm:"-"`
|
||||
IP string `gorm:"not null" json:"-"`
|
||||
Port int `gorm:"not null" json:"-"`
|
||||
Path string `gorm:"not null" json:"path"`
|
||||
ServiceName string `gorm:"not null" json:"serviceName"`
|
||||
Platform string `gorm:"not null;default:'windows'" json:"platform"`
|
||||
ContainerID string `gorm:"default:''" json:"-"`
|
||||
State *ServerState `gorm:"-" json:"state"`
|
||||
LastActivity *LastActivityInfo `gorm:"-" json:"lastActivity,omitempty"`
|
||||
DateCreated time.Time `json:"dateCreated"`
|
||||
FromSteamCMD bool `gorm:"not null; default:true" json:"-"`
|
||||
}
|
||||
|
||||
type PlayerState struct {
|
||||
|
||||
75
local/repository/activity_log.go
Normal file
75
local/repository/activity_log.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"acc-server-manager/local/model"
|
||||
"context"
|
||||
"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) {
|
||||
return r.BaseRepository.GetAll(ctx, filter)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -20,6 +20,7 @@ func InitializeRepositories(c *dig.Container) {
|
||||
c.Provide(NewSteamCredentialsRepository)
|
||||
c.Provide(NewMembershipRepository)
|
||||
c.Provide(NewLeaderboardRepository)
|
||||
c.Provide(NewActivityLogRepository)
|
||||
|
||||
if err := c.Provide(func() *model.Steam2FAManager {
|
||||
manager := model.NewSteam2FAManager()
|
||||
|
||||
62
local/service/activity_log.go
Normal file
62
local/service/activity_log.go
Normal file
@@ -0,0 +1,62 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
keysJSON, _ := json.Marshal(changedKeys)
|
||||
return fmt.Sprintf(`{"file":%q,"changed_keys":%s}`, file, string(keysJSON))
|
||||
}
|
||||
@@ -68,14 +68,16 @@ type ConfigService struct {
|
||||
repository *repository.ConfigRepository
|
||||
serverRepository *repository.ServerRepository
|
||||
serverService *ServerService
|
||||
activityLog *ActivityLogService
|
||||
configCache *model.ServerConfigCache
|
||||
}
|
||||
|
||||
func NewConfigService(repository *repository.ConfigRepository, serverRepository *repository.ServerRepository) *ConfigService {
|
||||
func NewConfigService(repository *repository.ConfigRepository, serverRepository *repository.ServerRepository, activityLog *ActivityLogService) *ConfigService {
|
||||
logging.Debug("Initializing ConfigService with 5m expiration and 1s throttle")
|
||||
return &ConfigService{
|
||||
repository: repository,
|
||||
serverRepository: serverRepository,
|
||||
activityLog: activityLog,
|
||||
configCache: model.NewServerConfigCache(model.CacheConfig{
|
||||
ExpirationTime: 5 * time.Minute,
|
||||
ThrottleTime: 1 * time.Second,
|
||||
@@ -91,12 +93,93 @@ 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},
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
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 {
|
||||
details := BuildConfigDetails(entry.fileName, oldDataUTF8, newData)
|
||||
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) {
|
||||
serverID := ctx.Locals("serverId").(string)
|
||||
configFile := ctx.Params("file")
|
||||
override := ctx.QueryBool("override", false)
|
||||
|
||||
return as.updateConfigInternal(ctx.UserContext(), serverID, configFile, body, override)
|
||||
actorID, _ := ctx.Locals("userID").(string)
|
||||
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) {
|
||||
@@ -155,7 +238,7 @@ func (as *ConfigService) updateConfigFiles(ctx context.Context, server *model.Se
|
||||
return oldDataUTF8, newData, nil
|
||||
}
|
||||
|
||||
func (as *ConfigService) updateConfigInternal(ctx context.Context, serverID string, configFile string, body *map[string]interface{}, override bool) (*model.Config, error) {
|
||||
func (as *ConfigService) updateConfigInternal(ctx context.Context, serverID string, configFile string, body *map[string]interface{}, override bool, actorID, actorUsername string) (*model.Config, error) {
|
||||
serverUUID, err := uuid.Parse(serverID)
|
||||
if err != nil {
|
||||
logging.Error("Invalid server ID format: %v", err)
|
||||
@@ -174,8 +257,21 @@ func (as *ConfigService) updateConfigInternal(ctx context.Context, serverID stri
|
||||
}
|
||||
|
||||
as.configCache.InvalidateServerCache(serverID)
|
||||
|
||||
as.serverService.StartAccServerRuntime(server)
|
||||
|
||||
if as.activityLog != nil {
|
||||
details := BuildConfigDetails(configFile, oldDataUTF8, newData)
|
||||
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{
|
||||
ServerID: serverUUID,
|
||||
ConfigFile: configFile,
|
||||
@@ -420,6 +516,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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"acc-server-manager/local/model"
|
||||
"acc-server-manager/local/repository"
|
||||
"acc-server-manager/local/utl/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
@@ -10,11 +11,12 @@ import (
|
||||
)
|
||||
|
||||
type LeaderboardService struct {
|
||||
repo *repository.LeaderboardRepository
|
||||
repo *repository.LeaderboardRepository
|
||||
activityLog *ActivityLogService
|
||||
}
|
||||
|
||||
func NewLeaderboardService(repo *repository.LeaderboardRepository) *LeaderboardService {
|
||||
return &LeaderboardService{repo: repo}
|
||||
func NewLeaderboardService(repo *repository.LeaderboardRepository, activityLog *ActivityLogService) *LeaderboardService {
|
||||
return &LeaderboardService{repo: repo, activityLog: activityLog}
|
||||
}
|
||||
|
||||
// Get returns the leaderboard for a server.
|
||||
@@ -23,7 +25,7 @@ func (s *LeaderboardService) Get(ctx context.Context, serverID uuid.UUID) (*mode
|
||||
}
|
||||
|
||||
// Update replaces the leaderboard for a server.
|
||||
func (s *LeaderboardService) Update(ctx context.Context, serverID uuid.UUID, lb *model.Leaderboard) (*model.Leaderboard, error) {
|
||||
func (s *LeaderboardService) Update(ctx context.Context, serverID uuid.UUID, lb *model.Leaderboard, actorID, actorUsername string) (*model.Leaderboard, error) {
|
||||
if lb == nil {
|
||||
return nil, fmt.Errorf("input is required")
|
||||
}
|
||||
@@ -33,5 +35,25 @@ func (s *LeaderboardService) Update(ctx context.Context, serverID uuid.UUID, lb
|
||||
for i := range lb.Races {
|
||||
lb.Races[i].Position = i
|
||||
}
|
||||
return s.repo.FullReplace(ctx, serverID, lb)
|
||||
result, err := 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,12 +26,13 @@ const (
|
||||
type ServerService struct {
|
||||
repository *repository.ServerRepository
|
||||
stateHistoryRepo *repository.StateHistoryRepository
|
||||
activityLogRepo *repository.ActivityLogRepository
|
||||
apiService *ServiceControlService
|
||||
configService *ConfigService
|
||||
steamService *SteamService
|
||||
runtime platform.ServerRuntime
|
||||
firewall platform.FirewallManager
|
||||
logStreamer platform.LogStreamer
|
||||
logStreamer platform.LogStreamer
|
||||
portPool *network.PortPoolManager
|
||||
webSocketService *WebSocketService
|
||||
instances sync.Map // uuid.UUID → *tracking.AccServerInstance
|
||||
@@ -56,6 +57,7 @@ func (s *ServerService) ensureLogTailing(server *model.Server, instance *trackin
|
||||
func NewServerService(
|
||||
repository *repository.ServerRepository,
|
||||
stateHistoryRepo *repository.StateHistoryRepository,
|
||||
activityLogRepo *repository.ActivityLogRepository,
|
||||
apiService *ServiceControlService,
|
||||
configService *ConfigService,
|
||||
steamService *SteamService,
|
||||
@@ -68,6 +70,7 @@ func NewServerService(
|
||||
service := &ServerService{
|
||||
repository: repository,
|
||||
stateHistoryRepo: stateHistoryRepo,
|
||||
activityLogRepo: activityLogRepo,
|
||||
apiService: apiService,
|
||||
configService: configService,
|
||||
steamService: steamService,
|
||||
@@ -266,6 +269,16 @@ func (s *ServerService) GetAll(ctx *fiber.Ctx, filter *model.ServerFilter) (*[]m
|
||||
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 {
|
||||
server := &(*servers)[i]
|
||||
status, err := s.apiService.GetCachedStatus(server.ServiceName)
|
||||
@@ -282,6 +295,11 @@ func (s *ServerService) GetAll(ctx *fiber.Ctx, filter *model.ServerFilter) (*[]m
|
||||
server.State = serverInstance.State
|
||||
}
|
||||
}
|
||||
if lastActivities != nil {
|
||||
if info, ok := lastActivities[server.ID]; ok {
|
||||
server.LastActivity = info
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return servers, nil
|
||||
@@ -574,10 +592,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
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ func InitializeServices(c *dig.Container) {
|
||||
|
||||
logging.Debug("Registering services")
|
||||
c.Provide(NewSteamService)
|
||||
c.Provide(NewActivityLogService)
|
||||
c.Provide(NewServerService)
|
||||
c.Provide(NewStateHistoryService)
|
||||
c.Provide(NewServiceControlService)
|
||||
|
||||
@@ -15,6 +15,7 @@ type ServiceControlService struct {
|
||||
repository *repository.ServiceControlRepository
|
||||
serverRepository *repository.ServerRepository
|
||||
serverService *ServerService
|
||||
activityLog *ActivityLogService
|
||||
statusCache *model.ServerStatusCache
|
||||
runtime platform.ServerRuntime
|
||||
}
|
||||
@@ -23,11 +24,13 @@ func NewServiceControlService(
|
||||
repository *repository.ServiceControlRepository,
|
||||
serverRepository *repository.ServerRepository,
|
||||
runtime platform.ServerRuntime,
|
||||
activityLog *ActivityLogService,
|
||||
) *ServiceControlService {
|
||||
return &ServiceControlService{
|
||||
repository: repository,
|
||||
serverRepository: serverRepository,
|
||||
runtime: runtime,
|
||||
activityLog: activityLog,
|
||||
statusCache: model.NewServerStatusCache(model.CacheConfig{
|
||||
ExpirationTime: 30 * time.Second,
|
||||
ThrottleTime: 5 * time.Second,
|
||||
@@ -36,6 +39,28 @@ 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) {
|
||||
as.serverService = serverService
|
||||
}
|
||||
@@ -61,10 +86,11 @@ func (as *ServiceControlService) GetStatus(ctx *fiber.Ctx) (string, error) {
|
||||
}
|
||||
|
||||
func (as *ServiceControlService) ServiceControlStartServer(ctx *fiber.Ctx) (string, error) {
|
||||
serviceName, err := as.GetServiceName(ctx)
|
||||
server, err := as.getServerFromCtx(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
serviceName := server.ServiceName
|
||||
|
||||
as.statusCache.UpdateStatus(serviceName, model.StatusStarting)
|
||||
|
||||
@@ -79,14 +105,29 @@ func (as *ServiceControlService) ServiceControlStartServer(ctx *fiber.Ctx) (stri
|
||||
|
||||
status := model.ParseServiceStatus(statusStr)
|
||||
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
|
||||
}
|
||||
|
||||
func (as *ServiceControlService) ServiceControlStopServer(ctx *fiber.Ctx) (string, error) {
|
||||
serviceName, err := as.GetServiceName(ctx)
|
||||
server, err := as.getServerFromCtx(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
serviceName := server.ServiceName
|
||||
|
||||
as.statusCache.UpdateStatus(serviceName, model.StatusStopping)
|
||||
|
||||
@@ -101,14 +142,29 @@ func (as *ServiceControlService) ServiceControlStopServer(ctx *fiber.Ctx) (strin
|
||||
|
||||
status := model.ParseServiceStatus(statusStr)
|
||||
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
|
||||
}
|
||||
|
||||
func (as *ServiceControlService) ServiceControlRestartServer(ctx *fiber.Ctx) (string, error) {
|
||||
serviceName, err := as.GetServiceName(ctx)
|
||||
server, err := as.getServerFromCtx(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
serviceName := server.ServiceName
|
||||
|
||||
as.statusCache.UpdateStatus(serviceName, model.StatusRestarting)
|
||||
|
||||
@@ -123,6 +179,20 @@ func (as *ServiceControlService) ServiceControlRestartServer(ctx *fiber.Ctx) (st
|
||||
|
||||
status := model.ParseServiceStatus(statusStr)
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,8 @@ type RouteGroups struct {
|
||||
WebSocket fiber.Router
|
||||
Leaderboard fiber.Router
|
||||
Steam fiber.Router
|
||||
ActivityLog fiber.Router
|
||||
Groups fiber.Router
|
||||
}
|
||||
|
||||
func CheckError(err error) {
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
Version = "0.10.7"
|
||||
Version = "0.12.3"
|
||||
Prefix = "v1"
|
||||
Secret string
|
||||
SecretCode string
|
||||
|
||||
@@ -54,6 +54,7 @@ func Migrate(db *gorm.DB) {
|
||||
&model.LeaderboardRace{},
|
||||
&model.LeaderboardResult{},
|
||||
&model.LeaderboardPointRow{},
|
||||
&model.ActivityLog{},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
@@ -80,6 +81,10 @@ func runMigrations(db *gorm.DB) {
|
||||
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)
|
||||
}
|
||||
|
||||
logging.Info("Custom database migrations completed")
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -20,14 +20,14 @@ func TestConfigService_GetConfiguration_ValidFile(t *testing.T) {
|
||||
|
||||
configRepo := repository.NewConfigRepository(helper.DB)
|
||||
serverRepo := repository.NewServerRepository(helper.DB)
|
||||
configService := service.NewConfigService(configRepo, serverRepo)
|
||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
||||
|
||||
config, err := configService.GetConfiguration(helper.TestData.Server)
|
||||
tests.AssertNoError(t, err)
|
||||
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)
|
||||
@@ -43,7 +43,7 @@ func TestConfigService_GetEventConfig_ValidFile(t *testing.T) {
|
||||
|
||||
configRepo := repository.NewConfigRepository(helper.DB)
|
||||
serverRepo := repository.NewServerRepository(helper.DB)
|
||||
configService := service.NewConfigService(configRepo, serverRepo)
|
||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
||||
|
||||
eventConfig, err := configService.GetEventConfig(helper.TestData.Server)
|
||||
tests.AssertNoError(t, err)
|
||||
@@ -73,7 +73,7 @@ func TestConfigService_SaveConfiguration_Success(t *testing.T) {
|
||||
|
||||
configRepo := repository.NewConfigRepository(helper.DB)
|
||||
serverRepo := repository.NewServerRepository(helper.DB)
|
||||
configService := service.NewConfigService(configRepo, serverRepo)
|
||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
||||
|
||||
newConfig := &model.Configuration{
|
||||
UdpPort: model.IntString(9999),
|
||||
@@ -115,14 +115,14 @@ func TestConfigService_LoadConfigs_Success(t *testing.T) {
|
||||
|
||||
configRepo := repository.NewConfigRepository(helper.DB)
|
||||
serverRepo := repository.NewServerRepository(helper.DB)
|
||||
configService := service.NewConfigService(configRepo, serverRepo)
|
||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
||||
|
||||
configs, err := configService.LoadConfigs(helper.TestData.Server)
|
||||
tests.AssertNoError(t, err)
|
||||
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)
|
||||
@@ -142,7 +142,7 @@ func TestConfigService_MalformedJSON(t *testing.T) {
|
||||
|
||||
configRepo := repository.NewConfigRepository(helper.DB)
|
||||
serverRepo := repository.NewServerRepository(helper.DB)
|
||||
configService := service.NewConfigService(configRepo, serverRepo)
|
||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
||||
|
||||
config, err := configService.GetConfiguration(helper.TestData.Server)
|
||||
if err == nil {
|
||||
@@ -245,7 +245,7 @@ func TestConfigService_Caching_Configuration(t *testing.T) {
|
||||
|
||||
configRepo := repository.NewConfigRepository(helper.DB)
|
||||
serverRepo := repository.NewServerRepository(helper.DB)
|
||||
configService := service.NewConfigService(configRepo, serverRepo)
|
||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
||||
|
||||
config1, err := configService.GetConfiguration(helper.TestData.Server)
|
||||
tests.AssertNoError(t, err)
|
||||
@@ -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) {
|
||||
@@ -276,7 +276,7 @@ func TestConfigService_Caching_EventConfig(t *testing.T) {
|
||||
|
||||
configRepo := repository.NewConfigRepository(helper.DB)
|
||||
serverRepo := repository.NewServerRepository(helper.DB)
|
||||
configService := service.NewConfigService(configRepo, serverRepo)
|
||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
||||
|
||||
event1, err := configService.GetEventConfig(helper.TestData.Server)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
Reference in New Issue
Block a user