Compare commits
2 Commits
feature/ac
...
feature/se
| Author | SHA1 | Date | |
|---|---|---|---|
| a6f67dd652 | |||
| e637b5e649 |
@@ -34,8 +34,7 @@ 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"),
|
Log: serverIdGroup.Group("/log"),
|
||||||
Groups: groups,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
accessKeyMiddleware := middleware.NewAccessKeyMiddleware()
|
accessKeyMiddleware := middleware.NewAccessKeyMiddleware()
|
||||||
|
|||||||
@@ -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)
|
|
||||||
}
|
|
||||||
@@ -70,8 +70,8 @@ func InitializeControllers(c *dig.Container) {
|
|||||||
logging.Panic("unable to initialize steam controller")
|
logging.Panic("unable to initialize steam controller")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = c.Invoke(NewActivityLogController)
|
err = c.Invoke(NewLogController)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Panic("unable to initialize activity log controller")
|
logging.Panic("unable to initialize log controller")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
type LeaderboardController struct {
|
type LeaderboardController struct {
|
||||||
service *service.LeaderboardService
|
service *service.LeaderboardService
|
||||||
errorHandler *error_handler.ControllerErrorHandler
|
errorHandler *error_handler.ControllerErrorHandler
|
||||||
@@ -61,14 +60,7 @@ func (lc *LeaderboardController) Update(c *fiber.Ctx) error {
|
|||||||
return lc.errorHandler.HandleParsingError(c, err)
|
return lc.errorHandler.HandleParsingError(c, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
userInfo, _ := c.Locals("userInfo").(*middleware.CachedUserInfo)
|
data, err := lc.service.Update(c.UserContext(), serverID, &input)
|
||||||
actorID, actorUsername := "", "system"
|
|
||||||
if userInfo != nil {
|
|
||||||
actorID = userInfo.UserID
|
|
||||||
actorUsername = userInfo.Username
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := lc.service.Update(c.UserContext(), serverID, &input, actorID, actorUsername)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return lc.errorHandler.HandleServiceError(c, err)
|
return lc.errorHandler.HandleServiceError(c, err)
|
||||||
}
|
}
|
||||||
|
|||||||
62
local/controller/log.go
Normal file
62
local/controller/log.go
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"acc-server-manager/local/middleware"
|
||||||
|
"acc-server-manager/local/model"
|
||||||
|
"acc-server-manager/local/service"
|
||||||
|
"acc-server-manager/local/utl/common"
|
||||||
|
"acc-server-manager/local/utl/error_handler"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LogController struct {
|
||||||
|
service *service.ServerService
|
||||||
|
errorHandler *error_handler.ControllerErrorHandler
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLogController(ss *service.ServerService, routeGroups *common.RouteGroups, auth *middleware.AuthMiddleware) *LogController {
|
||||||
|
lc := &LogController{
|
||||||
|
service: ss,
|
||||||
|
errorHandler: error_handler.NewControllerErrorHandler(),
|
||||||
|
}
|
||||||
|
|
||||||
|
logRoutes := routeGroups.Log
|
||||||
|
logRoutes.Use(auth.Authenticate)
|
||||||
|
logRoutes.Get("/", auth.HasPermission(model.ServerView), lc.GetLogLines)
|
||||||
|
|
||||||
|
return lc
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLogLines godoc
|
||||||
|
// @Summary Get last N lines of server log
|
||||||
|
// @Tags Server
|
||||||
|
// @Param id path string true "Server ID"
|
||||||
|
// @Param lines query int false "Number of lines to return (default 100)"
|
||||||
|
// @Success 200 {object} object{lines=[]string}
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Router /server/{id}/log [get]
|
||||||
|
func (lc *LogController) GetLogLines(c *fiber.Ctx) error {
|
||||||
|
serverIDStr := c.Params("id")
|
||||||
|
serverID, err := uuid.Parse(serverIDStr)
|
||||||
|
if err != nil {
|
||||||
|
return lc.errorHandler.HandleUUIDError(c, "server ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
n, _ := strconv.Atoi(c.Query("lines", "100"))
|
||||||
|
if n <= 0 {
|
||||||
|
n = 100
|
||||||
|
}
|
||||||
|
if n > 10000 {
|
||||||
|
n = 10000
|
||||||
|
}
|
||||||
|
|
||||||
|
lines, err := lc.service.GetLastLogLines(c, serverID, n)
|
||||||
|
if err != nil {
|
||||||
|
return lc.errorHandler.HandleServiceError(c, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.JSON(fiber.Map{"lines": lines})
|
||||||
|
}
|
||||||
@@ -115,7 +115,6 @@ func (m *AuthMiddleware) AuthenticateWithHandler(jwtHandler *jwt.JWTHandler, isO
|
|||||||
if os.Getenv("TESTING_ENV") == "true" {
|
if os.Getenv("TESTING_ENV") == "true" {
|
||||||
userInfo := CachedUserInfo{UserID: uuid.New().String(), Username: "test@example.com", RoleName: "Admin", Permissions: make(map[string]bool), CachedAt: time.Now()}
|
userInfo := CachedUserInfo{UserID: uuid.New().String(), Username: "test@example.com", RoleName: "Admin", Permissions: make(map[string]bool), CachedAt: time.Now()}
|
||||||
ctx.Locals("userID", userInfo.UserID)
|
ctx.Locals("userID", userInfo.UserID)
|
||||||
ctx.Locals("actorUsername", userInfo.Username)
|
|
||||||
ctx.Locals("userInfo", userInfo)
|
ctx.Locals("userInfo", userInfo)
|
||||||
ctx.Locals("authTime", time.Now())
|
ctx.Locals("authTime", time.Now())
|
||||||
} else {
|
} else {
|
||||||
@@ -128,7 +127,6 @@ func (m *AuthMiddleware) AuthenticateWithHandler(jwtHandler *jwt.JWTHandler, isO
|
|||||||
}
|
}
|
||||||
|
|
||||||
ctx.Locals("userID", claims.UserID)
|
ctx.Locals("userID", claims.UserID)
|
||||||
ctx.Locals("actorUsername", userInfo.Username)
|
|
||||||
ctx.Locals("userInfo", userInfo)
|
ctx.Locals("userInfo", userInfo)
|
||||||
ctx.Locals("authTime", time.Now())
|
ctx.Locals("authTime", time.Now())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
package migrations
|
|
||||||
|
|
||||||
import (
|
|
||||||
"acc-server-manager/local/utl/logging"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
func RunAddActivityLogMigration(db *gorm.DB) error {
|
|
||||||
if err := db.AutoMigrate(&MigrationRecord{}); err != nil {
|
|
||||||
return fmt.Errorf("failed to ensure migration_records table: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var record MigrationRecord
|
|
||||||
if err := db.Where("migration_name = ?", "006_add_activity_log").First(&record).Error; err == nil {
|
|
||||||
logging.Info("Activity log migration already applied, skipping")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
record = MigrationRecord{
|
|
||||||
MigrationName: "006_add_activity_log",
|
|
||||||
AppliedAt: "datetime('now')",
|
|
||||||
Success: true,
|
|
||||||
Notes: "Added ActivityLog table via GORM AutoMigrate",
|
|
||||||
}
|
|
||||||
if err := db.Create(&record).Error; err != nil {
|
|
||||||
return fmt.Errorf("failed to record migration 006: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
logging.Info("Activity log migration recorded")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,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"`
|
|
||||||
}
|
|
||||||
@@ -45,7 +45,6 @@ type Server struct {
|
|||||||
Platform string `gorm:"not null;default:'windows'" json:"platform"`
|
Platform string `gorm:"not null;default:'windows'" json:"platform"`
|
||||||
ContainerID string `gorm:"default:''" json:"-"`
|
ContainerID string `gorm:"default:''" json:"-"`
|
||||||
State *ServerState `gorm:"-" json:"state"`
|
State *ServerState `gorm:"-" json:"state"`
|
||||||
LastActivity *LastActivityInfo `gorm:"-" json:"lastActivity,omitempty"`
|
|
||||||
DateCreated time.Time `json:"dateCreated"`
|
DateCreated time.Time `json:"dateCreated"`
|
||||||
FromSteamCMD bool `gorm:"not null; default:true" json:"-"`
|
FromSteamCMD bool `gorm:"not null; default:true" json:"-"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ const (
|
|||||||
MessageTypeSteamOutput WebSocketMessageType = "steam_output"
|
MessageTypeSteamOutput WebSocketMessageType = "steam_output"
|
||||||
MessageTypeError WebSocketMessageType = "error"
|
MessageTypeError WebSocketMessageType = "error"
|
||||||
MessageTypeComplete WebSocketMessageType = "complete"
|
MessageTypeComplete WebSocketMessageType = "complete"
|
||||||
|
MessageTypeLogLine WebSocketMessageType = "log_line"
|
||||||
)
|
)
|
||||||
|
|
||||||
type WebSocketMessage struct {
|
type WebSocketMessage struct {
|
||||||
@@ -65,6 +66,10 @@ type CompleteMessage struct {
|
|||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type LogLineMessage struct {
|
||||||
|
Line string `json:"line"`
|
||||||
|
}
|
||||||
|
|
||||||
func GetStepDescription(step ServerCreationStep) string {
|
func GetStepDescription(step ServerCreationStep) string {
|
||||||
descriptions := map[ServerCreationStep]string{
|
descriptions := map[ServerCreationStep]string{
|
||||||
StepValidation: "Validating server configuration",
|
StepValidation: "Validating server configuration",
|
||||||
|
|||||||
@@ -25,4 +25,5 @@ type FirewallManager interface {
|
|||||||
type LogStreamer interface {
|
type LogStreamer interface {
|
||||||
Start(ctx context.Context, server *model.Server, handleLine func(string)) error
|
Start(ctx context.Context, server *model.Server, handleLine func(string)) error
|
||||||
Stop(serverID uuid.UUID)
|
Stop(serverID uuid.UUID)
|
||||||
|
GetLastLines(ctx context.Context, server *model.Server, n int) ([]string, error)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,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
|
|
||||||
}
|
|
||||||
@@ -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()
|
||||||
|
|||||||
@@ -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))
|
|
||||||
}
|
|
||||||
@@ -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,
|
||||||
@@ -122,12 +120,6 @@ func (as *ConfigService) UpdateAllConfigs(ctx *fiber.Ctx, req *model.Configurati
|
|||||||
{SettingsJson, req.Settings},
|
{SettingsJson, req.Settings},
|
||||||
}
|
}
|
||||||
|
|
||||||
actorID, _ := ctx.Locals("userID").(string)
|
|
||||||
actorUsername, _ := ctx.Locals("actorUsername").(string)
|
|
||||||
if actorUsername == "" {
|
|
||||||
actorUsername = "system"
|
|
||||||
}
|
|
||||||
|
|
||||||
var results []*model.Config
|
var results []*model.Config
|
||||||
for _, entry := range entries {
|
for _, entry := range entries {
|
||||||
if entry.body == nil {
|
if entry.body == nil {
|
||||||
@@ -145,19 +137,6 @@ func (as *ConfigService) UpdateAllConfigs(ctx *fiber.Ctx, req *model.Configurati
|
|||||||
ChangedAt: time.Now(),
|
ChangedAt: time.Now(),
|
||||||
})
|
})
|
||||||
results = append(results, result)
|
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 {
|
if len(results) > 0 {
|
||||||
@@ -173,13 +152,7 @@ func (as *ConfigService) UpdateConfig(ctx *fiber.Ctx, body *map[string]interface
|
|||||||
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 +211,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 +230,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,
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"context"
|
"context"
|
||||||
"io"
|
"io"
|
||||||
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/docker/docker/api/types"
|
"github.com/docker/docker/api/types"
|
||||||
@@ -72,3 +73,34 @@ func (s *DockerLogStreamer) Stop(serverID uuid.UUID) {
|
|||||||
v.(context.CancelFunc)()
|
v.(context.CancelFunc)()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *DockerLogStreamer) GetLastLines(ctx context.Context, server *model.Server, n int) ([]string, error) {
|
||||||
|
if n <= 0 || server.ContainerID == "" {
|
||||||
|
return []string{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
rc, err := s.client.ContainerLogs(ctx, server.ContainerID, types.ContainerLogsOptions{
|
||||||
|
ShowStdout: true,
|
||||||
|
ShowStderr: true,
|
||||||
|
Tail: strconv.Itoa(n),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rc.Close()
|
||||||
|
|
||||||
|
pr, pw := io.Pipe()
|
||||||
|
go func() {
|
||||||
|
defer pw.Close()
|
||||||
|
if _, err := stdcopy.StdCopy(pw, pw, rc); err != nil && err != io.EOF {
|
||||||
|
logging.Warn("DockerLogStreamer.GetLastLines: stdcopy error for %s: %v", server.ServiceName, err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
var lines []string
|
||||||
|
scanner := bufio.NewScanner(pr)
|
||||||
|
for scanner.Scan() {
|
||||||
|
lines = append(lines, scanner.Text())
|
||||||
|
}
|
||||||
|
return lines, scanner.Err()
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ package service
|
|||||||
import (
|
import (
|
||||||
"acc-server-manager/local/model"
|
"acc-server-manager/local/model"
|
||||||
"acc-server-manager/local/utl/tracking"
|
"acc-server-manager/local/utl/tracking"
|
||||||
|
"bufio"
|
||||||
"context"
|
"context"
|
||||||
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
@@ -36,3 +38,40 @@ func (s *FileLogStreamer) Stop(serverID uuid.UUID) {
|
|||||||
v.(*tracking.LogTailer).Stop()
|
v.(*tracking.LogTailer).Stop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *FileLogStreamer) GetLastLines(_ context.Context, server *model.Server, n int) ([]string, error) {
|
||||||
|
if n <= 0 {
|
||||||
|
return []string{}, nil
|
||||||
|
}
|
||||||
|
logPath := filepath.Join(server.GetLogPath(), "server.log")
|
||||||
|
f, err := os.Open(logPath)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return []string{}, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
ring := make([]string, n)
|
||||||
|
head := 0
|
||||||
|
count := 0
|
||||||
|
scanner := bufio.NewScanner(f)
|
||||||
|
for scanner.Scan() {
|
||||||
|
ring[head] = scanner.Text()
|
||||||
|
head = (head + 1) % n
|
||||||
|
if count < n {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := scanner.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if count < n {
|
||||||
|
return ring[:count], nil
|
||||||
|
}
|
||||||
|
out := make([]string, n)
|
||||||
|
copy(out, ring[head:])
|
||||||
|
copy(out[n-head:], ring[:head])
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package service
|
|||||||
import (
|
import (
|
||||||
"acc-server-manager/local/model"
|
"acc-server-manager/local/model"
|
||||||
"acc-server-manager/local/repository"
|
"acc-server-manager/local/repository"
|
||||||
"acc-server-manager/local/utl/logging"
|
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
@@ -12,11 +11,10 @@ import (
|
|||||||
|
|
||||||
type LeaderboardService struct {
|
type LeaderboardService struct {
|
||||||
repo *repository.LeaderboardRepository
|
repo *repository.LeaderboardRepository
|
||||||
activityLog *ActivityLogService
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewLeaderboardService(repo *repository.LeaderboardRepository, activityLog *ActivityLogService) *LeaderboardService {
|
func NewLeaderboardService(repo *repository.LeaderboardRepository) *LeaderboardService {
|
||||||
return &LeaderboardService{repo: repo, activityLog: activityLog}
|
return &LeaderboardService{repo: repo}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns the leaderboard for a server.
|
// Get returns the leaderboard for a server.
|
||||||
@@ -25,7 +23,7 @@ func (s *LeaderboardService) Get(ctx context.Context, serverID uuid.UUID) (*mode
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update replaces the leaderboard for a server.
|
// Update replaces the leaderboard for a server.
|
||||||
func (s *LeaderboardService) Update(ctx context.Context, serverID uuid.UUID, lb *model.Leaderboard, actorID, actorUsername string) (*model.Leaderboard, error) {
|
func (s *LeaderboardService) Update(ctx context.Context, serverID uuid.UUID, lb *model.Leaderboard) (*model.Leaderboard, error) {
|
||||||
if lb == nil {
|
if lb == nil {
|
||||||
return nil, fmt.Errorf("input is required")
|
return nil, fmt.Errorf("input is required")
|
||||||
}
|
}
|
||||||
@@ -35,25 +33,5 @@ func (s *LeaderboardService) Update(ctx context.Context, serverID uuid.UUID, lb
|
|||||||
for i := range lb.Races {
|
for i := range lb.Races {
|
||||||
lb.Races[i].Position = i
|
lb.Races[i].Position = i
|
||||||
}
|
}
|
||||||
result, err := s.repo.FullReplace(ctx, serverID, lb)
|
return s.repo.FullReplace(ctx, serverID, lb)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
driverCount := len(lb.Drivers)
|
|
||||||
raceCount := len(lb.Races)
|
|
||||||
details := fmt.Sprintf(`{"driver_count":%d,"race_count":%d}`, driverCount, raceCount)
|
|
||||||
go func() {
|
|
||||||
if logErr := s.activityLog.Log(context.Background(), &model.ActivityLog{
|
|
||||||
ServerID: serverID,
|
|
||||||
UserID: actorID,
|
|
||||||
Username: actorUsername,
|
|
||||||
Action: model.ActionLeaderboardUpdate,
|
|
||||||
Details: details,
|
|
||||||
}); logErr != nil {
|
|
||||||
logging.Error("Failed to log leaderboard update: %v", logErr)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ const (
|
|||||||
type ServerService struct {
|
type ServerService struct {
|
||||||
repository *repository.ServerRepository
|
repository *repository.ServerRepository
|
||||||
stateHistoryRepo *repository.StateHistoryRepository
|
stateHistoryRepo *repository.StateHistoryRepository
|
||||||
activityLogRepo *repository.ActivityLogRepository
|
|
||||||
apiService *ServiceControlService
|
apiService *ServiceControlService
|
||||||
configService *ConfigService
|
configService *ConfigService
|
||||||
steamService *SteamService
|
steamService *SteamService
|
||||||
@@ -48,16 +47,30 @@ type pendingState struct {
|
|||||||
|
|
||||||
func (s *ServerService) ensureLogTailing(server *model.Server, instance *tracking.AccServerInstance) {
|
func (s *ServerService) ensureLogTailing(server *model.Server, instance *tracking.AccServerInstance) {
|
||||||
go func() {
|
go func() {
|
||||||
if err := s.logStreamer.Start(context.Background(), server, instance.HandleLogLine); err != nil {
|
handleFn := func(line string) {
|
||||||
|
instance.HandleLogLine(line)
|
||||||
|
s.webSocketService.BroadcastLogLine(server.ID, line)
|
||||||
|
}
|
||||||
|
if err := s.logStreamer.Start(context.Background(), server, handleFn); err != nil {
|
||||||
logging.Error("Failed to start log streaming for server %s: %v", server.ID, err)
|
logging.Error("Failed to start log streaming for server %s: %v", server.ID, err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *ServerService) GetLastLogLines(ctx *fiber.Ctx, serverID uuid.UUID, n int) ([]string, error) {
|
||||||
|
server, err := s.repository.GetByID(ctx.UserContext(), serverID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if n <= 0 {
|
||||||
|
n = 100
|
||||||
|
}
|
||||||
|
return s.logStreamer.GetLastLines(ctx.UserContext(), server, n)
|
||||||
|
}
|
||||||
|
|
||||||
func NewServerService(
|
func NewServerService(
|
||||||
repository *repository.ServerRepository,
|
repository *repository.ServerRepository,
|
||||||
stateHistoryRepo *repository.StateHistoryRepository,
|
stateHistoryRepo *repository.StateHistoryRepository,
|
||||||
activityLogRepo *repository.ActivityLogRepository,
|
|
||||||
apiService *ServiceControlService,
|
apiService *ServiceControlService,
|
||||||
configService *ConfigService,
|
configService *ConfigService,
|
||||||
steamService *SteamService,
|
steamService *SteamService,
|
||||||
@@ -70,7 +83,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 +281,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 +297,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
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -103,6 +103,16 @@ func (ws *WebSocketService) BroadcastError(serverID uuid.UUID, error string, det
|
|||||||
ws.broadcastToServer(serverID, wsMsg)
|
ws.broadcastToServer(serverID, wsMsg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ws *WebSocketService) BroadcastLogLine(serverID uuid.UUID, line string) {
|
||||||
|
msg := model.WebSocketMessage{
|
||||||
|
Type: model.MessageTypeLogLine,
|
||||||
|
ServerID: &serverID,
|
||||||
|
Timestamp: time.Now().Unix(),
|
||||||
|
Data: model.LogLineMessage{Line: line},
|
||||||
|
}
|
||||||
|
ws.broadcastToServer(serverID, msg)
|
||||||
|
}
|
||||||
|
|
||||||
func (ws *WebSocketService) BroadcastComplete(serverID uuid.UUID, success bool, message string) {
|
func (ws *WebSocketService) BroadcastComplete(serverID uuid.UUID, success bool, message string) {
|
||||||
completeMsg := model.CompleteMessage{
|
completeMsg := model.CompleteMessage{
|
||||||
ServerID: serverID,
|
ServerID: serverID,
|
||||||
|
|||||||
@@ -28,8 +28,7 @@ type RouteGroups struct {
|
|||||||
WebSocket fiber.Router
|
WebSocket fiber.Router
|
||||||
Leaderboard fiber.Router
|
Leaderboard fiber.Router
|
||||||
Steam fiber.Router
|
Steam fiber.Router
|
||||||
ActivityLog fiber.Router
|
Log fiber.Router
|
||||||
Groups fiber.Router
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func CheckError(err error) {
|
func CheckError(err error) {
|
||||||
|
|||||||
@@ -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")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ 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)
|
||||||
@@ -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,7 +115,7 @@ 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)
|
||||||
@@ -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)
|
||||||
@@ -276,7 +276,7 @@ func TestConfigService_Caching_EventConfig(t *testing.T) {
|
|||||||
|
|
||||||
configRepo := repository.NewConfigRepository(helper.DB)
|
configRepo := repository.NewConfigRepository(helper.DB)
|
||||||
serverRepo := repository.NewServerRepository(helper.DB)
|
serverRepo := repository.NewServerRepository(helper.DB)
|
||||||
configService := service.NewConfigService(configRepo, serverRepo, nil)
|
configService := service.NewConfigService(configRepo, serverRepo)
|
||||||
|
|
||||||
event1, err := configService.GetEventConfig(helper.TestData.Server)
|
event1, err := configService.GetEventConfig(helper.TestData.Server)
|
||||||
tests.AssertNoError(t, err)
|
tests.AssertNoError(t, err)
|
||||||
|
|||||||
Reference in New Issue
Block a user