Compare commits

..

5 Commits

29 changed files with 70 additions and 798 deletions

View File

@@ -13,7 +13,7 @@ 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

View File

@@ -1,5 +1,6 @@
# ACC Server container: Wine + 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, Xvfb (headless display for Wine), and minimal runtime deps. # Install Wine, Xvfb (headless display for Wine), and minimal runtime deps.
@@ -11,17 +12,13 @@ RUN dpkg --add-architecture i386 && \
wine64 \ wine64 \
xvfb \ xvfb \
ca-certificates \ ca-certificates \
tcpdump \
&& \ && \
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*
RUN mkdir -p /tmp/.X11-unix && chmod 1777 /tmp/.X11-unix # 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
# Copy entrypoint script. # Copy entrypoint script.
COPY entrypoint.sh /entrypoint.sh COPY entrypoint.sh /entrypoint.sh
@@ -30,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"]

View File

@@ -1,78 +1,16 @@
#!/bin/bash #!/bin/bash
set -e set -e
DISPLAY_NUM=$((SERVER_PORT % 1000 + 100)) Xvfb :99 -screen 0 1024x768x16 &
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=$! XVFB_PID=$!
TCPDUMP_PID=""
cleanup() { cleanup() {
echo "Stopping ACC server..." echo "Stopping ACC server..."
[ -n "${TCPDUMP_PID}" ] && kill "${TCPDUMP_PID}" 2>/dev/null || true kill $XVFB_PID 2>/dev/null || true
kill "${XVFB_PID}" 2>/dev/null || true
} }
trap cleanup SIGTERM SIGINT EXIT trap cleanup SIGTERM SIGINT
# Initialize Wine prefix (no-op if already done) echo "Starting ACC server on port ${SERVER_PORT}..."
wineboot -u 2>/dev/null
mkdir -p /acc/game/log exec wine /acc/game/accServer.exe \
-port "${SERVER_PORT}"
# ─── 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

@@ -34,8 +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,
} }
accessKeyMiddleware := middleware.NewAccessKeyMiddleware() accessKeyMiddleware := middleware.NewAccessKeyMiddleware()

View File

@@ -1,72 +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(),
}
// 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)
}

View File

@@ -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

View File

@@ -69,9 +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")
}
} }

View File

@@ -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)
} }

View File

@@ -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())
} }

View File

@@ -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
}

View File

@@ -1,81 +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"
)
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"`
}

View File

@@ -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"`

View File

@@ -35,19 +35,18 @@ func (s *Server) ToServerAPI() *ServerAPI {
} }
type Server struct { type Server struct {
ID uuid.UUID `gorm:"type:uuid;primary_key;" json:"id"` ID uuid.UUID `gorm:"type:uuid;primary_key;" json:"id"`
Name string `gorm:"not null" json:"name"` Name string `gorm:"not null" json:"name"`
Status ServiceStatus `json:"status" gorm:"-"` Status ServiceStatus `json:"status" gorm:"-"`
IP string `gorm:"not null" json:"-"` IP string `gorm:"not null" json:"-"`
Port int `gorm:"not null" json:"-"` Port int `gorm:"not null" json:"-"`
Path string `gorm:"not null" json:"path"` Path string `gorm:"not null" json:"path"`
ServiceName string `gorm:"not null" json:"serviceName"` ServiceName string `gorm:"not null" json:"serviceName"`
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:"-"`
} }
type PlayerState struct { type PlayerState struct {

View File

@@ -1,75 +0,0 @@
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
}

View File

@@ -20,7 +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)
if err := c.Provide(func() *model.Steam2FAManager { if err := c.Provide(func() *model.Steam2FAManager {
manager := model.NewSteam2FAManager() manager := model.NewSteam2FAManager()

View File

@@ -1,62 +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)
}
}
keysJSON, _ := json.Marshal(changedKeys)
return fmt.Sprintf(`{"file":%q,"changed_keys":%s}`, file, string(keysJSON))
}

View File

@@ -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,93 +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
}
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) { 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) {
@@ -238,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)
@@ -257,21 +174,8 @@ func (as *ConfigService) updateConfigInternal(ctx context.Context, serverID stri
} }
as.configCache.InvalidateServerCache(serverID) as.configCache.InvalidateServerCache(serverID)
as.serverService.StartAccServerRuntime(server) 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{ return as.repository.UpdateConfig(ctx, &model.Config{
ServerID: serverUUID, ServerID: serverUUID,
ConfigFile: configFile, ConfigFile: configFile,
@@ -516,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)

View File

@@ -33,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()
@@ -73,8 +71,6 @@ func (r *DockerRuntime) Create(ctx context.Context, server *model.Server) error
Binds: binds, Binds: binds,
PortBindings: portBindings, PortBindings: portBindings,
RestartPolicy: container.RestartPolicy{Name: "unless-stopped"}, 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) }, 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)
@@ -106,19 +102,10 @@ 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, types.ContainerStartOptions{}); err != nil {
return "", fmt.Errorf("failed to start container: %v", err) return "", fmt.Errorf("failed to start container: %v", err)
} }
@@ -137,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 {

View File

@@ -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"
@@ -11,12 +10,11 @@ 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
} }

View File

@@ -26,13 +26,12 @@ 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
runtime platform.ServerRuntime runtime platform.ServerRuntime
firewall platform.FirewallManager firewall platform.FirewallManager
logStreamer platform.LogStreamer logStreamer platform.LogStreamer
portPool *network.PortPoolManager portPool *network.PortPoolManager
webSocketService *WebSocketService webSocketService *WebSocketService
instances sync.Map // uuid.UUID → *tracking.AccServerInstance instances sync.Map // uuid.UUID → *tracking.AccServerInstance
@@ -57,7 +56,6 @@ func (s *ServerService) ensureLogTailing(server *model.Server, instance *trackin
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,
@@ -70,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,
@@ -269,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)
@@ -295,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
@@ -592,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
} }

View File

@@ -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)

View File

@@ -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
} }

View File

@@ -28,8 +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
} }
func CheckError(err error) { func CheckError(err error) {

View File

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

View File

@@ -54,7 +54,6 @@ func Migrate(db *gorm.DB) {
&model.LeaderboardRace{}, &model.LeaderboardRace{},
&model.LeaderboardResult{}, &model.LeaderboardResult{},
&model.LeaderboardPointRow{}, &model.LeaderboardPointRow{},
&model.ActivityLog{},
) )
if err != nil { if err != nil {
@@ -81,10 +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)
}
logging.Info("Custom database migrations completed") logging.Info("Custom database migrations completed")
} }

View File

@@ -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),

View File

@@ -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)

View File

@@ -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),

View File

@@ -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)