diff --git a/api/openapi.yaml b/api/openapi.yaml index 9edf4ba..66d4c62 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -1,5 +1,28 @@ components: schemas: + Capacity: + additionalProperties: false + properties: + memoryMiB: + description: Memory available for instances + format: int64 + type: integer + type: object + Command: + additionalProperties: false + properties: + instance: + type: string + line: + type: string + seq: + format: int64 + type: integer + required: + - seq + - instance + - line + type: object CommandBody: additionalProperties: false properties: @@ -34,6 +57,138 @@ components: required: - pool type: object + Desired: + additionalProperties: false + properties: + $schema: + description: A URL to the JSON Schema for this object. + examples: + - https://example.com/schemas/Desired.json + format: uri + readOnly: true + type: string + commands: + items: + $ref: "#/components/schemas/Command" + type: + - array + - "null" + instances: + items: + $ref: "#/components/schemas/DesiredInstance" + type: + - array + - "null" + revision: + description: Changes whenever the desired state changes + format: int64 + type: integer + required: + - revision + - instances + - commands + type: object + DesiredInstance: + additionalProperties: false + properties: + effective: + $ref: "#/components/schemas/EffectiveSpec" + env: + additionalProperties: + type: string + description: Environment of the instance as the controller built it; the agent overrides GRUS_URL + type: object + generation: + format: int64 + type: integer + id: + type: string + kill: + description: Kill the instance and forget it + type: boolean + memoryMiB: + format: int64 + type: integer + mode: + type: string + pool: + type: string + role: + type: string + stop: + $ref: "#/components/schemas/StopRequest" + templates: + items: + $ref: "#/components/schemas/TemplateVersion" + type: + - array + - "null" + token: + description: Plain per-instance token for GRUS_TOKEN + type: string + tokenHash: + type: string + required: + - id + - pool + - role + - mode + - generation + - effective + - stop + type: object + EffectiveSpec: + additionalProperties: false + properties: + args: + items: + type: string + type: + - array + - "null" + command: + items: + type: string + type: + - array + - "null" + driver: + type: string + env: + additionalProperties: + type: string + type: object + gracePeriod: + type: string + host: + type: string + image: + type: string + kind: + type: string + labels: + additionalProperties: + type: string + type: object + port: + format: int64 + type: integer + readiness: + type: string + stopCommand: + type: string + templates: + items: + $ref: "#/components/schemas/TemplateRef" + type: + - array + - "null" + required: + - driver + - port + - readiness + - gracePeriod + type: object Environment: additionalProperties: false properties: @@ -228,6 +383,45 @@ components: - array - "null" type: object + HostInfo: + additionalProperties: false + properties: + $schema: + description: A URL to the JSON Schema for this object. + examples: + - https://example.com/schemas/HostInfo.json + format: uri + readOnly: true + type: string + address: + type: string + capacity: + $ref: "#/components/schemas/Capacity" + instances: + description: Instances the agent reported + format: int64 + type: integer + labels: + additionalProperties: + type: string + type: object + lastSeen: + description: Last contact of the agent; absent when it never connected + format: date-time + type: string + name: + type: string + online: + type: boolean + portRange: + type: string + version: + type: string + required: + - name + - online + - instances + type: object Instance: additionalProperties: false properties: @@ -356,6 +550,72 @@ components: - maxPlayers - proxies type: object + ObservedInstance: + additionalProperties: false + properties: + address: + type: string + generation: + format: int64 + type: integer + id: + type: string + mode: + type: string + phase: + type: string + pool: + type: string + reason: + type: string + role: + type: string + startedAt: + format: date-time + type: string + tokenHash: + type: string + required: + - id + - phase + type: object + ObservedReport: + additionalProperties: false + properties: + $schema: + description: A URL to the JSON Schema for this object. + examples: + - https://example.com/schemas/ObservedReport.json + format: uri + readOnly: true + type: string + commandSeq: + description: Highest console command sequence number the agent has applied + format: int64 + type: integer + instances: + items: + $ref: "#/components/schemas/ObservedInstance" + type: + - array + - "null" + logs: + additionalProperties: + items: + type: string + type: + - array + - "null" + description: Last console lines per instance id + type: object + revision: + description: Desired revision the agent has applied before this report + format: int64 + type: integer + required: + - revision + - instances + type: object Placement: additionalProperties: false properties: @@ -489,6 +749,33 @@ components: format: int64 type: integer type: object + RegisterRequest: + additionalProperties: false + properties: + $schema: + description: A URL to the JSON Schema for this object. + examples: + - https://example.com/schemas/RegisterRequest.json + format: uri + readOnly: true + type: string + address: + description: IP address proxies use to reach instances on this host + type: string + capacity: + $ref: "#/components/schemas/Capacity" + labels: + additionalProperties: + type: string + description: Free host labels + type: object + portRange: + description: Instance port range, e.g. 30000-30100 + type: string + version: + description: Agent version + type: string + type: object Resources: additionalProperties: false properties: @@ -597,6 +884,21 @@ components: force: type: boolean type: object + StopRequest: + additionalProperties: false + properties: + command: + description: Console line that triggers a clean shutdown + type: string + graceSeconds: + description: Time before the agent sends SIGTERM + format: int64 + type: integer + requested: + type: boolean + required: + - requested + type: object TagBody: additionalProperties: false properties: @@ -626,6 +928,17 @@ components: required: - name type: object + TemplateVersion: + additionalProperties: false + properties: + digest: + type: string + name: + type: string + required: + - name + - digest + type: object securitySchemes: bearer: scheme: bearer @@ -663,6 +976,115 @@ paths: type: string description: not ready summary: Readiness + /v1/agents/{host}: + put: + operationId: register-agent + parameters: + - description: Agent host name + in: path + name: host + required: true + schema: + description: Agent host name + pattern: ^[a-z0-9][a-z0-9._-]{0,62}$ + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RegisterRequest" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/HostInfo" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Register an agent host or send its heartbeat + /v1/agents/{host}/desired: + get: + operationId: get-agent-desired + parameters: + - description: Agent host name + in: path + name: host + required: true + schema: + description: Agent host name + pattern: ^[a-z0-9][a-z0-9._-]{0,62}$ + type: string + - description: How long the request may wait for a change, as a duration (max 60s) + explode: false + in: query + name: wait + schema: + default: 25s + description: How long the request may wait for a change, as a duration (max 60s) + type: string + - description: Revision the agent already has; the call returns at once when it differs + explode: false + in: query + name: revision + schema: + default: -1 + description: Revision the agent already has; the call returns at once when it differs + format: int64 + type: integer + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Desired" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Long-poll the desired state of an agent host + /v1/agents/{host}/observed: + put: + operationId: put-agent-observed + parameters: + - description: Agent host name + in: path + name: host + required: true + schema: + description: Agent host name + pattern: ^[a-z0-9][a-z0-9._-]{0,62}$ + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/ObservedReport" + required: true + responses: + "204": + description: No Content + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Report the instances an agent host runs /v1/environments: get: operationId: list-environments @@ -901,6 +1323,56 @@ paths: security: - bearer: [] summary: Create or replace a group + /v1/hosts: + get: + operationId: list-hosts + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/HostInfo" + type: + - array + - "null" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: List agent hosts + /v1/hosts/{name}: + get: + operationId: get-host + parameters: + - description: Host name + in: path + name: name + required: true + schema: + description: Host name + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/HostInfo" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Get an agent host /v1/instances: get: operationId: list-instances diff --git a/cmd/grus-agent/config.go b/cmd/grus-agent/config.go new file mode 100644 index 0000000..73d12a6 --- /dev/null +++ b/cmd/grus-agent/config.go @@ -0,0 +1,74 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "github.com/OneLiteFeatherNET/grus/internal/agent" + "os" + "strconv" + "strings" +) + +// parseConfig parses args on top of the environment read through getenv. hostname supplies the default host. +func parseConfig(args []string, getenv func(string) string, hostname func() (string, error)) (agent.Config, error) { + fs := flag.NewFlagSet("grus-agent", flag.ContinueOnError) + str := func(name, env, def, usage string) *string { + v := getenv(env) + if v == "" { + v = def + } + return fs.String(name, v, usage+" ["+env+"]") + } + defHost := "" + if h, err := hostname(); err == nil { + defHost = strings.ToLower(h) + } + url := str("url", "GRUS_URL", "", "controller URL, e.g. https://grus.example.org (required)") + tokenFile := str("token-file", "GRUS_AGENT_TOKEN_FILE", "", "file holding the agent token (required)") + host := str("host", "GRUS_AGENT_HOST", defHost, "host name this agent registers as") + dir := str("dir", "GRUS_AGENT_DIR", "./instances", "working directory of the instances") + address := str("address", "GRUS_AGENT_ADDRESS", "", "IP address proxies use to reach the instances (required)") + portRange := str("port-range", "GRUS_AGENT_PORT_RANGE", "30000-30100", "instance port range min-max") + java := str("java", "GRUS_AGENT_JAVA", "", "java binary used for commands that start with java") + caFile := str("ca-file", "GRUS_AGENT_CA_FILE", "", "extra CA certificates (PEM) for the controller URL, optional") + stopOnExit := str("stop-on-exit", "GRUS_AGENT_STOP_ON_EXIT", "false", "stop the instances when the agent exits (true/false)") + if err := fs.Parse(args); err != nil { + return agent.Config{}, err + } + if fs.NArg() > 0 { + return agent.Config{}, fmt.Errorf("unexpected arguments: %s", strings.Join(fs.Args(), " ")) + } + + cfg := agent.Config{Version: version, URL: strings.TrimSuffix(*url, "/"), Host: *host, Dir: *dir, Address: *address, Java: *java, CAFile: *caFile} + switch { + case cfg.URL == "": + return agent.Config{}, errors.New("GRUS_URL (--url) is required") + case !strings.HasPrefix(cfg.URL, "https://") && !strings.HasPrefix(cfg.URL, "http://"): + return agent.Config{}, errors.New("GRUS_URL must start with https:// or http://") + case cfg.Host == "" || strings.ContainsAny(cfg.Host, "/ "): + return agent.Config{}, errors.New("--host must be a host name without slashes or spaces") + case cfg.Address == "": + return agent.Config{}, errors.New("GRUS_AGENT_ADDRESS (--address) is required: the IP proxies use to reach the instances") + case *tokenFile == "": + return agent.Config{}, errors.New("GRUS_AGENT_TOKEN_FILE (--token-file) is required") + } + raw, err := os.ReadFile(*tokenFile) + if err != nil { + return agent.Config{}, fmt.Errorf("read token file: %w", err) + } + if cfg.Token = strings.TrimSpace(string(raw)); cfg.Token == "" { + return agent.Config{}, errors.New("token file is empty") + } + lo, hi, ok := strings.Cut(*portRange, "-") + if cfg.PortMin, err = strconv.Atoi(lo); err != nil || !ok { + return agent.Config{}, fmt.Errorf("--port-range %q must look like 30000-30100", *portRange) + } + if cfg.PortMax, err = strconv.Atoi(hi); err != nil || cfg.PortMin < 1 || cfg.PortMax < cfg.PortMin || cfg.PortMax > 65535 { + return agent.Config{}, fmt.Errorf("--port-range %q must look like 30000-30100", *portRange) + } + if cfg.StopOnExit, err = strconv.ParseBool(*stopOnExit); err != nil { + return agent.Config{}, fmt.Errorf("GRUS_AGENT_STOP_ON_EXIT: %w", err) + } + return cfg, nil +} diff --git a/cmd/grus-agent/config_test.go b/cmd/grus-agent/config_test.go new file mode 100644 index 0000000..5d1927b --- /dev/null +++ b/cmd/grus-agent/config_test.go @@ -0,0 +1,73 @@ +package main + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +func envOf(m map[string]string) func(string) string { return func(k string) string { return m[k] } } + +func host() (string, error) { return "MC01", nil } + +func tokenFile(t *testing.T, content string) string { + t.Helper() + p := filepath.Join(t.TempDir(), "token") + if err := os.WriteFile(p, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +func TestParseConfigReadsEnvironmentAndAppliesDefaults(t *testing.T) { + env := map[string]string{ + "GRUS_URL": "https://grus-dev-api.apps.onelite.feather/", "GRUS_AGENT_TOKEN_FILE": tokenFile(t, "secret\n"), + "GRUS_AGENT_ADDRESS": "10.200.2.35", + } + cfg, err := parseConfig(nil, envOf(env), host) + if err != nil { + t.Fatalf("parseConfig: %v", err) + } + if cfg.URL != "https://grus-dev-api.apps.onelite.feather" || cfg.Token != "secret" || cfg.Host != "mc01" || + cfg.PortMin != 30000 || cfg.PortMax != 30100 || cfg.Dir != "./instances" || cfg.StopOnExit { + t.Errorf("config = %+v", cfg) + } +} + +func TestParseConfigFlagsOverrideEnvironment(t *testing.T) { + env := map[string]string{"GRUS_URL": "https://a", "GRUS_AGENT_TOKEN_FILE": tokenFile(t, "s"), "GRUS_AGENT_ADDRESS": "1.2.3.4"} + cfg, err := parseConfig([]string{"--host", "mc02", "--port-range", "31000-31010", "--stop-on-exit=true", "--java", "/opt/java"}, envOf(env), host) + if err != nil { + t.Fatalf("parseConfig: %v", err) + } + if cfg.Host != "mc02" || cfg.PortMin != 31000 || cfg.PortMax != 31010 || !cfg.StopOnExit || cfg.Java != "/opt/java" { + t.Errorf("config = %+v", cfg) + } +} + +func TestParseConfigRejectsBadInput(t *testing.T) { + good := func() map[string]string { + return map[string]string{"GRUS_URL": "https://a", "GRUS_AGENT_TOKEN_FILE": tokenFile(t, "s"), "GRUS_AGENT_ADDRESS": "1.2.3.4"} + } + for name, mod := range map[string]func(map[string]string){ + "no url": func(m map[string]string) { delete(m, "GRUS_URL") }, + "url without http": func(m map[string]string) { m["GRUS_URL"] = "grus.example" }, + "no address": func(m map[string]string) { delete(m, "GRUS_AGENT_ADDRESS") }, + "no token file": func(m map[string]string) { delete(m, "GRUS_AGENT_TOKEN_FILE") }, + "missing file": func(m map[string]string) { m["GRUS_AGENT_TOKEN_FILE"] = "/nonexistent/token" }, + "empty token": func(m map[string]string) { m["GRUS_AGENT_TOKEN_FILE"] = tokenFile(t, " \n") }, + "bad range": func(m map[string]string) { m["GRUS_AGENT_PORT_RANGE"] = "30100-30000" }, + "range not numbers": func(m map[string]string) { m["GRUS_AGENT_PORT_RANGE"] = "a-b" }, + } { + env := good() + mod(env) + if _, err := parseConfig(nil, envOf(env), host); err == nil { + t.Errorf("%s: parseConfig returned nil error", name) + } + } + if _, err := parseConfig(nil, envOf(nil), func() (string, error) { return "", errors.New("x") }); err == nil || strings.Contains(err.Error(), "secret") { + t.Errorf("missing config err = %v", err) + } +} diff --git a/cmd/grus-agent/main.go b/cmd/grus-agent/main.go index f266cf8..4a78fd0 100644 --- a/cmd/grus-agent/main.go +++ b/cmd/grus-agent/main.go @@ -1,13 +1,93 @@ -// Command grus-agent will run instances on hosts outside Kubernetes (mc01). It is a stub in the -// prototype and must never import client-go. +// Command grus-agent runs Grus instances on a host outside Kubernetes. It pulls the desired instances from +// the controller over HTTPS, runs them as local processes and reports what it observes. It never imports +// client-go. +// +// An agent restart ends its instances (the agent cannot re-attach to them) and starts them again from the +// desired state. A SIGTERM to the agent does not stop instances unless --stop-on-exit is set. package main import ( + "context" "fmt" + "github.com/OneLiteFeatherNET/grus/internal/agent" + "log/slog" "os" + "os/signal" + "path/filepath" + "syscall" + + "github.com/OneLiteFeatherNET/grus/internal/driver" + processdriver "github.com/OneLiteFeatherNET/grus/internal/driver/process" + "github.com/OneLiteFeatherNET/grus/internal/model" + "github.com/OneLiteFeatherNET/grus/internal/templates" ) +// version is set at build time with -ldflags "-X main.version=...". +var version = "dev" + func main() { - fmt.Fprintln(os.Stderr, "grus-agent is not implemented yet") - os.Exit(1) + if err := run(os.Args[1:]); err != nil { + fmt.Fprintf(os.Stderr, "grus-agent: %v\n", err) + os.Exit(1) + } +} + +func run(args []string) error { + if len(args) == 1 && args[0] == "version" { + fmt.Println(version) + return nil + } + cfg, err := parseConfig(args, os.Getenv, os.Hostname) + if err != nil { + return err + } + logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + httpClient, err := agent.NewHTTPClient(cfg.CAFile) + if err != nil { + return err + } + dir, err := filepath.Abs(cfg.Dir) + if err != nil { + return err + } + cfg.Dir = dir + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("create instance directory: %w", err) + } + agent.KillOrphans(dir, logger) + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + fetch := func(ctx context.Context, refs []driver.ResolvedTemplate, dest string) error { + list := make([]templates.Ref, len(refs)) + for i, r := range refs { + list[i] = templates.Ref{Name: r.Name, Digest: r.Digest} + } + return templates.Fetch(ctx, templates.FetchOptions{ + BaseURL: cfg.URL, Token: cfg.Token, Dest: dest, Templates: list, Client: httpClient, + }) + } + procs := processdriver.New(processdriver.Config{ + HostID: cfg.Host, + BaseDir: dir, + FetchTemplates: fetch, + Logger: logger, + Clock: model.SystemClock{}, + PortMin: cfg.PortMin, + PortMax: cfg.PortMax, + AdvertiseAddress: cfg.Address, + JavaPath: cfg.Java, + }) + api := agent.NewClient(cfg.URL, cfg.Host, cfg.Token, httpClient) + a := agent.New(ctx, cfg, api, procs, logger) + + logger.Info("agent started", "host", cfg.Host, "controller", cfg.URL, "dir", dir, "version", version) + a.Run(ctx) + if cfg.StopOnExit { + logger.Info("stopping instances before exit") + a.StopAll(context.Background()) + } + logger.Info("agent stopped") + return nil } diff --git a/cmd/grus/agent_e2e_test.go b/cmd/grus/agent_e2e_test.go new file mode 100644 index 0000000..020fe86 --- /dev/null +++ b/cmd/grus/agent_e2e_test.go @@ -0,0 +1,173 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "log/slog" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/agent" + processdriver "github.com/OneLiteFeatherNET/grus/internal/driver/process" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +const e2eAgentToken = "e2e-agent-token-0123456789" + +// TestAgentRunsAnInstanceOfAPlacedPoolFromStartToDrain runs the controller and a grus-agent in one process +// on loopback. A pool placed on the agent host must be started by the agent (the test binary acts as the +// game server), report ready through the self API, become Ready in the controller and be stopped again. +// +// Like the other end-to-end test it polls with a short interval under a hard deadline instead of sleeping: +// the agent, the controller loop and a child process run concurrently, so there is no clock to inject. +func TestAgentRunsAnInstanceOfAPlacedPoolFromStartToDrain(t *testing.T) { + dir := t.TempDir() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen on loopback: %v", err) + } + baseURL := "http://" + ln.Addr().String() + sum := sha256.Sum256([]byte(e2eAgentToken)) + cfg := config{ + DB: filepath.Join(dir, "grus.db"), + TemplatesDir: filepath.Join(dir, "templates"), + Driver: "process", + HostID: "local", + ProcessDir: filepath.Join(dir, "controller-instances"), + PublicURL: "http://cluster.invalid:8080", // the agent must replace it with the URL it uses + AdminToken: e2eAdminToken, + MaxInstances: 10, + ReconcileInterval: pollInterval, + AgentTokens: map[string]string{"mc01": hex.EncodeToString(sum[:])}, + } + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + ctx, cancel := context.WithCancel(context.Background()) + s, err := newStack(ctx, cfg, logger) + if err != nil { + cancel() + t.Fatalf("newStack: %v", err) + } + srv := &http.Server{Handler: s.handler} + go func() { _ = srv.Serve(ln) }() + ctrlDone := make(chan struct{}) + go func() { _ = s.ctrl.Run(ctx); close(ctrlDone) }() + + pl, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("find a port: %v", err) + } + port := pl.Addr().(*net.TCPAddr).Port + _ = pl.Close() + procs := processdriver.New(processdriver.Config{ + HostID: "mc01", BaseDir: filepath.Join(dir, "agent-instances"), Logger: logger, + PortMin: port, PortMax: port, AdvertiseAddress: "127.0.0.1", + }) + acfg := agent.Config{URL: baseURL, Token: e2eAgentToken, Host: "mc01", Dir: filepath.Join(dir, "agent-instances"), + Address: "127.0.0.1", PortMin: port, PortMax: port, ReportInterval: pollInterval} + a := agent.New(ctx, acfg, agent.NewClient(baseURL, "mc01", e2eAgentToken, http.DefaultClient), procs, logger) + agentDone := make(chan struct{}) + go func() { a.Run(ctx); close(agentDone) }() + + t.Cleanup(func() { + if obs, err := procs.List(context.Background()); err == nil { + for _, o := range obs { + _ = procs.Kill(context.Background(), o.Ref) + } + } + cancel() + <-agentDone + <-ctrlDone + _ = srv.Close() + _ = s.store.Close() + }) + + client := &http.Client{} + putJSON(t, client, baseURL, "/v1/pools/mc01-stub", model.PoolSpec{ + Role: model.RoleGame, + Mode: model.ModeDynamic, + Placement: model.Placement{Driver: model.DriverAgent, Host: "mc01"}, + Command: []string{os.Args[0], "-test.run=TestHelperProcess"}, + Env: map[string]string{helperEnv: "1"}, + Resources: model.Resources{MemoryMiB: 128}, + Scaling: model.Scaling{Min: 1, Max: 1, Capacity: 10}, + Lifecycle: model.Lifecycle{GracePeriod: model.Duration(100 * time.Millisecond)}, + }) + + var inst model.Instance + waitFor(t, "instance Ready on mc01", func() bool { + var list []model.Instance + getJSON(t, client, baseURL, "/v1/instances", &list) + if len(list) == 1 && list[0].State == model.StateReady { + inst = list[0] + return true + } + return false + }) + if inst.Host != "mc01" { + t.Errorf("instance host = %q, want mc01", inst.Host) + } + if want := "127.0.0.1:"; !strings.HasPrefix(inst.Address, want) { + t.Errorf("instance address = %q, want it to start with %s", inst.Address, want) + } + var hosts []map[string]any + getJSON(t, client, baseURL, "/v1/hosts", &hosts) + if len(hosts) != 1 || hosts[0]["online"] != true { + t.Errorf("hosts = %v, want mc01 online", hosts) + } + + postJSON(t, client, baseURL, "/v1/instances/"+inst.ID+"/stop", map[string]any{}) + waitFor(t, "stopped instance to disappear", func() bool { + var list []model.Instance + getJSON(t, client, baseURL, "/v1/instances", &list) + for _, i := range list { + if i.ID == inst.ID && i.State != model.StateStopped { + return false + } + } + return true + }) +} + +// waitFor polls cond every pollInterval until it holds or e2eTimeout passes. +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.NewTimer(e2eTimeout) + defer deadline.Stop() + ticker := time.NewTicker(pollInterval) + defer ticker.Stop() + for !cond() { + select { + case <-ticker.C: + case <-deadline.C: + t.Fatalf("timed out after %s waiting for %s", e2eTimeout, what) + } + } +} + +func postJSON(t *testing.T, client *http.Client, baseURL, path string, body any) { + t.Helper() + raw, _ := json.Marshal(body) + req, err := http.NewRequest(http.MethodPost, baseURL+path, strings.NewReader(string(raw))) + if err != nil { + t.Fatalf("build POST %s: %v", path, err) + } + req.Header.Set("Authorization", "Bearer "+e2eAdminToken) + req.Header.Set("Content-Type", "application/json") + resp, err := client.Do(req) + if err != nil { + t.Fatalf("POST %s: %v", path, err) + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + msg, _ := io.ReadAll(resp.Body) + t.Fatalf("POST %s: HTTP %d: %s", path, resp.StatusCode, msg) + } +} diff --git a/cmd/grus/agents.go b/cmd/grus/agents.go new file mode 100644 index 0000000..7596cff --- /dev/null +++ b/cmd/grus/agents.go @@ -0,0 +1,80 @@ +package main + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" + + "github.com/OneLiteFeatherNET/grus/internal/driver" + "github.com/OneLiteFeatherNET/grus/internal/driver/remote" + "github.com/OneLiteFeatherNET/grus/internal/driver/router" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +// parseAgentTokens parses GRUS_AGENT_TOKENS: a comma list of host=. +// Only hashes are configured, so the setting is safe to keep in a ConfigMap-like place. +func parseAgentTokens(s string) (map[string]string, error) { + pairs := splitList(s) + if len(pairs) == 0 { + return nil, nil + } + out := make(map[string]string, len(pairs)) + for _, pair := range pairs { + host, hash, ok := strings.Cut(pair, "=") + host, hash = strings.TrimSpace(host), strings.ToLower(strings.TrimSpace(hash)) + if !ok || host == "" { + return nil, errors.New("GRUS_AGENT_TOKENS: every entry must be host=") + } + if strings.Contains(host, "/") { + return nil, fmt.Errorf("GRUS_AGENT_TOKENS: host %q must not contain /", host) + } + if raw, err := hex.DecodeString(hash); err != nil || len(raw) != sha256.Size { + return nil, fmt.Errorf("GRUS_AGENT_TOKENS: the value for host %q is not a SHA-256 hex digest", host) + } + out[host] = hash + } + return out, nil +} + +// withAgents wraps the configured driver and the agent hosts in a router. The configured driver stays one +// host of its own; every host named in the agent tokens is registered up front, so its instances keep their +// state while the agent is away, and further hosts join when an agent contacts the controller. +func withAgents(base driver.Driver, cfg config) (driver.Driver, *remote.Registry, error) { + var reg *remote.Registry + rtr := router.New(placementSelector(base, func(host string) bool { return reg != nil && reg.Online(host) })) + reg = remote.NewRegistry(rtr, remote.Config{}) + if err := rtr.Add(base); err != nil { + return nil, nil, fmt.Errorf("add driver host: %w", err) + } + for host := range cfg.AgentTokens { + if err := reg.Preregister(host); err != nil { + return nil, nil, fmt.Errorf("add agent host %s: %w", host, err) + } + } + return rtr, reg, nil +} + +// placementSelector picks the host by the effective placement: kubernetes and process go to the configured +// driver when it is that kind, agent goes to the host named in the placement and must be online. +func placementSelector(base driver.Driver, online func(host string) bool) router.Selector { + return func(spec driver.StartSpec) (string, error) { + eff := spec.EffectiveOrV1() + switch eff.Driver { + case model.DriverAgent: + if eff.Host == "" { + return "", fmt.Errorf("%w: pool %s has no placement.host", router.ErrNoHost, spec.Pool.Name) + } + if !online(eff.Host) { + return "", fmt.Errorf("%w: agent host %q is not registered or offline", router.ErrNoHost, eff.Host) + } + return eff.Host, nil + case "", base.Name(): + return base.Host(), nil + default: + return "", fmt.Errorf("%w: this controller runs the %s driver, pool %s is placed on %s", + router.ErrNoHost, base.Name(), spec.Pool.Name, eff.Driver) + } + } +} diff --git a/cmd/grus/agents_test.go b/cmd/grus/agents_test.go new file mode 100644 index 0000000..ed67dcd --- /dev/null +++ b/cmd/grus/agents_test.go @@ -0,0 +1,85 @@ +package main + +import ( + "errors" + "strings" + "testing" + + "github.com/OneLiteFeatherNET/grus/internal/driver" + "github.com/OneLiteFeatherNET/grus/internal/driver/fake" + "github.com/OneLiteFeatherNET/grus/internal/driver/router" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +const hashA = "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3" + +func TestParseAgentTokensReadsHostHashPairs(t *testing.T) { + got, err := parseAgentTokens(" mc01=" + strings.ToUpper(hashA) + ", mc02=" + hashA + " ") + if err != nil { + t.Fatalf("parseAgentTokens: %v", err) + } + if len(got) != 2 || got["mc01"] != hashA || got["mc02"] != hashA { + t.Errorf("tokens = %v, want two hosts with the lower case hash", got) + } + if none, err := parseAgentTokens(""); err != nil || none != nil { + t.Errorf("empty list = %v, %v, want nil, nil", none, err) + } +} + +func TestParseAgentTokensRejectsMalformedEntriesWithoutEchoingTheValue(t *testing.T) { + for _, in := range []string{"mc01", "=" + hashA, "mc01=not-hex", "mc01=abcd", "a/b=" + hashA} { + _, err := parseAgentTokens(in) + if err == nil { + t.Errorf("parseAgentTokens(%q) returned nil error", in) + continue + } + if strings.Contains(err.Error(), "not-hex") { + t.Errorf("error %q echoes the token value", err) + } + } +} + +func agentSpec(driverName, host string) driver.StartSpec { + return driver.StartSpec{ + Pool: model.Pool{Name: "p"}, + Effective: model.EffectiveSpec{Driver: driverName, Host: host, Command: []string{"x"}}, + } +} + +func TestPlacementSelectorRoutesByEffectivePlacement(t *testing.T) { + base := fake.New("k8s-grus-dev") + online := map[string]bool{"mc01": true} + sel := placementSelector(base, func(h string) bool { return online[h] }) + + if host, err := sel(agentSpec("agent", "mc01")); err != nil || host != "mc01" { + t.Errorf("agent on an online host = %q, %v, want mc01", host, err) + } + if host, err := sel(agentSpec("fake", "")); err != nil || host != "k8s-grus-dev" { + t.Errorf("pool of the base driver = %q, %v, want the base host", host, err) + } + for name, spec := range map[string]driver.StartSpec{ + "offline agent": agentSpec("agent", "mc02"), + "agent without host": agentSpec("agent", ""), + "foreign driver": agentSpec("kubernetes", ""), + } { + if _, err := sel(spec); !errors.Is(err, router.ErrNoHost) { + t.Errorf("%s: err = %v, want router.ErrNoHost", name, err) + } + } +} + +func TestWithAgentsKnowsConfiguredHostsBeforeTheyConnect(t *testing.T) { + base := fake.New("local") + drv, reg, err := withAgents(base, config{AgentTokens: map[string]string{"mc01": hashA}}) + if err != nil { + t.Fatalf("withAgents: %v", err) + } + _, err = drv.List(t.Context()) + var partial *router.PartialListError + if !errors.As(err, &partial) || len(partial.Hosts) != 1 || partial.Hosts[0] != "mc01" { + t.Errorf("List err = %v, want mc01 unlisted while its agent is away", err) + } + if reg.Online("mc01") { + t.Error("mc01 online before any contact") + } +} diff --git a/cmd/grus/config.go b/cmd/grus/config.go index 3f1b48d..1ce697b 100644 --- a/cmd/grus/config.go +++ b/cmd/grus/config.go @@ -37,6 +37,7 @@ type config struct { DebugEndpoints bool HostID string AdminToken string + AgentTokens map[string]string // host -> hex SHA-256 of the agent token ProcessDir string ReconcileInterval time.Duration CRDs bool @@ -106,6 +107,9 @@ func loadConfig(args []string, getenv func(string) string) (config, error) { cfg.ImagePullSecrets = splitList(*pullSecrets) var err error + if cfg.AgentTokens, err = parseAgentTokens(getenv("GRUS_AGENT_TOKENS")); err != nil { + return config{}, err + } if cfg.NodeSelector, err = parseKeyValues("GRUS_NODE_SELECTOR", *nodeSelector); err != nil { return config{}, err } diff --git a/cmd/grus/controller.go b/cmd/grus/controller.go index 0864780..4c0657e 100644 --- a/cmd/grus/controller.go +++ b/cmd/grus/controller.go @@ -69,6 +69,11 @@ func newStack(ctx context.Context, cfg config, logger *slog.Logger) (*stack, err _ = st.Close() return nil, err } + drv, agents, err := withAgents(drv, cfg) + if err != nil { + _ = st.Close() + return nil, err + } hub := events.NewHub(strconv.FormatInt(time.Now().UnixMilli(), 10), eventRingSize, model.SystemClock{}, logger) ctrl := controller.New(controller.Config{ PublicURL: cfg.PublicURL, @@ -76,11 +81,14 @@ func newStack(ctx context.Context, cfg config, logger *slog.Logger) (*stack, err Interval: cfg.ReconcileInterval, Logger: logger, }, st, drv, tpl, hub) + agents.OnNewHost(ctrl.MarkAdoptHost) handler := api.New(api.Config{ AdminToken: cfg.AdminToken, DebugEndpoints: cfg.DebugEndpoints, Ready: ctrl.Ready, Version: version, + AgentTokens: cfg.AgentTokens, + Agents: agents, }, ctrl, tpl, hub.Handler(sseHeartbeat), logger) return &stack{store: st, tpl: tpl, drv: drv, hub: hub, ctrl: ctrl, handler: handler}, nil } diff --git a/deploy/agent/README.md b/deploy/agent/README.md new file mode 100644 index 0000000..b28cc26 --- /dev/null +++ b/deploy/agent/README.md @@ -0,0 +1,85 @@ +# Grus agent + +The agent runs Grus instances on a machine outside Kubernetes. It pulls its work from the controller over +HTTPS, so the machine needs no inbound path from the controller; proxies need to reach the instance ports. + +## What it does + +- Registers as a host and sends a heartbeat every 10 seconds. +- Long-polls `GET /v1/agents/{host}/desired`, starts missing instances as local processes, stops and kills on + request and delivers console lines. +- Reports its instances and their log tails to `PUT /v1/agents/{host}/observed` every 5 seconds and after changes. +- Downloads template archives with its agent token and extracts them into the instance directory. +- Gives every instance `GRUS_URL` (the controller URL the agent uses), `GRUS_TOKEN`, `GRUS_INSTANCE`, `GRUS_POOL`, + `GRUS_ROLE`, `GRUS_PORT`/`SERVER_PORT` and `GRUS_DIR`, plus the environment of the pool. Children never inherit + the agent's own environment except PATH, HOME, LANG, LC_ALL, TZ, JAVA_HOME and TMPDIR. +- Allocates one port per instance from `--port-range` and reports `
:`; `{{port}}` and `${GRUS_DIR}` + in command arguments are replaced. + +## Failure behaviour + +- Controller or gateway down: instances keep running; the agent retries with backoff (1 s up to 30 s) and + re-reports everything on reconnect. The controller keeps the state of the host until the agent is back. +- Controller restart: the agent re-reports its instances and the controller adopts them. +- Agent restart: **the instances of the agent are ended and started again** from the desired state (the agent + cannot re-attach to child processes). Leftover processes are found through `grus.pid` files and killed on start. +- SIGTERM to the agent does not stop instances unless `--stop-on-exit` is set; with it they are stopped + gracefully (stop command, SIGTERM, SIGKILL) before the agent exits. +- Dynamic instances lose their directory when they are removed; static ones keep it (worlds). + +## Install (system service) + +```sh +useradd --system --home /var/lib/grus-agent --create-home grus +install -m 0755 grus-agent /usr/local/bin/grus-agent +install -d -m 0750 -o grus /etc/grus-agent +# token: the plain secret; the controller only knows its SHA-256 +install -m 0600 -o grus /dev/stdin /etc/grus-agent/token <<< "" +cp deploy/agent/grus-agent.service /etc/systemd/system/ +systemctl daemon-reload && systemctl enable --now grus-agent +``` + +`/etc/grus-agent/agent.env`: + +```sh +GRUS_URL=https://grus-dev-api.apps.onelite.feather +GRUS_AGENT_TOKEN_FILE=/etc/grus-agent/token +GRUS_AGENT_HOST=mc01 +GRUS_AGENT_DIR=/var/lib/grus-agent/instances +GRUS_AGENT_ADDRESS=10.200.2.35 +GRUS_AGENT_PORT_RANGE=30000-30100 +GRUS_AGENT_JAVA=/home/cloud/.sdkman/candidates/java/25.0.3-tem/bin/java +# GRUS_AGENT_CA_FILE=/etc/grus-agent/ca.pem # only when the system CAs do not trust the gateway +# GRUS_AGENT_STOP_ON_EXIT=true +``` + +## Install without root (user unit) + +```sh +mkdir -p ~/grus-agent/bin ~/.config/grus-agent ~/.config/systemd/user +install -m 0755 grus-agent ~/grus-agent/bin/grus-agent +umask 077 && printf '%s' '' > ~/.config/grus-agent/token +cp deploy/agent/grus-agent.user.service ~/.config/systemd/user/grus-agent.service +# write ~/.config/grus-agent/agent.env as above, with GRUS_AGENT_TOKEN_FILE=$HOME/.config/grus-agent/token +loginctl enable-linger "$USER" +systemctl --user daemon-reload && systemctl --user enable --now grus-agent +journalctl --user -u grus-agent -f +``` + +## Controller side + +Generate a token and give the controller its hash: + +```sh +TOKEN=$(openssl rand -hex 32) +printf '%s' "$TOKEN" | sha256sum | cut -d' ' -f1 # the hash +# GRUS_AGENT_TOKENS=mc01=[,other=] +``` + +The gateway in front of the controller must forward `/v1/agents`, `/v1/self`, `/v1/templates` and `/healthz`. +Check with `GET /v1/hosts` (admin token): the host shows `online: true`. + +## Examples + +`examples/agent/` holds an environment `minestom-jar`, a pool `mc01-lobby` (jvm, templates) and a native pool +`mc01-stub` that runs `./grus-stub-server` from a template. diff --git a/deploy/agent/grus-agent.service b/deploy/agent/grus-agent.service new file mode 100644 index 0000000..91beb89 --- /dev/null +++ b/deploy/agent/grus-agent.service @@ -0,0 +1,26 @@ +# System unit for a dedicated user. Install as /etc/systemd/system/grus-agent.service. +# For a host without root, use the user unit variant at the bottom of deploy/agent/README.md. +[Unit] +Description=Grus agent +After=network-online.target +Wants=network-online.target + +[Service] +User=grus +Group=grus +WorkingDirectory=/var/lib/grus-agent +EnvironmentFile=/etc/grus-agent/agent.env +ExecStart=/usr/local/bin/grus-agent +Restart=always +RestartSec=5 +# Instances are children of the agent. The default KillMode (control-group) ends them when the unit stops, +# which is what you want for a restart: the agent cannot re-attach to them and starts them again from the +# controller's desired state. Use KillMode=process only together with GRUS_AGENT_STOP_ON_EXIT=false and +# accept that leftover instance processes are killed on the next start. +NoNewPrivileges=true +ProtectSystem=strict +ReadWritePaths=/var/lib/grus-agent +PrivateTmp=true + +[Install] +WantedBy=multi-user.target diff --git a/deploy/agent/grus-agent.user.service b/deploy/agent/grus-agent.user.service new file mode 100644 index 0000000..0566ecc --- /dev/null +++ b/deploy/agent/grus-agent.user.service @@ -0,0 +1,15 @@ +# User unit for hosts without root, e.g. ~/.config/systemd/user/grus-agent.service +# (run `loginctl enable-linger $USER` once so it survives logouts). +[Unit] +Description=Grus agent +After=network-online.target + +[Service] +EnvironmentFile=%h/.config/grus-agent/agent.env +WorkingDirectory=%h/grus-agent +ExecStart=%h/grus-agent/bin/grus-agent +Restart=always +RestartSec=5 + +[Install] +WantedBy=default.target diff --git a/examples/agent/environment-minestom-jar.json b/examples/agent/environment-minestom-jar.json new file mode 100644 index 0000000..73b8755 --- /dev/null +++ b/examples/agent/environment-minestom-jar.json @@ -0,0 +1,6 @@ +{ + "kind": "jvm", + "jvm": { "jar": "server.jar", "flags": ["-XX:+UseG1GC"] }, + "readiness": "self", + "stopCommand": "stop" +} diff --git a/examples/agent/pool-mc01-lobby.json b/examples/agent/pool-mc01-lobby.json new file mode 100644 index 0000000..61f773c --- /dev/null +++ b/examples/agent/pool-mc01-lobby.json @@ -0,0 +1,9 @@ +{ + "role": "game", + "mode": "dynamic", + "environment": "minestom-jar", + "placement": { "driver": "agent", "host": "mc01" }, + "templates": [{ "name": "minestom-lobby", "tag": "stable" }], + "resources": { "memoryMiB": 1024 }, + "scaling": { "min": 1, "max": 2, "buffer": 1, "capacity": 50 } +} diff --git a/examples/agent/pool-mc01-stub.json b/examples/agent/pool-mc01-stub.json new file mode 100644 index 0000000..bb2075d --- /dev/null +++ b/examples/agent/pool-mc01-stub.json @@ -0,0 +1,9 @@ +{ + "role": "game", + "mode": "dynamic", + "placement": { "driver": "agent", "host": "mc01" }, + "command": ["./grus-stub-server"], + "templates": [{ "name": "stub-native", "tag": "stable" }], + "resources": { "memoryMiB": 64 }, + "scaling": { "min": 1, "max": 2, "buffer": 0, "capacity": 20 } +} diff --git a/internal/agent/agent.go b/internal/agent/agent.go new file mode 100644 index 0000000..f3caf29 --- /dev/null +++ b/internal/agent/agent.go @@ -0,0 +1,491 @@ +package agent + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/driver" + "github.com/OneLiteFeatherNET/grus/internal/driver/remote" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +const ( + registerInterval = 10 * time.Second + reportInterval = 5 * time.Second + longPollWait = 25 * time.Second + maxBackoff = 30 * time.Second + logTail = 100 + stopWait = 60 * time.Second + killTimeout = 15 * time.Second + pidFile = "grus.pid" +) + +// API is the controller as the agent sees it. +type API interface { + Register(ctx context.Context, req remote.RegisterRequest) error + Desired(ctx context.Context, revision int64, wait time.Duration) (remote.Desired, error) + Observed(ctx context.Context, rep remote.ObservedReport) error +} + +// Runner runs the instances; *process.Driver implements it. +type Runner interface { + Start(ctx context.Context, spec driver.StartSpec) (string, error) + Stop(ctx context.Context, ref string, stopCommand string, grace time.Duration) error + Kill(ctx context.Context, ref string) error + List(ctx context.Context) ([]driver.Observed, error) + Logs(ctx context.Context, ref string, tail int, follow bool) (io.ReadCloser, error) + Command(ctx context.Context, ref string, line string) error + Forget(ref string) error + Pid(ref string) (int, bool) +} + +type failure struct { + inst remote.DesiredInstance + reason string +} + +// Agent applies the desired state of the controller to the local runner and reports what it observes. +// It is level based: every poll re-applies the whole desired state, so a lost message or a controller +// restart heals itself. Instances keep running while the controller is unreachable. +type Agent struct { + cfg Config + api API + run Runner + log *slog.Logger + // spawn runs a start in the background; tests run it inline. + spawn func(func()) + // baseCtx is the lifetime of background starts (template downloads), not of one poll. + baseCtx context.Context + + wake chan struct{} // asks the reporter for an immediate report + + mu sync.Mutex + rev int64 // desired revision applied last; -1 before the first poll + cmdSeq int64 // highest console command applied + starting map[string]remote.DesiredInstance + failed map[string]failure + stopped map[string]bool + known map[string]remote.DesiredInstance // last desired state per instance +} + +func New(ctx context.Context, cfg Config, api API, run Runner, log *slog.Logger) *Agent { + return &Agent{ + cfg: cfg, api: api, run: run, log: log, baseCtx: ctx, + spawn: func(f func()) { go f() }, + wake: make(chan struct{}, 1), + rev: -1, + starting: map[string]remote.DesiredInstance{}, + failed: map[string]failure{}, + stopped: map[string]bool{}, + known: map[string]remote.DesiredInstance{}, + } +} + +func (a *Agent) poke() { + select { + case a.wake <- struct{}{}: + default: + } +} + +// register sends the host description; it doubles as the heartbeat. +func (a *Agent) register(ctx context.Context) error { + return a.api.Register(ctx, remote.RegisterRequest{ + Version: a.cfg.Version, + Address: a.cfg.Address, + PortRange: fmt.Sprintf("%d-%d", a.cfg.PortMin, a.cfg.PortMax), + }) +} + +// poll fetches the desired state, waiting up to wait for a change, and applies it. +func (a *Agent) poll(ctx context.Context, wait time.Duration) error { + a.mu.Lock() + rev := a.rev + a.mu.Unlock() + d, err := a.api.Desired(ctx, rev, wait) + if err != nil { + return err + } + a.apply(ctx, d) + a.mu.Lock() + a.rev = d.Revision + a.mu.Unlock() + a.poke() + return nil +} + +// apply makes the local state match d: console commands, kills, stops and missing starts. +func (a *Agent) apply(ctx context.Context, d remote.Desired) { + listed := map[string]driver.Observed{} + if obs, err := a.run.List(ctx); err == nil { + for _, o := range obs { + listed[o.InstanceID] = o + } + } + + a.mu.Lock() + seq := a.cmdSeq + a.mu.Unlock() + for _, c := range d.Commands { + if c.Seq <= seq { + continue + } + if err := a.run.Command(ctx, c.Instance, c.Line); err != nil { + a.log.Warn("console command not delivered", "instance", c.Instance, "error", err) + } + seq = c.Seq + } + a.mu.Lock() + a.cmdSeq = seq + a.mu.Unlock() + + want := make(map[string]bool, len(d.Instances)) + for _, di := range d.Instances { + want[di.ID] = true + a.mu.Lock() + a.known[di.ID] = di + _, isStarting := a.starting[di.ID] + _, isFailed := a.failed[di.ID] + wasStopped := a.stopped[di.ID] + a.mu.Unlock() + o, present := listed[di.ID] + + switch { + case di.Kill: + a.kill(ctx, di, present) + case present || isStarting: + if di.Stop.Requested && present && o.Phase == driver.PhaseRunning && !wasStopped { + grace := time.Duration(di.Stop.GraceSeconds) * time.Second + if err := a.run.Stop(ctx, di.ID, di.Stop.Command, grace); err != nil { + a.log.Warn("stop failed", "instance", di.ID, "error", err) + } else { + a.mu.Lock() + a.stopped[di.ID] = true + a.mu.Unlock() + } + } + case isFailed || len(di.Effective.Command) == 0: + // A failed start stays reported until the controller kills it; entries without a command + // are instances the controller adopted from an earlier agent run. + default: + a.start(di) + } + } + + // Exited instances nobody asks for any more are cleaned up. Running ones are left alone: the + // controller adopts them from the report. + for id, o := range listed { + if !want[id] && o.Phase == driver.PhaseExited { + a.forget(id, o.Mode) + } + } + a.mu.Lock() + for id := range a.known { + if !want[id] { + delete(a.known, id) + delete(a.failed, id) + delete(a.stopped, id) + } + } + a.mu.Unlock() +} + +func (a *Agent) kill(ctx context.Context, di remote.DesiredInstance, present bool) { + if present { + kctx, cancel := context.WithTimeout(ctx, killTimeout) + err := a.run.Kill(kctx, di.ID) + cancel() + if err != nil && !errors.Is(err, driver.ErrNotFound) { + a.log.Warn("kill failed, retrying on the next poll", "instance", di.ID, "error", err) + return + } + a.forget(di.ID, di.Mode) + } + a.mu.Lock() + delete(a.failed, di.ID) + delete(a.stopped, di.ID) + a.mu.Unlock() +} + +// forget drops the runner's record of an exited instance and removes the working directory of dynamic ones. +func (a *Agent) forget(id string, mode model.Mode) { + if err := a.run.Forget(id); err != nil && !errors.Is(err, driver.ErrNotFound) { + a.log.Warn("forget failed", "instance", id, "error", err) + return + } + _ = os.Remove(filepath.Join(a.cfg.Dir, id, pidFile)) + if mode == model.ModeDynamic && id != "" && id != "." && id != ".." && filepath.Base(id) == id { + if err := os.RemoveAll(filepath.Join(a.cfg.Dir, id)); err != nil { + a.log.Warn("remove instance directory failed", "instance", id, "error", err) + } + } +} + +func (a *Agent) start(di remote.DesiredInstance) { + a.mu.Lock() + a.starting[di.ID] = di + a.mu.Unlock() + a.spawn(func() { + _, err := a.run.Start(a.baseCtx, a.startSpec(di)) + a.mu.Lock() + delete(a.starting, di.ID) + if err != nil { + a.failed[di.ID] = failure{inst: di, reason: err.Error()} + } + a.mu.Unlock() + if err != nil { + a.log.Error("start failed", "instance", di.ID, "pool", di.Pool, "error", err) + } else if pid, ok := a.run.Pid(di.ID); ok { + _ = os.WriteFile(filepath.Join(a.cfg.Dir, di.ID, pidFile), []byte(strconv.Itoa(pid)), 0o600) + } + a.poke() + }) +} + +// startSpec builds the driver spec: the controller's env, with GRUS_URL pointing at the URL this agent uses. +func (a *Agent) startSpec(di remote.DesiredInstance) driver.StartSpec { + env := make(map[string]string, len(di.Env)+5) + for k, v := range di.Effective.Env { + env[k] = v + } + for k, v := range di.Env { + env[k] = v + } + env["GRUS_URL"] = a.cfg.URL + env["GRUS_INSTANCE"] = di.ID + env["GRUS_POOL"] = di.Pool + env["GRUS_ROLE"] = string(di.Role) + refs := make([]driver.ResolvedTemplate, len(di.Templates)) + for i, t := range di.Templates { + refs[i] = driver.ResolvedTemplate{Name: t.Name, Digest: t.Digest} + } + return driver.StartSpec{ + Instance: model.Instance{ + ID: di.ID, Pool: di.Pool, Role: di.Role, PoolGeneration: di.Generation, TokenHash: di.TokenHash, + }, + Pool: model.Pool{Name: di.Pool, Spec: model.PoolSpec{ + Role: di.Role, Mode: di.Mode, Resources: model.Resources{MemoryMiB: di.MemoryMiB}, + }}, + Effective: di.Effective, + Token: di.Token, + Env: env, + Templates: refs, + } +} + +// report sends the full observed state: running instances, starts in progress, failed starts and log tails. +func (a *Agent) report(ctx context.Context) error { + obs, err := a.run.List(ctx) + if err != nil { + return fmt.Errorf("list instances: %w", err) + } + rep := remote.ObservedReport{Instances: []remote.ObservedInstance{}, Logs: map[string][]string{}} + seen := map[string]bool{} + for _, o := range obs { + seen[o.InstanceID] = true + rep.Instances = append(rep.Instances, remote.ObservedInstance{ + ID: o.InstanceID, Pool: o.Pool, Role: o.Role, Mode: o.Mode, Generation: o.PoolGeneration, + TokenHash: o.TokenHash, Address: o.Address, Phase: o.Phase, Reason: o.Reason, StartedAt: o.StartedAt, + }) + if lines := a.tail(ctx, o.Ref); len(lines) > 0 { + rep.Logs[o.InstanceID] = lines + } + } + a.mu.Lock() + rep.Revision, rep.CommandSeq = a.rev, a.cmdSeq + for id, di := range a.starting { + if !seen[id] { + rep.Instances = append(rep.Instances, observedOf(di, driver.PhasePending, "")) + } + } + for id, f := range a.failed { + if !seen[id] { + rep.Instances = append(rep.Instances, observedOf(f.inst, driver.PhaseFailed, f.reason)) + } + } + a.mu.Unlock() + if rep.Revision < 0 { + rep.Revision = 0 + } + return a.api.Observed(ctx, rep) +} + +func observedOf(di remote.DesiredInstance, phase driver.Phase, reason string) remote.ObservedInstance { + return remote.ObservedInstance{ + ID: di.ID, Pool: di.Pool, Role: di.Role, Mode: di.Mode, Generation: di.Generation, + TokenHash: di.TokenHash, Phase: phase, Reason: reason, + } +} + +func (a *Agent) tail(ctx context.Context, ref string) []string { + rc, err := a.run.Logs(ctx, ref, logTail, false) + if err != nil { + return nil + } + defer rc.Close() + raw, err := io.ReadAll(rc) + if err != nil || len(raw) == 0 { + return nil + } + return strings.Split(strings.TrimSuffix(string(raw), "\n"), "\n") +} + +// Run registers, polls and reports until ctx ends. Controller errors only delay the next attempt. +func (a *Agent) Run(ctx context.Context) { + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); a.every(ctx, registerInterval, "register", a.register) }() + go func() { defer wg.Done(); a.reportLoop(ctx) }() + a.pollLoop(ctx) + wg.Wait() +} + +func (a *Agent) pollLoop(ctx context.Context) { + backoff := time.Second + failing := false + for ctx.Err() == nil { + err := a.poll(ctx, longPollWait) + if err == nil { + if failing { + a.log.Info("controller reachable again") + failing = false + } + backoff = time.Second + continue + } + if ctx.Err() != nil { + return + } + if !failing { + a.log.Warn("controller not reachable, instances keep running", "error", err) + failing = true + } + select { + case <-ctx.Done(): + return + case <-time.After(backoff): + } + backoff = min(backoff*2, maxBackoff) + } +} + +func (a *Agent) reportLoop(ctx context.Context) { + every := a.cfg.ReportInterval + if every <= 0 { + every = reportInterval + } + ticker := time.NewTicker(every) + defer ticker.Stop() + failing := false + for { + if err := a.report(ctx); err != nil && ctx.Err() == nil { + if !failing { + a.log.Warn("report failed", "error", err) + } + failing = true + } else { + failing = false + } + select { + case <-ctx.Done(): + return + case <-ticker.C: + case <-a.wake: + } + } +} + +// every runs f now and then on every tick, logging a failure only when it starts. +func (a *Agent) every(ctx context.Context, interval time.Duration, what string, f func(context.Context) error) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + failing := false + for { + if err := f(ctx); err != nil && ctx.Err() == nil { + if !failing { + a.log.Warn(what+" failed", "error", err) + } + failing = true + } else { + failing = false + } + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} + +// StopAll asks every running instance to stop and waits until they are gone or stopWait passed. +func (a *Agent) StopAll(ctx context.Context) { + obs, err := a.run.List(ctx) + if err != nil { + return + } + for _, o := range obs { + if o.Phase != driver.PhaseRunning { + continue + } + a.mu.Lock() + di := a.known[o.InstanceID] + a.mu.Unlock() + grace := di.Effective.GracePeriod.D() + if err := a.run.Stop(ctx, o.Ref, di.Effective.StopCommand, grace); err != nil { + a.log.Warn("stop on exit failed", "instance", o.InstanceID, "error", err) + } + } + deadline := time.After(stopWait) + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + for { + running := 0 + if obs, err := a.run.List(ctx); err == nil { + for _, o := range obs { + if o.Phase == driver.PhaseRunning { + running++ + } + } + } + if running == 0 { + return + } + select { + case <-deadline: + return + case <-ticker.C: + } + } +} + +// NewClient returns the controller client of the agent host. +func NewClient(base, host, token string, httpClient *http.Client) *Client { + return &Client{base: base, host: host, token: token, http: httpClient} +} + +// Config is what the agent needs to run. +type Config struct { + URL string // controller URL the agent and its instances use + Token string // agent token + Host string + Dir string // instance working directory + Address string // IP advertised to proxies + PortMin int + PortMax int + Java string + CAFile string + StopOnExit bool + Version string + // ReportInterval is how often the agent reports without a change; zero means 5s. + ReportInterval time.Duration +} diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go new file mode 100644 index 0000000..551679b --- /dev/null +++ b/internal/agent/agent_test.go @@ -0,0 +1,353 @@ +package agent + +import ( + "context" + "errors" + "io" + "log/slog" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/driver" + "github.com/OneLiteFeatherNET/grus/internal/driver/remote" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +// fakeRunner is an in-memory runner that records what the agent asks for. +type fakeRunner struct { + mu sync.Mutex + procs map[string]*driver.Observed + started []driver.StartSpec + stopped []string + killed []string + forgot []string + commands []string + logs map[string][]string + startErr error +} + +func newFakeRunner() *fakeRunner { + return &fakeRunner{procs: map[string]*driver.Observed{}, logs: map[string][]string{}} +} + +func (r *fakeRunner) Start(_ context.Context, spec driver.StartSpec) (string, error) { + r.mu.Lock() + defer r.mu.Unlock() + if r.startErr != nil { + return "", r.startErr + } + id := spec.Instance.ID + r.started = append(r.started, spec) + r.procs[id] = &driver.Observed{Ref: id, InstanceID: id, Pool: spec.Instance.Pool, Role: spec.Instance.Role, + Mode: spec.Pool.Spec.Mode, TokenHash: spec.Instance.TokenHash, Phase: driver.PhaseRunning, Address: "10.0.0.1:30000"} + return id, nil +} + +func (r *fakeRunner) Stop(_ context.Context, ref, _ string, _ time.Duration) error { + r.mu.Lock() + defer r.mu.Unlock() + r.stopped = append(r.stopped, ref) + return nil +} + +func (r *fakeRunner) Kill(_ context.Context, ref string) error { + r.mu.Lock() + defer r.mu.Unlock() + p, ok := r.procs[ref] + if !ok { + return driver.ErrNotFound + } + p.Phase = driver.PhaseExited + r.killed = append(r.killed, ref) + return nil +} + +func (r *fakeRunner) List(context.Context) ([]driver.Observed, error) { + r.mu.Lock() + defer r.mu.Unlock() + var out []driver.Observed + for _, p := range r.procs { + out = append(out, *p) + } + return out, nil +} + +func (r *fakeRunner) Logs(_ context.Context, ref string, _ int, _ bool) (io.ReadCloser, error) { + r.mu.Lock() + defer r.mu.Unlock() + return io.NopCloser(strings.NewReader(strings.Join(r.logs[ref], "\n"))), nil +} + +func (r *fakeRunner) Command(_ context.Context, ref, line string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.commands = append(r.commands, ref+": "+line) + return nil +} + +func (r *fakeRunner) Forget(ref string) error { + r.mu.Lock() + defer r.mu.Unlock() + delete(r.procs, ref) + r.forgot = append(r.forgot, ref) + return nil +} + +func (r *fakeRunner) Pid(string) (int, bool) { return 0, false } + +// fakeAPI is a controller whose answers the test sets. +type fakeAPI struct { + desired remote.Desired + err error + reports []remote.ObservedReport + register []remote.RegisterRequest +} + +func (f *fakeAPI) Register(_ context.Context, req remote.RegisterRequest) error { + f.register = append(f.register, req) + return f.err +} + +func (f *fakeAPI) Desired(context.Context, int64, time.Duration) (remote.Desired, error) { + return f.desired, f.err +} + +func (f *fakeAPI) Observed(_ context.Context, rep remote.ObservedReport) error { + f.reports = append(f.reports, rep) + return f.err +} + +type rig struct { + t *testing.T + a *Agent + run *fakeRunner + api *fakeAPI + dir string +} + +func newRig(t *testing.T) *rig { + t.Helper() + dir := t.TempDir() + r := &rig{t: t, run: newFakeRunner(), api: &fakeAPI{}, dir: dir} + cfg := Config{URL: "https://grus.example", Token: "agent-secret", Host: "mc01", Dir: dir, Address: "10.200.2.35", PortMin: 30000, PortMax: 30100} + r.a = New(context.Background(), cfg, r.api, r.run, slog.New(slog.NewTextHandler(io.Discard, nil))) + r.a.spawn = func(f func()) { f() } + return r +} + +func desiredInstance(id string, mode model.Mode) remote.DesiredInstance { + return remote.DesiredInstance{ + ID: id, Pool: "lobby", Role: model.RoleGame, Mode: mode, Generation: 2, Token: "tok-" + id, TokenHash: "h-" + id, + Effective: model.EffectiveSpec{Driver: "agent", Command: []string{"./server"}, Env: map[string]string{"A": "pool"}}, + Env: map[string]string{"GRUS_URL": "http://cluster.internal:8080", "GRUS_MAX_PLAYERS": "20"}, + Templates: []remote.TemplateVersion{{Name: "base", Digest: "sha256:aa"}}, + MemoryMiB: 512, + } +} + +func (r *rig) poll(d remote.Desired) { + r.t.Helper() + r.api.desired = d + if err := r.a.poll(context.Background(), 0); err != nil { + r.t.Fatalf("poll: %v", err) + } +} + +func TestPollStartsMissingInstancesWithTheAgentsControllerURL(t *testing.T) { + r := newRig(t) + r.poll(remote.Desired{Revision: 7, Instances: []remote.DesiredInstance{desiredInstance("lobby-a", model.ModeDynamic)}}) + + if len(r.run.started) != 1 { + t.Fatalf("started %d instances, want 1", len(r.run.started)) + } + spec := r.run.started[0] + if spec.Token != "tok-lobby-a" || spec.Instance.TokenHash != "h-lobby-a" || spec.Templates[0].Digest != "sha256:aa" { + t.Errorf("spec token/hash/templates = %q %q %v", spec.Token, spec.Instance.TokenHash, spec.Templates) + } + want := map[string]string{ + "GRUS_URL": "https://grus.example", "GRUS_INSTANCE": "lobby-a", "GRUS_POOL": "lobby", "GRUS_ROLE": "game", + "A": "pool", "GRUS_MAX_PLAYERS": "20", + } + for k, v := range want { + if spec.Env[k] != v { + t.Errorf("env %s = %q, want %q", k, spec.Env[k], v) + } + } + if spec.Pool.Spec.Mode != model.ModeDynamic || spec.Pool.Spec.Resources.MemoryMiB != 512 { + t.Errorf("pool spec = %+v", spec.Pool.Spec) + } +} + +func TestRepeatedPollsDoNotStartAnInstanceTwice(t *testing.T) { + r := newRig(t) + d := remote.Desired{Revision: 1, Instances: []remote.DesiredInstance{desiredInstance("lobby-a", model.ModeDynamic)}} + r.poll(d) + r.poll(d) + if len(r.run.started) != 1 { + t.Errorf("started %d times, want 1", len(r.run.started)) + } +} + +func TestFailedStartIsReportedAsFailedAndNotRetried(t *testing.T) { + r := newRig(t) + r.run.startErr = errors.New("fetch templates: boom") + d := remote.Desired{Revision: 1, Instances: []remote.DesiredInstance{desiredInstance("lobby-a", model.ModeDynamic)}} + r.poll(d) + r.run.startErr = nil + r.poll(d) + + if len(r.run.started) != 0 { + t.Error("a failed start was retried") + } + if err := r.a.report(context.Background()); err != nil { + t.Fatalf("report: %v", err) + } + got := r.api.reports[0].Instances + if len(got) != 1 || got[0].Phase != driver.PhaseFailed || !strings.Contains(got[0].Reason, "boom") || got[0].TokenHash != "h-lobby-a" { + t.Errorf("reported instances = %+v, want one Failed with the reason", got) + } +} + +func TestReportCarriesRevisionInstancesAndLogTails(t *testing.T) { + r := newRig(t) + r.run.logs["lobby-a"] = []string{"one", "two"} + r.poll(remote.Desired{Revision: 9, Instances: []remote.DesiredInstance{desiredInstance("lobby-a", model.ModeDynamic)}}) + + if err := r.a.report(context.Background()); err != nil { + t.Fatalf("report: %v", err) + } + rep := r.api.reports[0] + if rep.Revision != 9 { + t.Errorf("report revision = %d, want the applied 9", rep.Revision) + } + if len(rep.Instances) != 1 || rep.Instances[0].Phase != driver.PhaseRunning || rep.Instances[0].Address != "10.0.0.1:30000" { + t.Errorf("instances = %+v", rep.Instances) + } + if got := rep.Logs["lobby-a"]; len(got) != 2 || got[1] != "two" { + t.Errorf("logs = %v", rep.Logs) + } +} + +func TestStopRequestIsForwardedOnce(t *testing.T) { + r := newRig(t) + di := desiredInstance("lobby-a", model.ModeDynamic) + r.poll(remote.Desired{Revision: 1, Instances: []remote.DesiredInstance{di}}) + di.Stop = remote.StopRequest{Requested: true, Command: "stop", GraceSeconds: 20} + r.poll(remote.Desired{Revision: 2, Instances: []remote.DesiredInstance{di}}) + r.poll(remote.Desired{Revision: 2, Instances: []remote.DesiredInstance{di}}) + + if len(r.run.stopped) != 1 || r.run.stopped[0] != "lobby-a" { + t.Errorf("stopped = %v, want one stop of lobby-a", r.run.stopped) + } +} + +func TestKillRemovesTheInstanceAndTheDirectoryOfDynamicOnes(t *testing.T) { + r := newRig(t) + for _, c := range []struct { + id string + mode model.Mode + keep bool + }{{"dyn-1", model.ModeDynamic, false}, {"static-1", model.ModeStatic, true}} { + di := desiredInstance(c.id, c.mode) + r.poll(remote.Desired{Revision: 1, Instances: []remote.DesiredInstance{di}}) + if err := os.MkdirAll(filepath.Join(r.dir, c.id), 0o755); err != nil { + t.Fatal(err) + } + di.Kill = true + r.poll(remote.Desired{Revision: 2, Instances: []remote.DesiredInstance{di}}) + + _, err := os.Stat(filepath.Join(r.dir, c.id)) + if kept := err == nil; kept != c.keep { + t.Errorf("%s: directory kept = %v, want %v", c.id, kept, c.keep) + } + } + if len(r.run.killed) != 2 || len(r.run.forgot) != 2 { + t.Errorf("killed %v forgot %v, want both instances", r.run.killed, r.run.forgot) + } +} + +func TestCommandsAreDeliveredOncePerSequenceNumber(t *testing.T) { + r := newRig(t) + d := remote.Desired{Revision: 1, Instances: []remote.DesiredInstance{desiredInstance("lobby-a", model.ModeDynamic)}, + Commands: []remote.Command{{Seq: 5, Instance: "lobby-a", Line: "say hi"}}} + r.poll(d) + r.poll(d) + if len(r.run.commands) != 1 || r.run.commands[0] != "lobby-a: say hi" { + t.Errorf("commands = %v, want one delivery", r.run.commands) + } + if err := r.a.report(context.Background()); err != nil { + t.Fatal(err) + } + if got := r.api.reports[0].CommandSeq; got != 5 { + t.Errorf("acknowledged command seq = %d, want 5", got) + } +} + +func TestAdoptedPlaceholdersWithoutACommandAreNeverStarted(t *testing.T) { + r := newRig(t) + r.poll(remote.Desired{Revision: 1, Instances: []remote.DesiredInstance{{ID: "old", Pool: "lobby"}}}) + if len(r.run.started) != 0 { + t.Errorf("started %d instances from a placeholder, want 0", len(r.run.started)) + } +} + +func TestRunningInstancesNobodyAsksForAreLeftAloneButExitedOnesAreForgotten(t *testing.T) { + r := newRig(t) + r.run.procs["running"] = &driver.Observed{Ref: "running", InstanceID: "running", Phase: driver.PhaseRunning} + r.run.procs["dead"] = &driver.Observed{Ref: "dead", InstanceID: "dead", Phase: driver.PhaseExited, Mode: model.ModeStatic} + r.poll(remote.Desired{Revision: 1}) + + if len(r.run.killed) != 0 || len(r.run.stopped) != 0 { + t.Errorf("agent stopped or killed an instance that is not desired: %v %v", r.run.stopped, r.run.killed) + } + if len(r.run.forgot) != 1 || r.run.forgot[0] != "dead" { + t.Errorf("forgot = %v, want [dead]", r.run.forgot) + } +} + +func TestControllerOutageLeavesInstancesUntouched(t *testing.T) { + r := newRig(t) + r.poll(remote.Desired{Revision: 1, Instances: []remote.DesiredInstance{desiredInstance("lobby-a", model.ModeDynamic)}}) + r.api.err = errors.New("connection refused") + + if err := r.a.poll(context.Background(), 0); err == nil { + t.Fatal("poll during an outage returned nil error") + } + if len(r.run.killed)+len(r.run.stopped) != 0 { + t.Error("the outage touched a running instance") + } + r.api.err = nil + if err := r.a.report(context.Background()); err != nil { + t.Fatalf("report after the outage: %v", err) + } + if got := r.api.reports[0].Instances; len(got) != 1 || got[0].ID != "lobby-a" { + t.Errorf("re-report after reconnect = %+v, want the running instance", got) + } +} + +func TestRegisterAnnouncesAddressAndPortRange(t *testing.T) { + r := newRig(t) + if err := r.a.register(context.Background()); err != nil { + t.Fatalf("register: %v", err) + } + got := r.api.register[0] + if got.Address != "10.200.2.35" || got.PortRange != "30000-30100" { + t.Errorf("register = %+v", got) + } +} + +func TestStopAllStopsRunningInstancesWithTheirStopCommand(t *testing.T) { + r := newRig(t) + di := desiredInstance("lobby-a", model.ModeDynamic) + r.poll(remote.Desired{Revision: 1, Instances: []remote.DesiredInstance{di}}) + r.run.procs["lobby-a"].Phase = driver.PhaseExited // the fake exits at once, so stopAll does not wait + + r.a.StopAll(context.Background()) + if len(r.run.stopped) != 0 { + t.Errorf("stopAll stopped %v, want nothing for an instance that already exited", r.run.stopped) + } +} diff --git a/internal/agent/client.go b/internal/agent/client.go new file mode 100644 index 0000000..fbffecd --- /dev/null +++ b/internal/agent/client.go @@ -0,0 +1,112 @@ +package agent + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strconv" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/driver/remote" +) + +const ( + requestTimeout = 15 * time.Second + errBodyLimit = 256 +) + +// Client talks to the controller's agent routes. It implements API. +type Client struct { + base string + host string + token string + http *http.Client +} + +var _ API = (*Client)(nil) + +// NewHTTPClient returns an HTTP client that trusts the system CAs plus the PEM file at caFile, if given. +// It has no overall timeout: every call carries its own context deadline, the long poll included. +func NewHTTPClient(caFile string) (*http.Client, error) { + transport := http.DefaultTransport.(*http.Transport).Clone() + if caFile != "" { + pem, err := os.ReadFile(caFile) + if err != nil { + return nil, fmt.Errorf("read CA file: %w", err) + } + pool, err := x509.SystemCertPool() + if err != nil || pool == nil { + pool = x509.NewCertPool() + } + if !pool.AppendCertsFromPEM(pem) { + return nil, fmt.Errorf("CA file %s holds no certificate", caFile) + } + transport.TLSClientConfig = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12} + } + return &http.Client{Transport: transport}, nil +} + +func (c *Client) path(suffix string) string { + return c.base + "/v1/agents/" + url.PathEscape(c.host) + suffix +} + +func (c *Client) Register(ctx context.Context, req remote.RegisterRequest) error { + return c.do(ctx, requestTimeout, http.MethodPut, c.path(""), req, nil) +} + +func (c *Client) Desired(ctx context.Context, revision int64, wait time.Duration) (remote.Desired, error) { + q := url.Values{"wait": {wait.String()}, "revision": {strconv.FormatInt(revision, 10)}} + var out remote.Desired + err := c.do(ctx, wait+requestTimeout, http.MethodGet, c.path("/desired")+"?"+q.Encode(), nil, &out) + return out, err +} + +func (c *Client) Observed(ctx context.Context, rep remote.ObservedReport) error { + return c.do(ctx, requestTimeout, http.MethodPut, c.path("/observed"), rep, nil) +} + +// do sends one JSON request. The token only travels in the Authorization header and never ends up in an error. +func (c *Client) do(ctx context.Context, timeout time.Duration, method, target string, in, out any) error { + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + var body io.Reader + if in != nil { + raw, err := json.Marshal(in) + if err != nil { + return err + } + body = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, method, target, body) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+c.token) + req.Header.Set("Accept", "application/json") + if in != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := c.http.Do(req) + if err != nil { + return fmt.Errorf("%s %s: %w", method, req.URL.Path, err) + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + snippet, _ := io.ReadAll(io.LimitReader(resp.Body, errBodyLimit)) + return fmt.Errorf("%s %s: HTTP %d: %s", method, req.URL.Path, resp.StatusCode, snippet) + } + if out == nil { + return nil + } + if err := json.NewDecoder(resp.Body).Decode(out); err != nil { + return fmt.Errorf("%s %s: decode response: %w", method, req.URL.Path, err) + } + return nil +} diff --git a/internal/agent/client_test.go b/internal/agent/client_test.go new file mode 100644 index 0000000..c0866ef --- /dev/null +++ b/internal/agent/client_test.go @@ -0,0 +1,72 @@ +package agent + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/driver/remote" +) + +func testClient(t *testing.T, h http.Handler) *Client { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + return &Client{base: srv.URL, host: "mc01", token: "agent-secret", http: srv.Client()} +} + +func TestClientSendsTheTokenAndTheRequestShapes(t *testing.T) { + var gotAuth, gotPath, gotQuery string + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth, gotPath, gotQuery = r.Header.Get("Authorization"), r.URL.Path, r.URL.RawQuery + _ = json.NewEncoder(w).Encode(remote.Desired{Revision: 4, Instances: []remote.DesiredInstance{{ID: "a"}}}) + })) + + d, err := c.Desired(context.Background(), 3, 25*time.Second) + if err != nil { + t.Fatalf("Desired: %v", err) + } + if gotAuth != "Bearer agent-secret" || gotPath != "/v1/agents/mc01/desired" { + t.Errorf("request = %q %q", gotAuth, gotPath) + } + if !strings.Contains(gotQuery, "revision=3") || !strings.Contains(gotQuery, "wait=25s") { + t.Errorf("query = %q", gotQuery) + } + if d.Revision != 4 || len(d.Instances) != 1 { + t.Errorf("desired = %+v", d) + } +} + +func TestClientErrorsNeverContainTheToken(t *testing.T) { + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "nope", http.StatusForbidden) + })) + err := c.Register(context.Background(), remote.RegisterRequest{}) + if err == nil || !strings.Contains(err.Error(), "403") { + t.Fatalf("Register err = %v, want an HTTP 403 error", err) + } + if strings.Contains(err.Error(), "agent-secret") { + t.Errorf("error %q leaks the token", err) + } +} + +func TestClientPutsTheObservedReport(t *testing.T) { + var got remote.ObservedReport + var method string + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + method = r.Method + _ = json.NewDecoder(r.Body).Decode(&got) + w.WriteHeader(http.StatusNoContent) + })) + rep := remote.ObservedReport{Revision: 2, Instances: []remote.ObservedInstance{{ID: "a", Phase: "Running"}}} + if err := c.Observed(context.Background(), rep); err != nil { + t.Fatalf("Observed: %v", err) + } + if method != http.MethodPut || got.Revision != 2 || got.Instances[0].ID != "a" { + t.Errorf("method %s body %+v", method, got) + } +} diff --git a/internal/agent/orphans.go b/internal/agent/orphans.go new file mode 100644 index 0000000..e831ea6 --- /dev/null +++ b/internal/agent/orphans.go @@ -0,0 +1,52 @@ +package agent + +import ( + "bytes" + "log/slog" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" +) + +// KillOrphans kills instances of an earlier agent run. The agent cannot re-attach to them (stdin, console +// and exit status are gone), so it ends them and lets the controller's desired state start them again. +// A pid file counts only when the process still carries GRUS_INSTANCE= in its environment, so a reused +// pid is never killed by mistake. +func KillOrphans(dir string, log *slog.Logger) int { + entries, err := os.ReadDir(dir) + if err != nil { + return 0 + } + killed := 0 + for _, e := range entries { + if !e.IsDir() { + continue + } + path := filepath.Join(dir, e.Name(), pidFile) + raw, err := os.ReadFile(path) + if err != nil { + continue + } + _ = os.Remove(path) + pid, err := strconv.Atoi(strings.TrimSpace(string(raw))) + if err != nil || pid <= 1 || !carriesInstance(pid, e.Name()) { + continue + } + if err := syscall.Kill(-pid, syscall.SIGKILL); err != nil { + _ = syscall.Kill(pid, syscall.SIGKILL) + } + log.Info("killed instance process left over from an earlier agent run", "instance", e.Name(), "pid", pid) + killed++ + } + return killed +} + +func carriesInstance(pid int, id string) bool { + env, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/environ") + if err != nil { + return false + } + return bytes.Contains(append([]byte{0}, env...), []byte("\x00GRUS_INSTANCE="+id+"\x00")) +} diff --git a/internal/agent/orphans_test.go b/internal/agent/orphans_test.go new file mode 100644 index 0000000..39294c3 --- /dev/null +++ b/internal/agent/orphans_test.go @@ -0,0 +1,50 @@ +package agent + +import ( + "io" + "log/slog" + "os" + "os/exec" + "path/filepath" + "strconv" + "syscall" + "testing" +) + +func startOrphan(t *testing.T, dir, id, envInstance string) *exec.Cmd { + t.Helper() + cmd := exec.Command("sleep", "60") + cmd.Env = []string{"GRUS_INSTANCE=" + envInstance} + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if err := cmd.Start(); err != nil { + t.Fatalf("start sleep: %v", err) + } + t.Cleanup(func() { _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); _ = cmd.Wait() }) + if err := os.MkdirAll(filepath.Join(dir, id), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, id, pidFile), []byte(strconv.Itoa(cmd.Process.Pid)), 0o600); err != nil { + t.Fatal(err) + } + return cmd +} + +func TestKillOrphansEndsProcessesOfAnEarlierRunOnly(t *testing.T) { + dir := t.TempDir() + mine := startOrphan(t, dir, "lobby-a", "lobby-a") + reused := startOrphan(t, dir, "lobby-b", "someone-else") // pid file points at an unrelated process + + n := KillOrphans(dir, slog.New(slog.NewTextHandler(io.Discard, nil))) + if n != 1 { + t.Errorf("killed %d processes, want 1", n) + } + if err := mine.Wait(); err == nil { + t.Error("the instance process survived KillOrphans") + } + if err := reused.Process.Signal(syscall.Signal(0)); err != nil { + t.Errorf("an unrelated process was killed: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, "lobby-a", pidFile)); err == nil { + t.Error("pid file was not removed") + } +} diff --git a/internal/api/agents.go b/internal/api/agents.go new file mode 100644 index 0000000..760dfe7 --- /dev/null +++ b/internal/api/agents.go @@ -0,0 +1,131 @@ +package api + +import ( + "context" + "errors" + "net/http" + "time" + + "github.com/danielgtaylor/huma/v2" + + "github.com/OneLiteFeatherNET/grus/internal/driver/remote" +) + +// Agents is what the agent and host routes need from the remote hosts. *remote.Registry implements it. +type Agents interface { + Register(ctx context.Context, host string, req remote.RegisterRequest) (remote.HostInfo, error) + Desired(ctx context.Context, host string, revision int64, wait time.Duration) (remote.Desired, error) + Observed(ctx context.Context, host string, rep remote.ObservedReport) error + Hosts() []remote.HostInfo + Host(name string) (remote.HostInfo, error) +} + +type registerInput struct { + Host string `path:"host" pattern:"^[a-z0-9][a-z0-9._-]{0,62}$" doc:"Agent host name"` + Body remote.RegisterRequest +} + +type hostOutput struct { + Body remote.HostInfo +} + +type hostsOutput struct { + Body []remote.HostInfo +} + +type desiredInput struct { + Host string `path:"host" pattern:"^[a-z0-9][a-z0-9._-]{0,62}$" doc:"Agent host name"` + Wait string `query:"wait" default:"25s" doc:"How long the request may wait for a change, as a duration (max 60s)"` + Revision int64 `query:"revision" default:"-1" doc:"Revision the agent already has; the call returns at once when it differs"` +} + +type desiredOutput struct { + Body remote.Desired +} + +type observedInput struct { + Host string `path:"host" pattern:"^[a-z0-9][a-z0-9._-]{0,62}$" doc:"Agent host name"` + Body remote.ObservedReport +} + +type hostNameInput struct { + Name string `path:"name" doc:"Host name"` +} + +func (s *server) registerAgents(api huma.API) { + huma.Register(api, operation(scopeAgent, huma.Operation{ + OperationID: "register-agent", Method: http.MethodPut, Path: "/v1/agents/{host}", + Summary: "Register an agent host or send its heartbeat", + }), func(ctx context.Context, in *registerInput) (*hostOutput, error) { + if s.cfg.Agents == nil { + return nil, huma.Error404NotFound("agents are not enabled") + } + info, err := s.cfg.Agents.Register(ctx, in.Host, in.Body) + if err != nil { + return nil, mapError(s.log, err) + } + return &hostOutput{Body: info}, nil + }) + + huma.Register(api, operation(scopeAgent, huma.Operation{ + OperationID: "get-agent-desired", Method: http.MethodGet, Path: "/v1/agents/{host}/desired", + Summary: "Long-poll the desired state of an agent host", + }), func(ctx context.Context, in *desiredInput) (*desiredOutput, error) { + if s.cfg.Agents == nil { + return nil, huma.Error404NotFound("agents are not enabled") + } + wait, err := time.ParseDuration(in.Wait) + if err != nil || wait < 0 { + return nil, huma.Error422UnprocessableEntity("wait must be a duration like 25s") + } + desired, err := s.cfg.Agents.Desired(ctx, in.Host, in.Revision, wait) + if err != nil { + return nil, mapError(s.log, err) + } + return &desiredOutput{Body: desired}, nil + }) + + huma.Register(api, operation(scopeAgent, huma.Operation{ + OperationID: "put-agent-observed", Method: http.MethodPut, Path: "/v1/agents/{host}/observed", + Summary: "Report the instances an agent host runs", DefaultStatus: http.StatusNoContent, + }), func(ctx context.Context, in *observedInput) (*struct{}, error) { + if s.cfg.Agents == nil { + return nil, huma.Error404NotFound("agents are not enabled") + } + if err := s.cfg.Agents.Observed(ctx, in.Host, in.Body); err != nil { + return nil, mapError(s.log, err) + } + return nil, nil + }) + + huma.Register(api, operation(scopeHostsRead, huma.Operation{ + OperationID: "list-hosts", Method: http.MethodGet, Path: "/v1/hosts", + Summary: "List agent hosts", + }), func(_ context.Context, _ *struct{}) (*hostsOutput, error) { + if s.cfg.Agents == nil { + return &hostsOutput{Body: []remote.HostInfo{}}, nil + } + hosts := s.cfg.Agents.Hosts() + if hosts == nil { + hosts = []remote.HostInfo{} + } + return &hostsOutput{Body: hosts}, nil + }) + + huma.Register(api, operation(scopeHostsRead, huma.Operation{ + OperationID: "get-host", Method: http.MethodGet, Path: "/v1/hosts/{name}", + Summary: "Get an agent host", + }), func(_ context.Context, in *hostNameInput) (*hostOutput, error) { + if s.cfg.Agents == nil { + return nil, huma.Error404NotFound("not found") + } + info, err := s.cfg.Agents.Host(in.Name) + if errors.Is(err, remote.ErrUnknownHost) { + return nil, huma.Error404NotFound("not found") + } + if err != nil { + return nil, mapError(s.log, err) + } + return &hostOutput{Body: info}, nil + }) +} diff --git a/internal/api/agents_test.go b/internal/api/agents_test.go new file mode 100644 index 0000000..692a86c --- /dev/null +++ b/internal/api/agents_test.go @@ -0,0 +1,138 @@ +package api + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/OneLiteFeatherNET/grus/internal/driver/remote" + "github.com/OneLiteFeatherNET/grus/internal/driver/router" +) + +const agentToken = "mc01-agent-token-secret" + +func hashOf(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +func agentFixture(t *testing.T) fixture { + t.Helper() + reg := remote.NewRegistry(router.New(nil), remote.Config{}) + return newFixture(t, Config{ + AgentTokens: map[string]string{"mc01": hashOf(agentToken), "other": hashOf("other-agent-token")}, + Agents: reg, + }, nil) +} + +func TestAgentRegistersItsOwnHostAndAdminSeesIt(t *testing.T) { + fx := agentFixture(t) + body := `{"version":"0.1.0","address":"10.200.2.35","portRange":"30000-30100","capacity":{"memoryMiB":8192}}` + + rec := fx.call(t, http.MethodPut, "/v1/agents/mc01", agentToken, "application/json", body) + if rec.Code != http.StatusOK { + t.Fatalf("register status = %d, want 200; body %s", rec.Code, rec.Body) + } + + rec = fx.call(t, http.MethodGet, "/v1/hosts/mc01", adminToken, "", "") + if rec.Code != http.StatusOK { + t.Fatalf("get host status = %d, want 200; body %s", rec.Code, rec.Body) + } + var info remote.HostInfo + if err := json.Unmarshal(rec.Body.Bytes(), &info); err != nil { + t.Fatalf("decode host: %v", err) + } + if !info.Online || info.Address != "10.200.2.35" || info.Capacity.MemoryMiB != 8192 || info.Version != "0.1.0" { + t.Errorf("host = %+v", info) + } + rec = fx.call(t, http.MethodGet, "/v1/hosts", adminToken, "", "") + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"mc01"`) { + t.Errorf("list hosts = %d %s", rec.Code, rec.Body) + } +} + +func TestAgentTokenCannotUseAnotherHostsRoutes(t *testing.T) { + fx := agentFixture(t) + for _, target := range []string{"/v1/agents/other", "/v1/agents/other/desired?wait=0s", "/v1/agents/other/observed"} { + method, body := http.MethodGet, "" + if !strings.Contains(target, "desired") { + method, body = http.MethodPut, `{"instances":[]}` + } + rec := fx.call(t, method, target, agentToken, "application/json", body) + if rec.Code != http.StatusForbidden { + t.Errorf("%s %s with the mc01 token = %d, want 403", method, target, rec.Code) + } + } +} + +func TestAgentTokenHasNoOtherScopes(t *testing.T) { + fx := agentFixture(t) + for _, c := range []struct{ method, target string }{ + {http.MethodGet, "/v1/pools"}, + {http.MethodGet, "/v1/instances"}, + {http.MethodGet, "/v1/hosts"}, + {http.MethodGet, "/v1/templates"}, + } { + if rec := fx.call(t, c.method, c.target, agentToken, "", ""); rec.Code != http.StatusForbidden { + t.Errorf("%s %s with an agent token = %d, want 403", c.method, c.target, rec.Code) + } + } +} + +func TestAgentTokenMayDownloadTemplateArchives(t *testing.T) { + fx := agentFixture(t) + digest := fx.tpl.addArchive(t, "content") + rec := fx.call(t, http.MethodGet, "/v1/templates/base/versions/"+digest+"/archive", agentToken, "", "") + if rec.Code != http.StatusOK { + t.Errorf("archive status = %d, want 200", rec.Code) + } +} + +func TestWrongAgentTokenReturns401(t *testing.T) { + fx := agentFixture(t) + if rec := fx.call(t, http.MethodPut, "/v1/agents/mc01", "not-the-token", "application/json", `{}`); rec.Code != http.StatusUnauthorized { + t.Errorf("status = %d, want 401", rec.Code) + } +} + +func TestDesiredReturnsAtOnceForAStaleRevisionAndPutObservedAnswers204(t *testing.T) { + fx := agentFixture(t) + rec := fx.call(t, http.MethodGet, "/v1/agents/mc01/desired?wait=0s&revision=-1", agentToken, "", "") + if rec.Code != http.StatusOK { + t.Fatalf("desired status = %d, want 200; body %s", rec.Code, rec.Body) + } + var d remote.Desired + if err := json.Unmarshal(rec.Body.Bytes(), &d); err != nil { + t.Fatalf("decode desired: %v", err) + } + if d.Instances == nil || d.Commands == nil { + t.Errorf("desired = %+v, want empty lists and not null", d) + } + + rec = fx.call(t, http.MethodPut, "/v1/agents/mc01/observed", agentToken, "application/json", + `{"revision":1,"instances":[{"id":"stub-1","phase":"Running","address":"10.200.2.35:30000"}],"logs":{"stub-1":["hi"]}}`) + if rec.Code != http.StatusNoContent { + t.Fatalf("observed status = %d, want 204; body %s", rec.Code, rec.Body) + } + rec = fx.call(t, http.MethodGet, "/v1/hosts/mc01", adminToken, "", "") + if !strings.Contains(rec.Body.String(), `"instances":1`) { + t.Errorf("host after report = %s, want one instance", rec.Body) + } +} + +func TestInvalidWaitIsRejected(t *testing.T) { + fx := agentFixture(t) + if rec := fx.call(t, http.MethodGet, "/v1/agents/mc01/desired?wait=soon", agentToken, "", ""); rec.Code != http.StatusUnprocessableEntity { + t.Errorf("status = %d, want 422", rec.Code) + } +} + +func TestUnknownHostIs404(t *testing.T) { + fx := agentFixture(t) + if rec := fx.call(t, http.MethodGet, "/v1/hosts/nope", adminToken, "", ""); rec.Code != http.StatusNotFound { + t.Errorf("status = %d, want 404", rec.Code) + } +} diff --git a/internal/api/api.go b/internal/api/api.go index 6a611d2..d3d8291 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -24,6 +24,10 @@ type Config struct { DebugEndpoints bool // registers the admin-only debug routes Ready func() bool Version string + // AgentTokens maps an agent host to the hex SHA-256 of its token. Empty disables agent tokens. + AgentTokens map[string]string + // Agents serves the /v1/agents and /v1/hosts routes. Nil answers them with 404. + Agents Agents } const ( @@ -79,7 +83,7 @@ func newServer(cfg Config, svc controller.Service, tpl templates.Store, events h tpl: tpl, events: events, log: logger, - auth: newAuthenticator(cfg.AdminToken, svc, logger), + auth: newAuthenticator(cfg.AdminToken, cfg.AgentTokens, svc, logger), } } @@ -100,6 +104,7 @@ func build(mux *http.ServeMux, s *server, version string) huma.API { s.registerInstances(api) s.registerSelf(api) s.registerTemplates(api) + s.registerAgents(api) if s.cfg.DebugEndpoints { s.registerDebug(api) } diff --git a/internal/api/auth.go b/internal/api/auth.go index 6b8fa46..fef93ae 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -4,6 +4,7 @@ import ( "context" "crypto/sha256" "crypto/subtle" + "encoding/hex" "errors" "log/slog" "net/http" @@ -31,6 +32,12 @@ const ( scopeEventsRead = "events:read" scopeTemplatesRead = "templates:read" scopeTemplatesWrite = "templates:write" + // scopeTemplatesArchive covers downloading one template version; instances and agents have it. + scopeTemplatesArchive = "templates:archive" + // scopeAgent covers the /v1/agents/{host} routes; an agent principal is bound to its own host. + scopeAgent = "agent" + // scopeHostsRead covers GET /v1/hosts; only the admin token has it. + scopeHostsRead = "hosts:read" ) // metaScope is the huma Operation.Metadata key holding the scope an operation requires. @@ -40,6 +47,7 @@ const metaScope = "grus.scope" type principal struct { admin bool instanceID string + agentHost string // set for agent tokens: the only host whose paths the principal may use scopes map[string]bool } @@ -61,6 +69,8 @@ func instancePrincipal(inst model.Instance) principal { scopeInstancesRead: true, scopePlayersConnect: true, scopeTemplatesRead: true, + + scopeTemplatesArchive: true, } if inst.Role == model.RoleProxy { scopes[scopeEventsRead] = true @@ -70,6 +80,11 @@ func instancePrincipal(inst model.Instance) principal { return principal{instanceID: inst.ID, scopes: scopes} } +// agentPrincipal is the principal of an agent token: its own host routes and template downloads. +func agentPrincipal(host string) principal { + return principal{agentHost: host, scopes: map[string]bool{scopeAgent: true, scopeTemplatesArchive: true}} +} + type principalKey struct{} func withPrincipal(ctx context.Context, p principal) context.Context { @@ -89,12 +104,19 @@ type authenticator struct { // adminDigest is the SHA-256 of the admin token; hashing first makes the comparison length independent. adminDigest [sha256.Size]byte adminSet bool - svc controller.Service - log *slog.Logger + // agents maps a host to the SHA-256 of its agent token. + agents map[string][sha256.Size]byte + svc controller.Service + log *slog.Logger } -func newAuthenticator(adminToken string, svc controller.Service, logger *slog.Logger) *authenticator { - a := &authenticator{svc: svc, log: logger} +func newAuthenticator(adminToken string, agentTokens map[string]string, svc controller.Service, logger *slog.Logger) *authenticator { + a := &authenticator{svc: svc, log: logger, agents: make(map[string][sha256.Size]byte, len(agentTokens))} + for host, hexHash := range agentTokens { + if raw, err := hex.DecodeString(hexHash); err == nil && len(raw) == sha256.Size { + a.agents[host] = [sha256.Size]byte(raw) + } + } if adminToken != "" { a.adminDigest = sha256.Sum256([]byte(adminToken)) a.adminSet = true @@ -118,6 +140,19 @@ func (a *authenticator) authenticate(ctx context.Context, header string) (princi return adminPrincipal, nil } } + if len(a.agents) > 0 { + digest := sha256.Sum256([]byte(token)) + matched := "" + for host, want := range a.agents { + // Every host is compared so the time does not tell which host matched. + if subtle.ConstantTimeCompare(digest[:], want[:]) == 1 { + matched = host + } + } + if matched != "" { + return agentPrincipal(matched), nil + } + } inst, err := a.svc.AuthenticateInstance(ctx, token) if err != nil { if !errors.Is(err, controller.ErrNotFound) && !errors.Is(err, store.ErrNotFound) { @@ -142,6 +177,10 @@ func (a *authenticator) middleware(api huma.API) func(huma.Context, func(huma.Co _ = huma.WriteErr(api, ctx, http.StatusForbidden, "token lacks scope "+scope) return } + if host := ctx.Param("host"); host != "" && p.agentHost != "" && host != p.agentHost { + _ = huma.WriteErr(api, ctx, http.StatusForbidden, "token is bound to another host") + return + } next(huma.WithContext(ctx, withPrincipal(ctx.Context(), p))) } } diff --git a/internal/api/templates.go b/internal/api/templates.go index ef41f57..7fe271a 100644 --- a/internal/api/templates.go +++ b/internal/api/templates.go @@ -56,7 +56,7 @@ func (s *server) registerTemplates(api huma.API) { return nil, nil }) - huma.Register(api, operation(scopeTemplatesRead, huma.Operation{ + huma.Register(api, operation(scopeTemplatesArchive, huma.Operation{ OperationID: "get-template-archive", Method: http.MethodGet, Path: "/v1/templates/{name}/versions/{digest}/archive", Summary: "Download a template version as tar.gz", diff --git a/internal/controller/controller.go b/internal/controller/controller.go index bdd0171..bc9de98 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -9,6 +9,7 @@ import ( "fmt" "log/slog" "math/big" + "strings" "sync" "sync/atomic" "time" @@ -59,6 +60,7 @@ type Controller struct { lastPublished map[string]time.Time // per instance: last instance.updated from SelfStatus resolveWarned map[string]string // per pool: last unresolvable reason already reported lastNetwork model.NetworkStatus // last network.players payload + adoptHosts map[string]bool // hosts whose unknown instances are adopted once they can be listed } // New builds a controller. Call Adopt (or Run, which adopts first) before reconciling. @@ -90,6 +92,7 @@ func New(cfg Config, st store.Store, drv driver.Driver, tpl templates.Store, pub belowSince: make(map[string]*time.Time), lastPublished: make(map[string]time.Time), resolveWarned: make(map[string]string), + adoptHosts: make(map[string]bool), } } @@ -126,15 +129,43 @@ func (c *Controller) Trigger() { func (c *Controller) Ready() bool { return c.ready.Load() } // Adopt creates store records for driver instances that have none, so a restart takes over running -// instances instead of stopping them. Nothing is stopped here. +// instances instead of stopping them. Nothing is stopped here. Hosts that cannot be listed yet (agents that +// have not reconnected) do not block readiness: their instances are adopted by the reconcile loop as soon +// as the host can be listed. func (c *Controller) Adopt(ctx context.Context) error { c.mu.Lock() defer c.mu.Unlock() observed, err := c.drv.List(ctx) if err != nil { - return fmt.Errorf("list driver instances: %w", err) + var partial unlistedHostsError + if !errors.As(err, &partial) { + return fmt.Errorf("list driver instances: %w", err) + } + for _, host := range partial.FailedHosts() { + c.adoptHosts[host] = true + } + c.log.Warn("some hosts cannot be listed yet, adopting their instances later", "hosts", partial.FailedHosts()) + } + adopted, err := c.adoptObserved(ctx, observed) + if err != nil { + return err } + c.ready.Store(true) + c.log.Info("adopted instances", "count", adopted) + return nil +} + +// MarkAdoptHost makes the reconcile loop adopt the unknown instances of host once it can be listed. It is +// meant for hosts that appear at runtime, such as an agent that registers for the first time. +func (c *Controller) MarkAdoptHost(host string) { + c.mu.Lock() + defer c.mu.Unlock() + c.adoptHosts[host] = true +} + +// adoptObserved creates records for the observed instances that have none and returns how many it created. +func (c *Controller) adoptObserved(ctx context.Context, observed []driver.Observed) (int, error) { now := c.clock.Now() adopted := 0 for _, o := range observed { @@ -146,7 +177,7 @@ func (c *Controller) Adopt(ctx context.Context) error { continue } if !errors.Is(err, store.ErrNotFound) { - return fmt.Errorf("load instance %s: %w", o.InstanceID, err) + return adopted, fmt.Errorf("load instance %s: %w", o.InstanceID, err) } created := o.StartedAt if created.IsZero() { @@ -157,7 +188,7 @@ func (c *Controller) Adopt(ctx context.Context) error { Pool: o.Pool, Role: o.Role, PoolGeneration: o.PoolGeneration, - Host: c.drv.Host(), + Host: hostOfRef(o.Ref, c.drv.Host()), DriverRef: o.Ref, Address: o.Address, StateSince: now, @@ -178,16 +209,52 @@ func (c *Controller) Adopt(ctx context.Context) error { } } if err := c.st.CreateInstance(ctx, inst); err != nil { - return fmt.Errorf("adopt instance %s: %w", inst.ID, err) + return adopted, fmt.Errorf("adopt instance %s: %w", inst.ID, err) } c.pub.Publish(model.EventInstanceCreated, inst) adopted++ } - c.ready.Store(true) - c.log.Info("adopted instances", "count", adopted) + return adopted, nil +} + +// adoptLater adopts the unknown instances of the marked hosts that can be listed now. +func (c *Controller) adoptLater(ctx context.Context, observed []driver.Observed, unlisted map[string]bool) error { + var due []driver.Observed + ready := map[string]bool{} + for host := range c.adoptHosts { + if !unlisted[host] { + ready[host] = true + } + } + if len(ready) == 0 { + return nil + } + for _, o := range observed { + if ready[hostOfRef(o.Ref, "")] { + due = append(due, o) + } + } + n, err := c.adoptObserved(ctx, due) + if err != nil { + return err + } + for host := range ready { + delete(c.adoptHosts, host) + } + if n > 0 { + c.log.Info("adopted instances of reconnected hosts", "count", n) + } return nil } +// hostOfRef returns the host part of a router ref "/", or fallback for plain refs. +func hostOfRef(ref, fallback string) string { + if host, _, ok := strings.Cut(ref, "/"); ok { + return host + } + return fallback +} + // apply runs one lifecycle input. When the state changes it persists the instance and publishes // instance.state. Callers that changed other fields must persist them themselves when the state stays. func (c *Controller) apply(ctx context.Context, inst model.Instance, in state.Input, reason string) (model.Instance, error) { @@ -318,6 +385,7 @@ func (c *Controller) createInstance(ctx context.Context, pool model.Pool) (model return c.apply(ctx, inst, state.InFailed, "start: "+err.Error()) } inst.DriverRef = ref + inst.Host = hostOfRef(ref, inst.Host) return c.apply(ctx, inst, state.InPreparing, "") } diff --git a/internal/controller/controller_test.go b/internal/controller/controller_test.go index d49777b..ac48864 100644 --- a/internal/controller/controller_test.go +++ b/internal/controller/controller_test.go @@ -603,3 +603,69 @@ func startedIDs(specs []driver.StartSpec) []string { } return ids } + +// routerFixture runs the controller over a router with a reachable host and an agent host that cannot be +// listed yet. +func routerFixture(t *testing.T) (f *fixture, up, agent *fake.Driver) { + t.Helper() + f = newFixture(t, Config{}) + up, agent = fake.New("host-up"), fake.New("agent-host") + agent.ListErr = errors.New("agent offline") + rtr := router.New(func(driver.StartSpec) (string, error) { return "host-up", nil }) + for _, d := range []driver.Driver{up, agent} { + if err := rtr.Add(d); err != nil { + t.Fatalf("add host %s: %v", d.Host(), err) + } + } + f.c = New(f.c.cfg, f.st, rtr, nil, f.pub) + return f, up, agent +} + +func TestAdoptToleratesAnOfflineHostAndAdoptsTheOthers(t *testing.T) { + f, up, _ := routerFixture(t) + up.Add(driver.Observed{InstanceID: "lobby-a", Pool: "lobby", Role: model.RoleGame, Phase: driver.PhaseRunning}) + + if err := f.c.Adopt(f.ctx); err != nil { + t.Fatalf("Adopt with an offline host: %v", err) + } + if !f.c.Ready() { + t.Error("Ready() = false: an offline agent host must not block readiness") + } + got := f.get("lobby-a") + if got.Host != "host-up" || got.State != model.StateReady { + t.Errorf("adopted instance host = %q, state = %s, want host-up and Ready", got.Host, got.State) + } +} + +func TestInstancesOfAHostThatReconnectsLaterAreAdoptedByReconcile(t *testing.T) { + f, _, agent := routerFixture(t) + f.putPool("stub", dynamicSpec(0, 0)) + if err := f.c.Adopt(f.ctx); err != nil { + t.Fatalf("Adopt: %v", err) + } + agent.Add(driver.Observed{InstanceID: "stub-1", Pool: "stub", Role: model.RoleGame, Phase: driver.PhaseRunning, + Address: "10.200.2.35:30001", TokenHash: "h"}) + + f.reconcile() // still offline: nothing to adopt, no failure + if _, err := f.st.GetInstance(f.ctx, "stub-1"); !errors.Is(err, store.ErrNotFound) { + t.Fatalf("instance of an offline host stored early: %v", err) + } + + agent.ListErr = nil + f.reconcile() + got := f.get("stub-1") + if got.Host != "agent-host" || got.DriverRef != "agent-host/stub-1" || got.State != model.StateReady || got.TokenHash != "h" { + t.Errorf("adopted instance = host %q ref %q state %s hash %q", got.Host, got.DriverRef, got.State, got.TokenHash) + } +} + +func TestStartedInstanceRecordsTheRealHostNotTheRouter(t *testing.T) { + f, up, _ := routerFixture(t) + f.putPool("lobby", dynamicSpec(1, 0)) + f.reconcile() + + id := up.Started()[0].Instance.ID + if got := f.get(id).Host; got != "host-up" { + t.Errorf("instance host = %q, want host-up", got) + } +} diff --git a/internal/controller/reconcile.go b/internal/controller/reconcile.go index a0b0387..7132bc5 100644 --- a/internal/controller/reconcile.go +++ b/internal/controller/reconcile.go @@ -58,6 +58,9 @@ func (c *Controller) ReconcileOnce(ctx context.Context) error { } var errs []error + if err := c.adoptLater(ctx, observed, unlisted); err != nil { + errs = append(errs, err) + } insts, err := c.listAll(ctx) if err != nil { return err diff --git a/internal/driver/process/process.go b/internal/driver/process/process.go index 245650e..d9ed1d9 100644 --- a/internal/driver/process/process.go +++ b/internal/driver/process/process.go @@ -19,7 +19,6 @@ import ( "strconv" "strings" "sync" - "syscall" "time" "github.com/OneLiteFeatherNET/grus/internal/driver" @@ -47,6 +46,13 @@ type Config struct { Logger *slog.Logger // Clock stamps StartedAt. Nil means model.SystemClock. Clock model.Clock + // PortMin and PortMax bound the ports handed to instances (inclusive). Both zero means a free + // loopback port chosen by the kernel, or the fixed port of a static pool. + PortMin, PortMax int + // AdvertiseAddress is the host part of the reported address. Empty means 127.0.0.1. + AdvertiseAddress string + // JavaPath replaces a command whose first element is "java". Empty keeps "java" from PATH. + JavaPath string } // Driver runs instances as local processes. It is safe for concurrent use. @@ -65,6 +71,7 @@ var _ driver.Driver = (*Driver)(nil) // proc is one instance. All fields are guarded by Driver.mu except done, which is closed once after // Wait returned. type proc struct { + port int // reserved port, released when the process is forgotten or failed to start obs driver.Observed cmd *exec.Cmd stdin io.WriteCloser @@ -98,6 +105,9 @@ func (d *Driver) Host() string { return d.cfg.HostID } // returned ref is the instance id. Starting an id that is still running is an error. func (d *Driver) Start(ctx context.Context, spec driver.StartSpec) (string, error) { id := spec.Instance.ID + if err := checkSupported(); err != nil { + return "", err + } if err := checkID(id); err != nil { return "", err } @@ -156,7 +166,7 @@ func (d *Driver) Start(ctx context.Context, spec driver.StartSpec) (string, erro } } - port, err := pickPort(spec) + port, err := d.reservePort(p, spec) if err != nil { return fail(err) } @@ -171,13 +181,17 @@ func (d *Driver) Start(ctx context.Context, spec driver.StartSpec) (string, erro return fail(fmt.Errorf("create output pipe: %w", err)) } - args := append(slices.Clone(eff.Command[1:]), eff.Args...) - cmd := exec.Command(eff.Command[0], args...) + command := slices.Clone(eff.Command) + if command[0] == "java" && d.cfg.JavaPath != "" { + command[0] = d.cfg.JavaPath + } + args := expand(append(command[1:], eff.Args...), port, workdir) + cmd := exec.Command(command[0], args...) cmd.Dir = workdir - cmd.Env = buildEnv(spec.Env, spec.Token, port) + cmd.Env = buildEnv(spec.Env, spec.Token, port, workdir) cmd.Stdout = outW cmd.Stderr = outW - cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + prepareCmd(cmd) stdin, err := cmd.StdinPipe() if err != nil { outR.Close() @@ -197,7 +211,7 @@ func (d *Driver) Start(ctx context.Context, spec driver.StartSpec) (string, erro d.mu.Lock() p.cmd = cmd p.stdin = stdin - p.obs.Address = net.JoinHostPort("127.0.0.1", strconv.Itoa(port)) + p.obs.Address = net.JoinHostPort(d.advertise(), strconv.Itoa(port)) p.obs.StartedAt = d.cfg.Clock.Now() d.setPhaseLocked(p, driver.PhaseRunning, "") d.mu.Unlock() @@ -255,7 +269,7 @@ func (d *Driver) Kill(ctx context.Context, ref string) error { if !started { return fmt.Errorf("process: instance %q is not started yet", ref) } - d.signal(ref, p, syscall.SIGKILL) + d.signal(ref, p, true) select { case <-p.done: return nil @@ -276,6 +290,17 @@ func (d *Driver) List(_ context.Context) ([]driver.Observed, error) { return out, nil } +// Pid returns the process id of a started instance. +func (d *Driver) Pid(ref string) (int, bool) { + d.mu.Lock() + defer d.mu.Unlock() + p, ok := d.procs[ref] + if !ok || p.cmd == nil || p.cmd.Process == nil { + return 0, false + } + return p.cmd.Process.Pid, true +} + // Forget drops an exited instance from List. Running instances cannot be forgotten. func (d *Driver) Forget(ref string) error { d.mu.Lock() @@ -369,7 +394,7 @@ func (d *Driver) escalate(ref string, p *proc, grace time.Duration) { case <-d.after(grace): } d.cfg.Logger.Info("grace period over, sending SIGTERM", "instance", ref) - d.signal(ref, p, syscall.SIGTERM) + d.signal(ref, p, false) select { case <-p.done: @@ -377,11 +402,11 @@ func (d *Driver) escalate(ref string, p *proc, grace time.Duration) { case <-d.after(d.termWait): } d.cfg.Logger.Warn("process ignored SIGTERM, sending SIGKILL", "instance", ref) - d.signal(ref, p, syscall.SIGKILL) + d.signal(ref, p, true) } // signal sends sig to the process group unless the process has already been reaped. -func (d *Driver) signal(ref string, p *proc, sig syscall.Signal) { +func (d *Driver) signal(ref string, p *proc, kill bool) { d.mu.Lock() exited := p.obs.Phase == driver.PhaseExited pid := p.cmd.Process.Pid @@ -389,8 +414,8 @@ func (d *Driver) signal(ref string, p *proc, sig syscall.Signal) { if exited { return } - if err := syscall.Kill(-pid, sig); err != nil && !errors.Is(err, syscall.ESRCH) { - d.cfg.Logger.Warn("signal failed", "instance", ref, "signal", sig.String(), "err", err) + if err := signalGroup(pid, kill); err != nil { + d.cfg.Logger.Warn("signal failed", "instance", ref, "kill", kill, "err", err) } } @@ -497,14 +522,82 @@ func joinLines(lines []string) string { return b.String() } -// buildEnv is the parent environment, then the spec env, then the GRUS_* values. Later entries win. -func buildEnv(extra map[string]string, token string, port int) []string { - env := os.Environ() +// inheritedEnv lists the only variables a child inherits from the process that runs the driver. Everything +// else of the parent environment, secrets included, stays out. +var inheritedEnv = []string{"PATH", "HOME", "LANG", "LC_ALL", "TZ", "JAVA_HOME", "TMPDIR"} + +// buildEnv is the allowlisted parent environment, then the spec env, then the GRUS_* values. Later entries win. +func buildEnv(extra map[string]string, token string, port int, workdir string) []string { + var env []string + for _, k := range inheritedEnv { + if v, ok := os.LookupEnv(k); ok { + env = append(env, k+"="+v) + } + } for _, k := range slices.Sorted(maps.Keys(extra)) { env = append(env, k+"="+extra[k]) } p := strconv.Itoa(port) - return append(env, "GRUS_TOKEN="+token, "GRUS_PORT="+p, "SERVER_PORT="+p) + return append(env, "GRUS_TOKEN="+token, "GRUS_PORT="+p, "SERVER_PORT="+p, "GRUS_DIR="+workdir) +} + +// expand replaces {{port}} and ${GRUS_DIR} in every argument. +func expand(args []string, port int, workdir string) []string { + r := strings.NewReplacer("{{port}}", strconv.Itoa(port), "${GRUS_DIR}", workdir) + out := make([]string, len(args)) + for i, a := range args { + out[i] = r.Replace(a) + } + return out +} + +func (d *Driver) advertise() string { + if d.cfg.AdvertiseAddress != "" { + return d.cfg.AdvertiseAddress + } + return "127.0.0.1" +} + +// reservePort picks the port of a new instance and records it on p. With a configured range it is the +// first port of the range that no live instance holds and that can be bound; otherwise the fixed port of +// a static pool or a free loopback port. +func (d *Driver) reservePort(p *proc, spec driver.StartSpec) (int, error) { + if d.cfg.PortMax > 0 { + d.mu.Lock() + defer d.mu.Unlock() + used := map[int]bool{} + for _, q := range d.procs { + if q != p && q.port > 0 && q.obs.Phase != driver.PhaseExited { + used[q.port] = true + } + } + for port := d.cfg.PortMin; port <= d.cfg.PortMax; port++ { + if used[port] || !bindable(port) { + continue + } + p.port = port + return port, nil + } + return 0, fmt.Errorf("process: no free port in %d-%d", d.cfg.PortMin, d.cfg.PortMax) + } + port, err := pickPort(spec) + if err != nil { + return 0, err + } + d.mu.Lock() + p.port = port + d.mu.Unlock() + return port, nil +} + +// bindable reports whether nothing listens on the TCP port. +func bindable(port int) bool { + l, err := net.Listen("tcp", ":"+strconv.Itoa(port)) + if err != nil { + return false + } + _ = l.Close() + return true } // pickPort returns the fixed port of a static pool, or a free loopback port otherwise. @@ -537,8 +630,8 @@ func exitReason(cmd *exec.Cmd, err error) string { } return "exited" } - if ws, ok := st.Sys().(syscall.WaitStatus); ok && ws.Signaled() { - return "signal: " + ws.Signal().String() + if r, ok := signaledReason(st); ok { + return r } return fmt.Sprintf("exit code %d", st.ExitCode()) } diff --git a/internal/driver/process/process_other.go b/internal/driver/process/process_other.go new file mode 100644 index 0000000..3cc3099 --- /dev/null +++ b/internal/driver/process/process_other.go @@ -0,0 +1,19 @@ +//go:build !unix + +package process + +import ( + "errors" + "os" + "os/exec" +) + +func checkSupported() error { + return errors.New("process driver is not supported on this operating system") +} + +func prepareCmd(*exec.Cmd) {} + +func signalGroup(int, bool) error { return checkSupported() } + +func signaledReason(*os.ProcessState) (string, bool) { return "", false } diff --git a/internal/driver/process/process_test.go b/internal/driver/process/process_test.go index 8332710..2d55359 100644 --- a/internal/driver/process/process_test.go +++ b/internal/driver/process/process_test.go @@ -37,6 +37,7 @@ func runHelperServer() { signal.Ignore(syscall.SIGTERM) } fmt.Printf("started on %s\n", os.Getenv("GRUS_PORT")) + fmt.Printf("args %s\n", strings.Join(os.Args[1:], " ")) sc := bufio.NewScanner(os.Stdin) for sc.Scan() { line := sc.Text() @@ -438,3 +439,83 @@ func TestStartRunsTheEffectiveCommandInsteadOfThePoolCommand(t *testing.T) { } h.waitPhase(ref, driver.PhaseRunning) } + +func TestChildDoesNotInheritTheParentEnvironment(t *testing.T) { + t.Setenv("GRUS_TEST_PARENT_SECRET", "s3cret") + t.Setenv("TZ", "UTC") + h := newHarness(t, nil) + ref, _ := h.d.Start(h.ctx, h.spec("inst-1", map[string]string{"FROM_SPEC": "yes"})) + h.waitPhase(ref, driver.PhaseRunning) + w := h.follow(ref) + + for _, c := range []struct{ name, want string }{ + {"GRUS_TEST_PARENT_SECRET", "env "}, + {"TZ", "env UTC"}, + {"FROM_SPEC", "env yes"}, + } { + if err := h.d.Command(h.ctx, ref, "env "+c.name); err != nil { + t.Fatalf("Command: %v", err) + } + w.wait(c.want) + } +} + +// freePort returns a TCP port nothing listens on right now. +func freePort(t *testing.T) int { + t.Helper() + l, err := net.Listen("tcp", ":0") + if err != nil { + t.Fatalf("find free port: %v", err) + } + defer l.Close() + return l.Addr().(*net.TCPAddr).Port +} + +func TestPortComesFromTheConfiguredRangeAndIsAdvertised(t *testing.T) { + port := freePort(t) + h := newHarness(t, nil) + h.d.cfg.PortMin, h.d.cfg.PortMax = port, port + h.d.cfg.AdvertiseAddress = "10.200.2.35" + spec := h.spec("inst-1", nil) + spec.Effective = model.EffectiveSpec{Driver: "process", Command: []string{os.Args[0]}, Args: []string{"--port={{port}}", "--dir=${GRUS_DIR}"}} + + ref, err := h.d.Start(h.ctx, spec) + if err != nil { + t.Fatalf("Start: %v", err) + } + o := h.waitPhase(ref, driver.PhaseRunning) + if want := fmt.Sprintf("10.200.2.35:%d", port); o.Address != want { + t.Errorf("Address = %q, want %q", o.Address, want) + } + w := h.follow(ref) + w.wait(fmt.Sprintf("args --port=%d --dir=%s", port, filepath.Join(h.base, "inst-1"))) +} + +func TestStartFailsWhenTheRangeIsExhausted(t *testing.T) { + port := freePort(t) + h := newHarness(t, nil) + h.d.cfg.PortMin, h.d.cfg.PortMax = port, port + ref, err := h.d.Start(h.ctx, h.spec("inst-1", nil)) + if err != nil { + t.Fatalf("first Start: %v", err) + } + h.waitPhase(ref, driver.PhaseRunning) + + if _, err := h.d.Start(h.ctx, h.spec("inst-2", nil)); err == nil { + t.Error("second Start with a one-port range returned nil error, want an error") + } +} + +func TestJavaCommandUsesTheConfiguredBinary(t *testing.T) { + h := newHarness(t, nil) + h.d.cfg.JavaPath = os.Args[0] + spec := h.spec("inst-1", nil) + spec.Effective = model.EffectiveSpec{Driver: "process", Command: []string{"java", "-jar", "server.jar"}} + + ref, err := h.d.Start(h.ctx, spec) + if err != nil { + t.Fatalf("Start: %v", err) + } + h.waitPhase(ref, driver.PhaseRunning) + h.follow(ref).wait("args -jar server.jar") +} diff --git a/internal/driver/process/process_unix.go b/internal/driver/process/process_unix.go new file mode 100644 index 0000000..602a416 --- /dev/null +++ b/internal/driver/process/process_unix.go @@ -0,0 +1,36 @@ +//go:build unix + +package process + +import ( + "errors" + "fmt" + "os" + "os/exec" + "syscall" +) + +func checkSupported() error { return nil } + +// prepareCmd puts the child in its own process group, so signals reach its whole tree. +func prepareCmd(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} } + +// signalGroup sends SIGKILL (kill) or SIGTERM to the process group of pid. A group that is gone is no error. +func signalGroup(pid int, kill bool) error { + sig := syscall.SIGTERM + if kill { + sig = syscall.SIGKILL + } + if err := syscall.Kill(-pid, sig); err != nil && !errors.Is(err, syscall.ESRCH) { + return err + } + return nil +} + +// signaledReason describes a process that was ended by a signal. +func signaledReason(st *os.ProcessState) (string, bool) { + if ws, ok := st.Sys().(syscall.WaitStatus); ok && ws.Signaled() { + return fmt.Sprintf("signal: %s", ws.Signal()), true + } + return "", false +} diff --git a/internal/driver/remote/driver.go b/internal/driver/remote/driver.go new file mode 100644 index 0000000..8aae44e --- /dev/null +++ b/internal/driver/remote/driver.go @@ -0,0 +1,353 @@ +package remote + +import ( + "context" + "errors" + "fmt" + "io" + "maps" + "slices" + "strings" + "sync" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/driver" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +const ( + // DefaultHeartbeatTimeout is how long an agent may stay silent before its host counts as offline. + DefaultHeartbeatTimeout = 30 * time.Second + // DefaultMaxWait caps the long poll. + DefaultMaxWait = 60 * time.Second + // maxLogLines is how many lines per instance are kept from an agent report. + maxLogLines = 500 +) + +// ErrOffline is returned when an agent host has not been heard of within the heartbeat timeout. +var ErrOffline = errors.New("remote: agent host offline") + +// Config configures the driver of one agent host. +type Config struct { + Host string + HeartbeatTimeout time.Duration // default DefaultHeartbeatTimeout + Clock model.Clock // default model.SystemClock + // After is the timer source of the long poll; tests replace it. Default time.After. + After func(time.Duration) <-chan time.Time +} + +// entry is one desired instance plus the revisions needed to tell when the agent has caught up. +type entry struct { + DesiredInstance + startRev int64 // revision that added the instance; 0 for instances adopted from a report + killRev int64 +} + +// Driver is the driver of one agent host. It is safe for concurrent use. +type Driver struct { + cfg Config + + mu sync.Mutex + info HostInfo + lastSeen time.Time + seen bool + revision int64 + changed chan struct{} // closed and replaced whenever the desired state changes + desired map[string]*entry + commands []Command + cmdSeq int64 + reported bool + reportRev int64 + observed map[string]ObservedInstance + logs map[string][]string +} + +var _ driver.Driver = (*Driver)(nil) + +// New returns the driver of an agent host. Until the agent reports, List fails. +func New(cfg Config) *Driver { + if cfg.HeartbeatTimeout <= 0 { + cfg.HeartbeatTimeout = DefaultHeartbeatTimeout + } + if cfg.Clock == nil { + cfg.Clock = model.SystemClock{} + } + if cfg.After == nil { + cfg.After = time.After + } + return &Driver{ + cfg: cfg, + info: HostInfo{Name: cfg.Host}, + revision: cfg.Clock.Now().UnixMilli(), + cmdSeq: cfg.Clock.Now().UnixMilli(), // later than any sequence of a previous controller run + changed: make(chan struct{}), + desired: make(map[string]*entry), + observed: make(map[string]ObservedInstance), + logs: make(map[string][]string), + } +} + +func (d *Driver) Name() string { return model.DriverAgent } + +func (d *Driver) Host() string { return d.cfg.Host } + +// Online reports whether the agent has been heard of within the heartbeat timeout. +func (d *Driver) Online() bool { + d.mu.Lock() + defer d.mu.Unlock() + return d.onlineLocked() +} + +func (d *Driver) onlineLocked() bool { + return d.seen && d.cfg.Clock.Now().Sub(d.lastSeen) <= d.cfg.HeartbeatTimeout +} + +// Info returns the host description. +func (d *Driver) Info() HostInfo { + d.mu.Lock() + defer d.mu.Unlock() + info := d.info + info.Online = d.onlineLocked() + if d.seen { + t := d.lastSeen + info.LastSeen = &t + } + info.Instances = len(d.observed) + return info +} + +// Register records the host description and counts as a heartbeat. +func (d *Driver) Register(req RegisterRequest) { + d.mu.Lock() + defer d.mu.Unlock() + d.touchLocked() + d.info.Version = req.Version + d.info.Labels = maps.Clone(req.Labels) + d.info.Capacity = req.Capacity + d.info.Address = req.Address + d.info.PortRange = req.PortRange +} + +func (d *Driver) touchLocked() { + d.lastSeen = d.cfg.Clock.Now() + d.seen = true +} + +// bumpLocked starts a new desired revision and wakes every long poll. +func (d *Driver) bumpLocked() int64 { + d.revision++ + close(d.changed) + d.changed = make(chan struct{}) + return d.revision +} + +// Start records the instance as desired. The agent starts it on its next poll. +func (d *Driver) Start(_ context.Context, spec driver.StartSpec) (string, error) { + id := spec.Instance.ID + if id == "" || strings.ContainsAny(id, "/\\") { + return "", fmt.Errorf("remote: invalid instance id %q", id) + } + eff := spec.EffectiveOrV1() + if len(eff.Command) == 0 { + return "", errors.New("remote: effective spec has no command") + } + refs := make([]TemplateVersion, len(spec.Templates)) + for i, t := range spec.Templates { + refs[i] = TemplateVersion{Name: t.Name, Digest: t.Digest} + } + + d.mu.Lock() + defer d.mu.Unlock() + if !d.onlineLocked() { + return "", fmt.Errorf("%w: %s", ErrOffline, d.cfg.Host) + } + if _, ok := d.desired[id]; ok { + return "", fmt.Errorf("remote: instance %q already exists on %s", id, d.cfg.Host) + } + e := &entry{DesiredInstance: DesiredInstance{ + ID: id, + Pool: spec.Instance.Pool, + Role: spec.Instance.Role, + Mode: spec.Pool.Spec.Mode, + Generation: spec.Instance.PoolGeneration, + Token: spec.Token, + TokenHash: spec.Instance.TokenHash, + Effective: eff, + Env: maps.Clone(spec.Env), + Templates: refs, + MemoryMiB: spec.Pool.Spec.Resources.MemoryMiB, + }} + e.startRev = d.bumpLocked() + d.desired[id] = e + return id, nil +} + +// Stop asks the agent to stop the instance; the agent runs the stop ladder (command, SIGTERM, SIGKILL). +func (d *Driver) Stop(_ context.Context, ref string, stopCommand string, grace time.Duration) error { + d.mu.Lock() + defer d.mu.Unlock() + e, ok := d.desired[ref] + if !ok { + return driver.ErrNotFound + } + if e.Stop.Requested || e.Kill { + return nil + } + e.Stop = StopRequest{Requested: true, Command: stopCommand, GraceSeconds: int(grace.Seconds())} + d.bumpLocked() + return nil +} + +// Kill asks the agent to kill the instance and forget it. The entry is dropped once the agent confirms. +func (d *Driver) Kill(_ context.Context, ref string) error { + d.mu.Lock() + defer d.mu.Unlock() + e, ok := d.desired[ref] + if !ok { + return driver.ErrNotFound + } + if e.Kill { + return nil + } + e.Kill = true + e.killRev = d.bumpLocked() + return nil +} + +// List returns the instances the agent last reported, plus instances started after the agent's last +// report. It fails while the agent is offline or has not reported yet, so the reconciler keeps the state. +func (d *Driver) List(_ context.Context) ([]driver.Observed, error) { + d.mu.Lock() + defer d.mu.Unlock() + if !d.onlineLocked() { + return nil, fmt.Errorf("%w: %s", ErrOffline, d.cfg.Host) + } + if !d.reported { + return nil, fmt.Errorf("remote: agent host %s has not reported yet", d.cfg.Host) + } + out := make([]driver.Observed, 0, len(d.desired)) + for _, id := range slices.Sorted(maps.Keys(d.observed)) { + o := d.observed[id] + out = append(out, driver.Observed{ + Ref: id, InstanceID: id, Pool: o.Pool, Role: o.Role, Mode: o.Mode, PoolGeneration: o.Generation, + TokenHash: o.TokenHash, Address: o.Address, Phase: o.Phase, Reason: o.Reason, StartedAt: o.StartedAt, + }) + } + for _, id := range slices.Sorted(maps.Keys(d.desired)) { + e := d.desired[id] + if _, reported := d.observed[id]; reported || e.Kill || e.startRev <= d.reportRev { + continue + } + out = append(out, driver.Observed{ + Ref: id, InstanceID: id, Pool: e.Pool, Role: e.Role, Mode: e.Mode, PoolGeneration: e.Generation, + TokenHash: e.TokenHash, Phase: driver.PhasePending, + }) + } + return out, nil +} + +// Logs returns the cached tail of the instance's console. Following is not supported: the agent reports +// the tail every few seconds, so follow returns the same snapshot and ends. +func (d *Driver) Logs(_ context.Context, ref string, tail int, _ bool) (io.ReadCloser, error) { + d.mu.Lock() + defer d.mu.Unlock() + if _, ok := d.desired[ref]; !ok { + return nil, driver.ErrNotFound + } + lines := d.logs[ref] + if tail > 0 && tail < len(lines) { + lines = lines[len(lines)-tail:] + } + var b strings.Builder + for _, l := range lines { + b.WriteString(l) + b.WriteByte('\n') + } + return io.NopCloser(strings.NewReader(b.String())), nil +} + +// Command queues a console line; the agent delivers it on its next poll. +func (d *Driver) Command(_ context.Context, ref string, line string) error { + if strings.ContainsAny(line, "\r\n") { + return errors.New("remote: console line must not contain line breaks") + } + d.mu.Lock() + defer d.mu.Unlock() + if _, ok := d.desired[ref]; !ok { + return driver.ErrNotFound + } + d.cmdSeq++ + d.commands = append(d.commands, Command{Seq: d.cmdSeq, Instance: ref, Line: line}) + d.bumpLocked() + return nil +} + +// Desired returns the desired state. When revision equals the current one it waits until the state +// changes, wait elapses or ctx ends, and then returns the current state either way. Asking counts as a +// heartbeat. +func (d *Driver) Desired(ctx context.Context, revision int64, wait time.Duration) Desired { + d.mu.Lock() + d.touchLocked() + if revision == d.revision && wait > 0 { + if wait > DefaultMaxWait { + wait = DefaultMaxWait + } + changed := d.changed + d.mu.Unlock() + select { + case <-changed: + case <-d.cfg.After(wait): + case <-ctx.Done(): + } + d.mu.Lock() + d.touchLocked() + } + defer d.mu.Unlock() + + out := Desired{Revision: d.revision, Instances: []DesiredInstance{}, Commands: slices.Clone(d.commands)} + if out.Commands == nil { + out.Commands = []Command{} + } + for _, id := range slices.Sorted(maps.Keys(d.desired)) { + out.Instances = append(out.Instances, d.desired[id].DesiredInstance) + } + return out +} + +// Observe stores the report of the agent. Instances the controller does not know yet are kept as desired +// entries so a restarted controller does not tell the agent to drop them. +func (d *Driver) Observe(rep ObservedReport) { + d.mu.Lock() + defer d.mu.Unlock() + d.touchLocked() + d.reported = true + if rep.Revision > d.reportRev { + d.reportRev = rep.Revision + } + d.observed = make(map[string]ObservedInstance, len(rep.Instances)) + for _, o := range rep.Instances { + if o.ID == "" { + continue + } + d.observed[o.ID] = o + if _, ok := d.desired[o.ID]; !ok { + d.desired[o.ID] = &entry{DesiredInstance: DesiredInstance{ + ID: o.ID, Pool: o.Pool, Role: o.Role, Mode: o.Mode, Generation: o.Generation, TokenHash: o.TokenHash, + }} + } + } + for id, e := range d.desired { + if _, reported := d.observed[id]; !reported && e.Kill && e.killRev <= rep.Revision { + delete(d.desired, id) + delete(d.logs, id) + } + } + d.logs = make(map[string][]string, len(rep.Logs)) + for id, lines := range rep.Logs { + if len(lines) > maxLogLines { + lines = lines[len(lines)-maxLogLines:] + } + d.logs[id] = slices.Clone(lines) + } + d.commands = slices.DeleteFunc(d.commands, func(c Command) bool { return c.Seq <= rep.CommandSeq }) +} diff --git a/internal/driver/remote/driver_test.go b/internal/driver/remote/driver_test.go new file mode 100644 index 0000000..f50b98f --- /dev/null +++ b/internal/driver/remote/driver_test.go @@ -0,0 +1,295 @@ +package remote + +import ( + "context" + "errors" + "io" + "sync" + "testing" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/driver" + "github.com/OneLiteFeatherNET/grus/internal/driver/router" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +type fakeClock struct { + mu sync.Mutex + now time.Time +} + +func (c *fakeClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *fakeClock) Advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = c.now.Add(d) +} + +type fixture struct { + clock *fakeClock + d *Driver + timer chan time.Time // fires the long poll timeout +} + +func newFixture(t *testing.T) *fixture { + t.Helper() + f := &fixture{clock: &fakeClock{now: time.Unix(1_700_000_000, 0)}, timer: make(chan time.Time, 1)} + f.d = New(Config{Host: "mc01", HeartbeatTimeout: 30 * time.Second, Clock: f.clock, + After: func(time.Duration) <-chan time.Time { return f.timer }}) + return f +} + +func startSpec(id string) driver.StartSpec { + return driver.StartSpec{ + Instance: model.Instance{ID: id, Pool: "lobby", Role: model.RoleGame, PoolGeneration: 3, TokenHash: "h-" + id}, + Pool: model.Pool{Name: "lobby", Spec: model.PoolSpec{Mode: model.ModeDynamic, Resources: model.Resources{MemoryMiB: 512}}}, + Effective: model.EffectiveSpec{Driver: "agent", Command: []string{"./server"}}, + Token: "plain-" + id, + Env: map[string]string{"GRUS_INSTANCE": id}, + Templates: []driver.ResolvedTemplate{{Name: "base", Digest: "sha256:aa"}}, + } +} + +func (f *fixture) online(t *testing.T) { + t.Helper() + f.d.Register(RegisterRequest{Version: "1"}) + f.d.Observe(ObservedReport{Revision: f.d.Desired(context.Background(), -1, 0).Revision}) +} + +func TestListFailsUntilTheAgentHasReported(t *testing.T) { + f := newFixture(t) + if _, err := f.d.List(context.Background()); err == nil { + t.Fatal("List of a host that never connected returned nil error") + } + f.d.Register(RegisterRequest{}) + if _, err := f.d.List(context.Background()); err == nil { + t.Error("List before the first report returned nil error") + } + f.d.Observe(ObservedReport{}) + if _, err := f.d.List(context.Background()); err != nil { + t.Errorf("List after the first report: %v", err) + } +} + +func TestListFailsOnceTheHeartbeatTimeoutPassed(t *testing.T) { + f := newFixture(t) + f.online(t) + f.clock.Advance(31 * time.Second) + + _, err := f.d.List(context.Background()) + if !errors.Is(err, ErrOffline) { + t.Errorf("List after the heartbeat timeout: err = %v, want ErrOffline", err) + } +} + +func TestStartIsOfferedToTheAgentAndListedAsPendingUntilReported(t *testing.T) { + f := newFixture(t) + f.online(t) + ref, err := f.d.Start(context.Background(), startSpec("lobby-a")) + if err != nil { + t.Fatalf("Start: %v", err) + } + list, _ := f.d.List(context.Background()) + if len(list) != 1 || list[0].Phase != driver.PhasePending || list[0].Ref != ref { + t.Fatalf("List = %+v, want one Pending instance %q", list, ref) + } + want := f.d.Desired(context.Background(), -1, 0) + if len(want.Instances) != 1 { + t.Fatalf("desired instances = %d, want 1", len(want.Instances)) + } + got := want.Instances[0] + if got.Token != "plain-lobby-a" || got.TokenHash != "h-lobby-a" || got.MemoryMiB != 512 || got.Templates[0].Digest != "sha256:aa" { + t.Errorf("desired instance = %+v", got) + } + + f.d.Observe(ObservedReport{Revision: want.Revision, Instances: []ObservedInstance{ + {ID: "lobby-a", Pool: "lobby", Phase: driver.PhaseRunning, Address: "10.0.0.1:30000"}, + }}) + list, _ = f.d.List(context.Background()) + if len(list) != 1 || list[0].Phase != driver.PhaseRunning || list[0].Address != "10.0.0.1:30000" { + t.Errorf("List after report = %+v, want the reported Running instance", list) + } +} + +func TestInstanceMissingFromAReportThatAppliedItsStartIsGone(t *testing.T) { + f := newFixture(t) + f.online(t) + _, _ = f.d.Start(context.Background(), startSpec("lobby-a")) + rev := f.d.Desired(context.Background(), -1, 0).Revision + + f.d.Observe(ObservedReport{Revision: rev}) + list, _ := f.d.List(context.Background()) + if len(list) != 0 { + t.Errorf("List = %+v, want no instances", list) + } +} + +func TestStartRefusesAnOfflineHostAndADuplicate(t *testing.T) { + f := newFixture(t) + if _, err := f.d.Start(context.Background(), startSpec("a")); !errors.Is(err, ErrOffline) { + t.Errorf("Start on an offline host: err = %v, want ErrOffline", err) + } + f.online(t) + if _, err := f.d.Start(context.Background(), startSpec("a")); err != nil { + t.Fatalf("Start: %v", err) + } + if _, err := f.d.Start(context.Background(), startSpec("a")); err == nil { + t.Error("second Start of the same id returned nil error") + } +} + +func TestStopAndKillAreDesiredStateAndKillIsDroppedOnceTheAgentConfirms(t *testing.T) { + f := newFixture(t) + f.online(t) + _, _ = f.d.Start(context.Background(), startSpec("a")) + if err := f.d.Stop(context.Background(), "a", "stop", 20*time.Second); err != nil { + t.Fatalf("Stop: %v", err) + } + got := f.d.Desired(context.Background(), -1, 0).Instances[0] + if !got.Stop.Requested || got.Stop.Command != "stop" || got.Stop.GraceSeconds != 20 { + t.Errorf("stop request = %+v", got.Stop) + } + + if err := f.d.Kill(context.Background(), "a"); err != nil { + t.Fatalf("Kill: %v", err) + } + rev := f.d.Desired(context.Background(), -1, 0) + if !rev.Instances[0].Kill { + t.Error("kill flag not set") + } + f.d.Observe(ObservedReport{Revision: rev.Revision - 1, Instances: []ObservedInstance{{ID: "a", Phase: driver.PhaseRunning}}}) + f.d.Observe(ObservedReport{Revision: rev.Revision}) + if n := len(f.d.Desired(context.Background(), -1, 0).Instances); n != 0 { + t.Errorf("desired instances after the agent confirmed the kill = %d, want 0", n) + } + if err := f.d.Kill(context.Background(), "a"); !errors.Is(err, driver.ErrNotFound) { + t.Errorf("Kill of a dropped instance: err = %v, want ErrNotFound", err) + } +} + +func TestLongPollReturnsImmediatelyForANewRevisionAndOtherwiseWaitsForAChange(t *testing.T) { + f := newFixture(t) + f.online(t) + rev := f.d.Desired(context.Background(), -1, 0).Revision + + // The client has the current revision: the poll blocks until the state changes. + done := make(chan Desired, 1) + go func() { done <- f.d.Desired(context.Background(), rev, 25*time.Second) }() + _, _ = f.d.Start(context.Background(), startSpec("a")) + got := <-done + if got.Revision == rev || len(got.Instances) != 1 { + t.Errorf("poll after a change = revision %d (was %d), %d instances", got.Revision, rev, len(got.Instances)) + } + + // A stale client revision returns at once, without waiting for the timer. + if got := f.d.Desired(context.Background(), rev, 25*time.Second); got.Revision == rev { + t.Error("poll with a stale revision returned the old revision") + } +} + +func TestLongPollEndsWhenTheWaitTimerFires(t *testing.T) { + f := newFixture(t) + f.online(t) + rev := f.d.Desired(context.Background(), -1, 0).Revision + f.timer <- time.Time{} + + got := f.d.Desired(context.Background(), rev, 25*time.Second) + if got.Revision != rev { + t.Errorf("revision after a timeout = %d, want unchanged %d", got.Revision, rev) + } +} + +func TestConsoleCommandsAreQueuedUntilTheAgentAcknowledgesThem(t *testing.T) { + f := newFixture(t) + f.online(t) + _, _ = f.d.Start(context.Background(), startSpec("a")) + if err := f.d.Command(context.Background(), "a", "say hi"); err != nil { + t.Fatalf("Command: %v", err) + } + if err := f.d.Command(context.Background(), "nope", "x"); !errors.Is(err, driver.ErrNotFound) { + t.Errorf("Command to an unknown instance: err = %v, want ErrNotFound", err) + } + cmds := f.d.Desired(context.Background(), -1, 0).Commands + if len(cmds) != 1 || cmds[0].Line != "say hi" || cmds[0].Instance != "a" { + t.Fatalf("commands = %+v", cmds) + } + f.d.Observe(ObservedReport{CommandSeq: cmds[0].Seq, Instances: []ObservedInstance{{ID: "a", Phase: driver.PhaseRunning}}}) + if n := len(f.d.Desired(context.Background(), -1, 0).Commands); n != 0 { + t.Errorf("commands after the acknowledgement = %d, want 0", n) + } +} + +func TestLogsReturnTheReportedTail(t *testing.T) { + f := newFixture(t) + f.online(t) + _, _ = f.d.Start(context.Background(), startSpec("a")) + f.d.Observe(ObservedReport{ + Instances: []ObservedInstance{{ID: "a", Phase: driver.PhaseRunning}}, + Logs: map[string][]string{"a": {"one", "two", "three"}}, + }) + rc, err := f.d.Logs(context.Background(), "a", 2, true) + if err != nil { + t.Fatalf("Logs: %v", err) + } + b, _ := io.ReadAll(rc) + if string(b) != "two\nthree\n" { + t.Errorf("logs = %q, want the last two lines", b) + } +} + +func TestInstancesReportedByARestartedAgentStayDesiredSoTheyAreNotDropped(t *testing.T) { + f := newFixture(t) + f.d.Register(RegisterRequest{}) + f.d.Observe(ObservedReport{Instances: []ObservedInstance{ + {ID: "old", Pool: "lobby", Role: model.RoleGame, TokenHash: "h", Phase: driver.PhaseRunning}, + }}) + got := f.d.Desired(context.Background(), -1, 0).Instances + if len(got) != 1 || got[0].ID != "old" || len(got[0].Effective.Command) != 0 { + t.Fatalf("desired = %+v, want the reported instance without a command", got) + } + list, err := f.d.List(context.Background()) + if err != nil || len(list) != 1 || list[0].TokenHash != "h" || list[0].Pool != "lobby" { + t.Errorf("List = %+v, %v", list, err) + } +} + +func TestRegistryAddsHostsToTheRouterAndNotifiesOnFirstContact(t *testing.T) { + r := router.New(nil) + clock := &fakeClock{now: time.Unix(1_700_000_000, 0)} + reg := NewRegistry(r, Config{Clock: clock}) + var notified []string + reg.OnNewHost(func(h string) { notified = append(notified, h) }) + if err := reg.Preregister("pre"); err != nil { + t.Fatalf("Preregister: %v", err) + } + + if _, err := reg.Register(context.Background(), "mc01", RegisterRequest{Version: "2", Address: "10.200.2.35"}); err != nil { + t.Fatalf("Register: %v", err) + } + if _, err := reg.Register(context.Background(), "mc01", RegisterRequest{Version: "2"}); err != nil { + t.Fatalf("second Register: %v", err) + } + if len(notified) != 1 || notified[0] != "mc01" { + t.Errorf("notified = %v, want [mc01] once", notified) + } + if !reg.Online("mc01") || reg.Online("pre") || reg.Online("nope") { + t.Errorf("Online mc01=%v pre=%v nope=%v, want true false false", reg.Online("mc01"), reg.Online("pre"), reg.Online("nope")) + } + if _, err := reg.Host("nope"); err == nil { + t.Error("Host of an unknown name returned nil error") + } + hosts := reg.Hosts() + if len(hosts) != 2 || hosts[0].Name != "mc01" || hosts[1].Name != "pre" || hosts[1].LastSeen != nil { + t.Errorf("Hosts = %+v", hosts) + } + _, err := r.List(context.Background()) + var partial *router.PartialListError + if !errors.As(err, &partial) || len(partial.Hosts) != 2 { + t.Errorf("router List err = %v, want both hosts unlisted before any report", err) + } +} diff --git a/internal/driver/remote/registry.go b/internal/driver/remote/registry.go new file mode 100644 index 0000000..1c870a6 --- /dev/null +++ b/internal/driver/remote/registry.go @@ -0,0 +1,142 @@ +package remote + +import ( + "context" + "fmt" + "maps" + "slices" + "sync" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/driver/router" +) + +// Registry owns the drivers of all agent hosts and keeps them registered in a router. A host exists from +// Ensure (at startup for configured hosts, or on first contact of an agent) and never leaves: an agent that +// disappears makes its host offline, not unknown, so its instances keep their state. +type Registry struct { + router *router.Router + base Config + + mu sync.Mutex + hosts map[string]*Driver + onNew func(host string) +} + +// NewRegistry returns a registry that adds its hosts to r. base supplies the heartbeat timeout, clock and +// timer source of every host driver; its Host is ignored. +func NewRegistry(r *router.Router, base Config) *Registry { + return &Registry{router: r, base: base, hosts: make(map[string]*Driver)} +} + +// OnNewHost sets a callback that runs for hosts created after startup, i.e. by first contact of an agent. +func (g *Registry) OnNewHost(fn func(host string)) { + g.mu.Lock() + defer g.mu.Unlock() + g.onNew = fn +} + +// Preregister adds hosts without any contact, so the router knows them and reports them as unlisted +// instead of unknown while their agent is away. +func (g *Registry) Preregister(hosts ...string) error { + for _, h := range hosts { + if _, _, err := g.ensure(h, false); err != nil { + return err + } + } + return nil +} + +// Ensure returns the driver of host and creates it on first use. +func (g *Registry) Ensure(host string) (*Driver, error) { + d, _, err := g.ensure(host, true) + return d, err +} + +func (g *Registry) ensure(host string, notify bool) (*Driver, bool, error) { + g.mu.Lock() + if d, ok := g.hosts[host]; ok { + g.mu.Unlock() + return d, false, nil + } + cfg := g.base + cfg.Host = host + d := New(cfg) + if err := g.router.Add(d); err != nil { + g.mu.Unlock() + return nil, false, err + } + g.hosts[host] = d + onNew := g.onNew + g.mu.Unlock() + if notify && onNew != nil { + onNew(host) + } + return d, true, nil +} + +// Online reports whether the host exists and its agent is within the heartbeat timeout. +func (g *Registry) Online(host string) bool { + g.mu.Lock() + d, ok := g.hosts[host] + g.mu.Unlock() + return ok && d.Online() +} + +// Register records a registration or heartbeat of the host's agent. +func (g *Registry) Register(_ context.Context, host string, req RegisterRequest) (HostInfo, error) { + d, err := g.Ensure(host) + if err != nil { + return HostInfo{}, err + } + d.Register(req) + return d.Info(), nil +} + +// Desired is the long poll of the host's agent. +func (g *Registry) Desired(ctx context.Context, host string, revision int64, wait time.Duration) (Desired, error) { + d, err := g.Ensure(host) + if err != nil { + return Desired{}, err + } + return d.Desired(ctx, revision, wait), nil +} + +// Observed stores the report of the host's agent. +func (g *Registry) Observed(_ context.Context, host string, rep ObservedReport) error { + d, err := g.Ensure(host) + if err != nil { + return err + } + d.Observe(rep) + return nil +} + +// Hosts lists all hosts sorted by name. +func (g *Registry) Hosts() []HostInfo { + g.mu.Lock() + drivers := make([]*Driver, 0, len(g.hosts)) + for _, name := range slices.Sorted(maps.Keys(g.hosts)) { + drivers = append(drivers, g.hosts[name]) + } + g.mu.Unlock() + out := make([]HostInfo, len(drivers)) + for i, d := range drivers { + out[i] = d.Info() + } + return out +} + +// Host returns one host. +func (g *Registry) Host(name string) (HostInfo, error) { + g.mu.Lock() + d, ok := g.hosts[name] + g.mu.Unlock() + if !ok { + return HostInfo{}, fmt.Errorf("%w: host %s", ErrUnknownHost, name) + } + return d.Info(), nil +} + +// ErrUnknownHost is returned by Host for a host that never registered and is not preregistered. +var ErrUnknownHost = fmt.Errorf("remote: unknown host") diff --git a/internal/driver/remote/wire.go b/internal/driver/remote/wire.go new file mode 100644 index 0000000..ac2933d --- /dev/null +++ b/internal/driver/remote/wire.go @@ -0,0 +1,107 @@ +// Package remote implements driver.Driver for a host that runs instances through a grus-agent. The agent +// pulls its desired state from the controller over HTTP and reports what it observes; this package keeps +// both sides of that exchange in memory. Nothing is persisted: after a controller restart the agent +// re-reports its running instances and the controller adopts them. +package remote + +import ( + "time" + + "github.com/OneLiteFeatherNET/grus/internal/driver" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +// Capacity is what a host offers. +type Capacity struct { + MemoryMiB int `json:"memoryMiB,omitempty" doc:"Memory available for instances"` +} + +// RegisterRequest is the body of PUT /v1/agents/{host}; it doubles as heartbeat. +type RegisterRequest struct { + Version string `json:"version,omitempty" doc:"Agent version"` + Labels map[string]string `json:"labels,omitempty" doc:"Free host labels"` + Capacity Capacity `json:"capacity,omitempty"` + Address string `json:"address,omitempty" doc:"IP address proxies use to reach instances on this host"` + PortRange string `json:"portRange,omitempty" doc:"Instance port range, e.g. 30000-30100"` +} + +// TemplateVersion is a template version the agent fetches before it starts an instance. +type TemplateVersion struct { + Name string `json:"name"` + Digest string `json:"digest"` +} + +// StopRequest asks the agent to stop an instance gracefully. +type StopRequest struct { + Requested bool `json:"requested"` + Command string `json:"command,omitempty" doc:"Console line that triggers a clean shutdown"` + GraceSeconds int `json:"graceSeconds,omitempty" doc:"Time before the agent sends SIGTERM"` +} + +// DesiredInstance is one instance the agent must run. Entries without an effective command are known +// instances the controller adopted from the agent: they are never started, only stopped or killed. +type DesiredInstance struct { + ID string `json:"id"` + Pool string `json:"pool"` + Role model.Role `json:"role"` + Mode model.Mode `json:"mode"` + Generation int64 `json:"generation"` + Token string `json:"token,omitempty" doc:"Plain per-instance token for GRUS_TOKEN"` + TokenHash string `json:"tokenHash,omitempty"` + Effective model.EffectiveSpec `json:"effective"` + Env map[string]string `json:"env,omitempty" doc:"Environment of the instance as the controller built it; the agent overrides GRUS_URL"` + Templates []TemplateVersion `json:"templates,omitempty"` + MemoryMiB int `json:"memoryMiB,omitempty"` + Stop StopRequest `json:"stop"` + Kill bool `json:"kill,omitempty" doc:"Kill the instance and forget it"` +} + +// Command is one console line for an instance. Seq grows per host; the agent acknowledges the highest +// sequence number it has applied in its observed report. +type Command struct { + Seq int64 `json:"seq"` + Instance string `json:"instance"` + Line string `json:"line"` +} + +// Desired is the response of the long poll. +type Desired struct { + Revision int64 `json:"revision" doc:"Changes whenever the desired state changes"` + Instances []DesiredInstance `json:"instances"` + Commands []Command `json:"commands"` +} + +// ObservedInstance is what the agent sees of one instance. +type ObservedInstance struct { + ID string `json:"id"` + Pool string `json:"pool,omitempty"` + Role model.Role `json:"role,omitempty"` + Mode model.Mode `json:"mode,omitempty"` + Generation int64 `json:"generation,omitempty"` + TokenHash string `json:"tokenHash,omitempty"` + Address string `json:"address,omitempty"` + Phase driver.Phase `json:"phase"` + Reason string `json:"reason,omitempty"` + StartedAt time.Time `json:"startedAt,omitempty"` +} + +// ObservedReport is the body of PUT /v1/agents/{host}/observed. +type ObservedReport struct { + Revision int64 `json:"revision" doc:"Desired revision the agent has applied before this report"` + CommandSeq int64 `json:"commandSeq,omitempty" doc:"Highest console command sequence number the agent has applied"` + Instances []ObservedInstance `json:"instances"` + Logs map[string][]string `json:"logs,omitempty" doc:"Last console lines per instance id"` +} + +// HostInfo describes one registered host. +type HostInfo struct { + Name string `json:"name"` + Version string `json:"version,omitempty"` + Address string `json:"address,omitempty"` + PortRange string `json:"portRange,omitempty"` + Labels map[string]string `json:"labels,omitempty"` + Capacity Capacity `json:"capacity,omitempty"` + LastSeen *time.Time `json:"lastSeen,omitempty" doc:"Last contact of the agent; absent when it never connected"` + Online bool `json:"online"` + Instances int `json:"instances" doc:"Instances the agent reported"` +} diff --git a/web/app/types/grus-api.d.ts b/web/app/types/grus-api.d.ts index a9bf0ca..3c5e4b8 100644 --- a/web/app/types/grus-api.d.ts +++ b/web/app/types/grus-api.d.ts @@ -38,6 +38,57 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/agents/{host}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** Register an agent host or send its heartbeat */ + put: operations["register-agent"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/agents/{host}/desired": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Long-poll the desired state of an agent host */ + get: operations["get-agent-desired"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/agents/{host}/observed": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** Report the instances an agent host runs */ + put: operations["put-agent-observed"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/environments": { parameters: { query?: never; @@ -142,6 +193,40 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/hosts": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** List agent hosts */ + get: operations["list-hosts"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/hosts/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Get an agent host */ + get: operations["get-host"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/instances": { parameters: { query?: never; @@ -484,6 +569,19 @@ export interface paths { export type webhooks = Record; export interface components { schemas: { + Capacity: { + /** + * Format: int64 + * @description Memory available for instances + */ + memoryMiB?: number; + }; + Command: { + instance: string; + line: string; + /** Format: int64 */ + seq: number; + }; CommandBody: { /** * Format: uri @@ -504,6 +602,63 @@ export interface components { /** @description Pool that gets the new instance */ pool: string; }; + Desired: { + /** + * Format: uri + * @description A URL to the JSON Schema for this object. + * @example https://example.com/schemas/Desired.json + */ + readonly $schema?: string; + commands: components["schemas"]["Command"][] | null; + instances: components["schemas"]["DesiredInstance"][] | null; + /** + * Format: int64 + * @description Changes whenever the desired state changes + */ + revision: number; + }; + DesiredInstance: { + effective: components["schemas"]["EffectiveSpec"]; + /** @description Environment of the instance as the controller built it; the agent overrides GRUS_URL */ + env?: { + [key: string]: string; + }; + /** Format: int64 */ + generation: number; + id: string; + /** @description Kill the instance and forget it */ + kill?: boolean; + /** Format: int64 */ + memoryMiB?: number; + mode: string; + pool: string; + role: string; + stop: components["schemas"]["StopRequest"]; + templates?: components["schemas"]["TemplateVersion"][] | null; + /** @description Plain per-instance token for GRUS_TOKEN */ + token?: string; + tokenHash?: string; + }; + EffectiveSpec: { + args?: string[] | null; + command?: string[] | null; + driver: string; + env?: { + [key: string]: string; + }; + gracePeriod: string; + host?: string; + image?: string; + kind?: string; + labels?: { + [key: string]: string; + }; + /** Format: int64 */ + port: number; + readiness: string; + stopCommand?: string; + templates?: components["schemas"]["TemplateRef"][] | null; + }; Environment: { /** * Format: uri @@ -621,6 +776,33 @@ export interface components { }; templates?: components["schemas"]["TemplateRef"][] | null; }; + HostInfo: { + /** + * Format: uri + * @description A URL to the JSON Schema for this object. + * @example https://example.com/schemas/HostInfo.json + */ + readonly $schema?: string; + address?: string; + capacity?: components["schemas"]["Capacity"]; + /** + * Format: int64 + * @description Instances the agent reported + */ + instances: number; + labels?: { + [key: string]: string; + }; + /** + * Format: date-time + * @description Last contact of the agent; absent when it never connected + */ + lastSeen?: string; + name: string; + online: boolean; + portRange?: string; + version?: string; + }; Instance: { /** * Format: uri @@ -689,6 +871,43 @@ export interface components { /** Format: int64 */ proxies: number; }; + ObservedInstance: { + address?: string; + /** Format: int64 */ + generation?: number; + id: string; + mode?: string; + phase: string; + pool?: string; + reason?: string; + role?: string; + /** Format: date-time */ + startedAt?: string; + tokenHash?: string; + }; + ObservedReport: { + /** + * Format: uri + * @description A URL to the JSON Schema for this object. + * @example https://example.com/schemas/ObservedReport.json + */ + readonly $schema?: string; + /** + * Format: int64 + * @description Highest console command sequence number the agent has applied + */ + commandSeq?: number; + instances: components["schemas"]["ObservedInstance"][] | null; + /** @description Last console lines per instance id */ + logs?: { + [key: string]: string[] | null; + }; + /** + * Format: int64 + * @description Desired revision the agent has applied before this report + */ + revision: number; + }; Placement: { driver?: string; host?: string; @@ -749,6 +968,25 @@ export interface components { /** Format: int64 */ quotaPerOwner?: number; }; + RegisterRequest: { + /** + * Format: uri + * @description A URL to the JSON Schema for this object. + * @example https://example.com/schemas/RegisterRequest.json + */ + readonly $schema?: string; + /** @description IP address proxies use to reach instances on this host */ + address?: string; + capacity?: components["schemas"]["Capacity"]; + /** @description Free host labels */ + labels?: { + [key: string]: string; + }; + /** @description Instance port range, e.g. 30000-30100 */ + portRange?: string; + /** @description Agent version */ + version?: string; + }; Resources: { cpu?: string; /** Format: int64 */ @@ -809,6 +1047,16 @@ export interface components { drain?: boolean; force?: boolean; }; + StopRequest: { + /** @description Console line that triggers a clean shutdown */ + command?: string; + /** + * Format: int64 + * @description Time before the agent sends SIGTERM + */ + graceSeconds?: number; + requested: boolean; + }; TagBody: { /** * Format: uri @@ -824,6 +1072,10 @@ export interface components { name: string; tag?: string; }; + TemplateVersion: { + digest: string; + name: string; + }; }; responses: never; parameters: never; @@ -882,6 +1134,113 @@ export interface operations { }; }; }; + "register-agent": { + parameters: { + query?: never; + header?: never; + path: { + /** @description Agent host name */ + host: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["RegisterRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HostInfo"]; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; + "get-agent-desired": { + parameters: { + query?: { + /** @description How long the request may wait for a change, as a duration (max 60s) */ + wait?: string; + /** @description Revision the agent already has; the call returns at once when it differs */ + revision?: number; + }; + header?: never; + path: { + /** @description Agent host name */ + host: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Desired"]; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; + "put-agent-observed": { + parameters: { + query?: never; + header?: never; + path: { + /** @description Agent host name */ + host: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["ObservedReport"]; + }; + }; + responses: { + /** @description No Content */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; "list-environments": { parameters: { query?: never; @@ -1174,6 +1533,67 @@ export interface operations { }; }; }; + "list-hosts": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HostInfo"][] | null; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; + "get-host": { + parameters: { + query?: never; + header?: never; + path: { + /** @description Host name */ + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HostInfo"]; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; "list-instances": { parameters: { query?: {