Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions agent/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,10 @@ func main() {
transport = rcon.New(rconHost, rconPort, rcon.PasswordFromFile(rconPassFile))
}

flushOnly := rconEnabled && capSpec != nil && capSpec.BackupFlush == "minecraft-save-all" && gameName == "minecraft-java" && capSpec.Quiesce == nil
commands := rcon.NewCommands(transport)
rconClient := transport
if quiesceSpec != nil {
if quiesceSpec != nil || flushOnly {
Comment thread
Baylem marked this conversation as resolved.
Resolved
rconClient = commands
}
r := chi.NewRouter()
Expand Down Expand Up @@ -219,9 +220,17 @@ func main() {
for _, version := range []string{"v1", "v2"} {
r.Route("/"+version+"/pods/{uid}", func(protected chi.Router) {
protected.Use(authCheck.Middleware, target.Guard(envOr("GAMEPLANE_POD_UID", "")), middleware.Timeout(30*time.Second))
protected.Get("/identity", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })
protected.Get("/identity", func(w http.ResponseWriter, _ *http.Request) {
if version == "v2" && flushOnly {
w.Header().Set("Gameplane-Backup-Mode", "flush-only")
}
w.WriteHeader(http.StatusNoContent)
})
if version == "v2" {
quiesce.MountVerified(protected, commands, gameName, quiesceSpec)
if flushOnly {
quiesce.MountMinecraftFlush(protected, commands)
}
} else {
quiesce.Mount(protected, commands, gameName, quiesceSpec)
}
Expand Down
2 changes: 1 addition & 1 deletion agent/internal/actions/actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func (h *handler) run(w http.ResponseWriter, req *http.Request) {
return
}

raw, err := h.rc.Exec(cmd)
raw, err := rcon.WithContext(req.Context(), h.rc).Exec(cmd)
if errors.Is(err, rcon.ErrDisabled) {
httpjson.Error(w, http.StatusNotImplemented, fmt.Sprintf("not supported by %s (no RCON)", h.game))
return
Expand Down
13 changes: 7 additions & 6 deletions agent/internal/caps/caps.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ import (

// Spec is the root capabilities document.
type Spec struct {
Players *PlayerActions `json:"players,omitempty"`
Quiesce *Quiesce `json:"quiesce,omitempty"`
Lifecycle *Lifecycle `json:"lifecycle,omitempty"`
Actions []ServerAction `json:"actions,omitempty"`
Status *Status `json:"status,omitempty"`
Mods *Mods `json:"mods,omitempty"`
BackupFlush string `json:"backupFlush,omitempty"`
Players *PlayerActions `json:"players,omitempty"`
Quiesce *Quiesce `json:"quiesce,omitempty"`
Lifecycle *Lifecycle `json:"lifecycle,omitempty"`
Actions []ServerAction `json:"actions,omitempty"`
Status *Status `json:"status,omitempty"`
Mods *Mods `json:"mods,omitempty"`
}

// Lifecycle declares command sequences the agent runs over RCON to drive
Expand Down
38 changes: 28 additions & 10 deletions agent/internal/console/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,19 +54,37 @@ func (h *handler) serve(w http.ResponseWriter, req *http.Request) {
}
defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()

ctx := req.Context()
for {
var in Envelope
if err := wsjson.Read(ctx, conn, &in); err != nil {
if !errors.Is(err, context.Canceled) {
_ = conn.Close(websocket.StatusInternalError, err.Error())
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
// Reading must continue while a command waits behind a backup, so a
// closed WebSocket cancels admission before the command can run.
input := make(chan string, 16)
go func() {
defer close(input)
defer cancel()
for {
var in Envelope
if err := wsjson.Read(ctx, conn, &in); err != nil {
return
}
if in.Kind != "cmd" || in.Body == "" {
continue
}
select {
case input <- in.Body:
default:
cancel()
_ = conn.Close(websocket.StatusPolicyViolation, "too many queued console commands")
return
}
return
}
if in.Kind != "cmd" || in.Body == "" {
continue
}()
rc := rcon.WithContext(ctx, h.rcon)
for command := range input {
if ctx.Err() != nil {
return
}
out, err := h.rcon.Exec(in.Body)
out, err := rc.Exec(command)
env := Envelope{Kind: "out", Body: out}
if err != nil {
errBody := "upstream unavailable"
Expand Down
46 changes: 46 additions & 0 deletions agent/internal/console/console_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"testing"
"time"

"github.com/GameplanePanel/gameplane/agent/internal/rcon"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"github.com/go-chi/chi/v5"
Expand Down Expand Up @@ -189,3 +190,48 @@ func TestConsole_ClientCloseEndsLoop(t *testing.T) {
// read-error return path is the goal.
time.Sleep(50 * time.Millisecond)
}

type queuedConsole struct {
*rcon.Commands
waiting chan struct{}
finished chan error
}

func (q queuedConsole) ExecContext(ctx context.Context, cmd string) (string, error) {
close(q.waiting)
out, err := q.Commands.ExecContext(ctx, cmd)
q.finished <- err
return out, err
}

func TestConsole_DisconnectCancelsQueuedCommand(t *testing.T) {
rc := &fakeRcon{}
q := queuedConsole{rcon.NewCommands(rc), make(chan struct{}), make(chan error, 1)}
_, wsURL := newServer(t, q)
conn, ctx, _ := dial(t, wsURL)
err := q.Sequence(ctx, func(rcon.Executor) error {
if err := wsjson.Write(ctx, conn, Envelope{Kind: "cmd", Body: "stop"}); err != nil {
return err
}
select {
case <-q.waiting:
case <-ctx.Done():
return ctx.Err()
}
if err := conn.CloseNow(); err != nil {
return err
}
select {
case err := <-q.finished:
if !errors.Is(err, context.Canceled) {
t.Fatalf("disconnected command returned %v", err)
}
case <-ctx.Done():
return ctx.Err()
}
return nil
})
if err != nil || rc.gotCmd != "" {
t.Fatalf("command after disconnect: %q, %v", rc.gotCmd, err)
}
}
2 changes: 2 additions & 0 deletions agent/internal/lifecycle/lifecycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ func Mount(r chi.Router, rc Rcon, _ string, spec *caps.Lifecycle) {
httpjson.Write(w, http.StatusOK, response{Stopped: false, Reason: "game declares no stop sequence"})
return
}
// Finish the game's shutdown sequence even if the operator disconnects
// while waiting for a backup to release RCON.
s.Stop(rc)
httpjson.Write(w, http.StatusOK, response{Stopped: true})
})
Expand Down
34 changes: 34 additions & 0 deletions agent/internal/lifecycle/lifecycle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ import (
"io"
"net/http"
"net/http/httptest"
"slices"
"sync"
"testing"
"testing/synctest"

"github.com/go-chi/chi/v5"

"github.com/GameplanePanel/gameplane/agent/internal/caps"
"github.com/GameplanePanel/gameplane/agent/internal/rcon"
)

type fakeRcon struct {
Expand Down Expand Up @@ -70,6 +73,37 @@ func TestStop_RunsDeclaredSequenceInOrder(t *testing.T) {
}
}

func TestStop_FinishesQueuedSequenceAfterRequestCancellation(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
transport := &fakeRcon{}
commands := rcon.NewCommands(transport)
router := chi.NewRouter()
sequence := []string{"save-all flush", "stop"}
Mount(router, commands, "minecraft-java", &caps.Lifecycle{Stop: sequence})
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/lifecycle/stop", nil)
rec := httptest.NewRecorder()

// Hold admission as a backup does. Disconnect the operator while its
// stop request is queued, then allow the backup to release the transport.
err := commands.Sequence(t.Context(), func(rcon.Executor) error {
go router.ServeHTTP(rec, req)
synctest.Wait()
cancel()
synctest.Wait()
return nil
})
if err != nil {
t.Fatal(err)
}
synctest.Wait()
if calls := transport.calls(); !slices.Equal(calls, sequence) {
t.Fatalf("stop commands after disconnect = %v, want %v", calls, sequence)
}
})
}

func TestStop_ToleratesRconError(t *testing.T) {
// The stop command brings RCON down, so an error is the expected outcome
// — the call must still report success and run every command.
Expand Down
22 changes: 13 additions & 9 deletions agent/internal/players/players.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
package players

import (
"context"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -118,14 +119,14 @@ func Mount(r chi.Router, rc Rcon, game string, actions *caps.PlayerActions) {

const cacheTTL = 5 * time.Second

func (h *handler) serve(w http.ResponseWriter, _ *http.Request) {
func (h *handler) serve(w http.ResponseWriter, req *http.Request) {
h.mu.Lock()
fresh := time.Since(h.lastFetch) < cacheTTL
result, err := h.lastResult, h.lastErr
h.mu.Unlock()

if !fresh {
result, err = h.fetch()
result, err = h.fetch(req.Context())
}
if errors.Is(err, rcon.ErrDisabled) {
// The game has no RCON: player counts are simply unknown. The
Expand All @@ -150,8 +151,11 @@ func (h *handler) serve(w http.ResponseWriter, _ *http.Request) {
httpjson.Write(w, http.StatusOK, result)
}

func (h *handler) fetch() (Snapshot, error) {
raw, err := h.rcon.Exec(h.listCmd)
func (h *handler) fetch(ctx context.Context) (Snapshot, error) {
raw, err := rcon.WithContext(ctx, h.rcon).Exec(h.listCmd)
if ctx.Err() != nil {
return Snapshot{}, ctx.Err()
}
h.mu.Lock()
defer h.mu.Unlock()
h.lastFetch = time.Now()
Expand Down Expand Up @@ -231,7 +235,7 @@ func (h *handler) runMod(
httpjson.Error(w, http.StatusNotImplemented, fmt.Sprintf("not supported by %s", h.game))
return
}
raw, err := h.rcon.Exec(cmd)
raw, err := rcon.WithContext(req.Context(), h.rcon).Exec(cmd)
if errors.Is(err, rcon.ErrDisabled) {
httpjson.Error(w, http.StatusNotImplemented, fmt.Sprintf("not supported by %s (no RCON)", h.game))
return
Expand All @@ -258,15 +262,15 @@ func (h *handler) whitelistRemove(w http.ResponseWriter, req *http.Request) {
}, false)
}

func (h *handler) whitelistList(w http.ResponseWriter, _ *http.Request) {
func (h *handler) whitelistList(w http.ResponseWriter, req *http.Request) {
cmd, ok := h.cmdr.WhitelistList()
if !ok {
// Empty list rather than 501 so a Whitelist tab renders uniformly;
// capabilities advertise whether management is actually available.
httpjson.Write(w, http.StatusOK, []string{})
return
}
raw, err := h.rcon.Exec(cmd)
raw, err := rcon.WithContext(req.Context(), h.rcon).Exec(cmd)
if errors.Is(err, rcon.ErrDisabled) {
httpjson.Write(w, http.StatusOK, []string{})
return
Expand All @@ -283,15 +287,15 @@ func (h *handler) whitelistList(w http.ResponseWriter, _ *http.Request) {
httpjson.Write(w, http.StatusOK, out)
}

func (h *handler) banned(w http.ResponseWriter, _ *http.Request) {
func (h *handler) banned(w http.ResponseWriter, req *http.Request) {
cmd, ok := h.cmdr.BanList()
if !ok {
// Empty list rather than 501: callers can render a Banned tab
// uniformly for every game; capabilities advertise reality.
httpjson.Write(w, http.StatusOK, []BannedPlayer{})
return
}
raw, err := h.rcon.Exec(cmd)
raw, err := rcon.WithContext(req.Context(), h.rcon).Exec(cmd)
if errors.Is(err, rcon.ErrDisabled) {
httpjson.Write(w, http.StatusOK, []BannedPlayer{})
return
Expand Down
16 changes: 16 additions & 0 deletions agent/internal/quiesce/quiesce.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,22 @@ func mount(r chi.Router, rc *rcon.Commands, game string, q Quiescer, verified bo
handle("/unquiesce", "resumed", false, q.Unquiesce)
}

// MountMinecraftFlush cannot pause or resume saving. Even a lost response
// leaves the game free to write; the caller can repeat the same checkpoint.
func MountMinecraftFlush(r chi.Router, rc *rcon.Commands) {
r.Post("/flush", func(w http.ResponseWriter, req *http.Request) {
err := rc.Sequence(req.Context(), func(transport rcon.Executor) error {
_, err := (minecraftReplies{transport}).Exec("save-all flush")
return err
})
if err != nil {
httpjson.Write(w, http.StatusBadGateway, response{Reason: "checkpoint was not acknowledged"})
return
}
httpjson.Write(w, http.StatusOK, response{Outcome: "flushed"})
})
}

type minecraftReplies struct{ Rcon }

// Vanilla Java 1.21.4 en_us commands.save.* messages. RCON can concatenate
Expand Down
21 changes: 21 additions & 0 deletions agent/internal/quiesce/verified_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,27 @@ func TestMinecraftPositiveCommandResponses(t *testing.T) {
}
}

func TestMinecraftCheckpointLeavesSavingEnabled(t *testing.T) {
for _, tc := range []struct {
reply string
code int
outcome string
}{
{"Saved the game", http.StatusOK, "flushed"},
{"Saving the game (this may take a moment!)", http.StatusBadGateway, ""},
} {
rc := &fakeRcon{respond: func(string) (string, error) { return tc.reply, nil }}
router := chi.NewRouter()
MountMinecraftFlush(router, rcon.NewCommands(rc))
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/flush", nil))
got := decodeResponse(t, w.Body.Bytes())
if w.Code != tc.code || got.Quiesced || got.Outcome != tc.outcome || !reflect.DeepEqual(rc.calls(), []string{"save-all flush"}) {
t.Fatalf("checkpoint reply %q: HTTP %d, %+v, commands %v", tc.reply, w.Code, got, rc.calls())
}
}
}

func TestVerifiedSequenceBlocksCleanupUntilRollbackFinishes(t *testing.T) {
reached, release := make(chan struct{}), make(chan struct{})
var once sync.Once
Expand Down
Loading
Loading