diff --git a/api/openapi.yaml b/api/openapi.yaml index ae820c6..9edf4ba 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -34,6 +34,83 @@ components: required: - pool type: object + Environment: + additionalProperties: false + properties: + $schema: + description: A URL to the JSON Schema for this object. + examples: + - https://example.com/schemas/Environment.json + format: uri + readOnly: true + type: string + createdAt: + format: date-time + type: string + generation: + format: int64 + type: integer + name: + type: string + source: + type: string + spec: + $ref: "#/components/schemas/EnvironmentSpec" + updatedAt: + format: date-time + type: string + required: + - name + - spec + - source + - generation + - createdAt + - updatedAt + type: object + EnvironmentSpec: + additionalProperties: false + properties: + $schema: + description: A URL to the JSON Schema for this object. + examples: + - https://example.com/schemas/EnvironmentSpec.json + format: uri + readOnly: true + type: string + args: + items: + type: string + type: + - array + - "null" + command: + items: + type: string + type: + - array + - "null" + env: + additionalProperties: + type: string + type: object + gracePeriod: + type: string + image: + type: string + jvm: + $ref: "#/components/schemas/JVM" + kind: + type: string + port: + format: int64 + type: integer + readiness: + type: string + stopCommand: + type: string + required: + - kind + type: object ErrorDetail: additionalProperties: false properties: @@ -93,6 +170,64 @@ components: format: uri type: string type: object + Group: + additionalProperties: false + properties: + $schema: + description: A URL to the JSON Schema for this object. + examples: + - https://example.com/schemas/Group.json + format: uri + readOnly: true + type: string + createdAt: + format: date-time + type: string + generation: + format: int64 + type: integer + name: + type: string + source: + type: string + spec: + $ref: "#/components/schemas/GroupSpec" + updatedAt: + format: date-time + type: string + required: + - name + - spec + - source + - generation + - createdAt + - updatedAt + type: object + GroupSpec: + additionalProperties: false + properties: + $schema: + description: A URL to the JSON Schema for this object. + examples: + - https://example.com/schemas/GroupSpec.json + format: uri + readOnly: true + type: string + env: + additionalProperties: + type: string + type: object + labels: + additionalProperties: + type: string + type: object + templates: + items: + $ref: "#/components/schemas/TemplateRef" + type: + - array + - "null" + type: object Instance: additionalProperties: false properties: @@ -156,6 +291,20 @@ components: - maxPlayers - createdAt type: object + JVM: + additionalProperties: false + properties: + flags: + description: JVM flags placed before -Xmx and -jar + items: + type: string + type: + - array + - "null" + jar: + description: Jar file inside the instance directory + type: string + type: object Lifecycle: additionalProperties: false properties: @@ -183,6 +332,38 @@ components: required: - enabled type: object + NetworkStatus: + additionalProperties: false + properties: + $schema: + description: A URL to the JSON Schema for this object. + examples: + - https://example.com/schemas/NetworkStatus.json + format: uri + readOnly: true + type: string + maxPlayers: + format: int64 + type: integer + players: + format: int64 + type: integer + proxies: + format: int64 + type: integer + required: + - players + - maxPlayers + - proxies + type: object + Placement: + additionalProperties: false + properties: + driver: + type: string + host: + type: string + type: object Pool: additionalProperties: false properties: @@ -203,6 +384,8 @@ components: type: boolean name: type: string + source: + type: string spec: $ref: "#/components/schemas/PoolSpec" updatedAt: @@ -244,6 +427,14 @@ components: additionalProperties: type: string type: object + environment: + type: string + groups: + items: + type: string + type: + - array + - "null" image: type: string labels: @@ -254,11 +445,15 @@ components: $ref: "#/components/schemas/Lifecycle" mode: type: string + placement: + $ref: "#/components/schemas/Placement" port: format: int64 type: integer priorityClassName: type: string + private: + $ref: "#/components/schemas/Private" resources: $ref: "#/components/schemas/Resources" role: @@ -271,6 +466,8 @@ components: type: - array - "null" + sharding: + $ref: "#/components/schemas/Sharding" templates: items: $ref: "#/components/schemas/TemplateRef" @@ -280,10 +477,18 @@ components: required: - role - mode - - driver - resources - scaling type: object + Private: + additionalProperties: false + properties: + idleTimeout: + type: string + quotaPerOwner: + format: int64 + type: integer + type: object Resources: additionalProperties: false properties: @@ -338,6 +543,21 @@ components: - secret - key type: object + Sharding: + additionalProperties: false + properties: + cellSize: + description: Cell edge length in chunks + format: int64 + type: integer + cells: + description: Explicit cell names + items: + type: string + type: + - array + - "null" + type: object StatusUpdate: additionalProperties: false properties: @@ -443,6 +663,112 @@ paths: type: string description: not ready summary: Readiness + /v1/environments: + get: + operationId: list-environments + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/Environment" + type: + - array + - "null" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: List environments + /v1/environments/{name}: + delete: + description: Pools that still name it stop starting instances. Objects owned by Kubernetes answer 409. + operationId: delete-environment + parameters: + - description: Object name + in: path + name: name + required: true + schema: + description: Object name + type: string + responses: + "204": + description: No Content + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Delete an environment + get: + operationId: get-environment + parameters: + - description: Object name + in: path + name: name + required: true + schema: + description: Object name + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Environment" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Get an environment + put: + description: Idempotent. Generation increases when the spec changes. Objects owned by Kubernetes answer 409. + operationId: put-environment + parameters: + - description: Environment name + in: path + name: name + required: true + schema: + description: Environment name + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/EnvironmentSpec" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Environment" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Create or replace an environment /v1/events: get: description: Each event has an `event:` type, an `id:` sequence and JSON `data:`. Resume with `Last-Event-ID`. @@ -469,6 +795,112 @@ paths: security: - bearer: [] summary: Event stream (server-sent events) + /v1/groups: + get: + operationId: list-groups + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/Group" + type: + - array + - "null" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: List groups + /v1/groups/{name}: + delete: + description: Pools that still name it stop starting instances. Objects owned by Kubernetes answer 409. + operationId: delete-group + parameters: + - description: Object name + in: path + name: name + required: true + schema: + description: Object name + type: string + responses: + "204": + description: No Content + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Delete a group + get: + operationId: get-group + parameters: + - description: Object name + in: path + name: name + required: true + schema: + description: Object name + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Group" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Get a group + put: + description: Idempotent. Generation increases when the spec changes. Objects owned by Kubernetes answer 409. + operationId: put-group + parameters: + - description: Group name + in: path + name: name + required: true + schema: + description: Group name + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/GroupSpec" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Group" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Create or replace a group /v1/instances: get: operationId: list-instances @@ -696,6 +1128,26 @@ paths: security: - bearer: [] summary: Stop an instance; with players it needs drain or force + /v1/network: + get: + description: Players and capacity summed over all Ready and Allocated proxy instances. The SSE event network.players is published whenever the sum changes. + operationId: get-network + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/NetworkStatus" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Get the network player count /v1/pools: get: operationId: list-pools diff --git a/internal/api/api.go b/internal/api/api.go index c7a862d..6a611d2 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -96,6 +96,7 @@ func build(mux *http.ServeMux, s *server, version string) huma.API { api := humago.New(mux, config) api.UseMiddleware(s.auth.middleware(api)) s.registerPools(api) + s.registerDeclarations(api) s.registerInstances(api) s.registerSelf(api) s.registerTemplates(api) diff --git a/internal/api/declarations.go b/internal/api/declarations.go new file mode 100644 index 0000000..a9ca30e --- /dev/null +++ b/internal/api/declarations.go @@ -0,0 +1,132 @@ +package api + +import ( + "context" + "net/http" + + "github.com/danielgtaylor/huma/v2" + + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +type nameInput struct { + Name string `path:"name" doc:"Object name"` +} + +type environmentOutput struct{ Body model.Environment } +type environmentsOutput struct{ Body []model.Environment } +type putEnvironmentInput struct { + Name string `path:"name" doc:"Environment name"` + Body model.EnvironmentSpec +} + +type groupOutput struct{ Body model.Group } +type groupsOutput struct{ Body []model.Group } +type putGroupInput struct { + Name string `path:"name" doc:"Group name"` + Body model.GroupSpec +} + +type networkOutput struct{ Body model.NetworkStatus } + +const managedNote = " Objects owned by Kubernetes answer 409." + +func (s *server) registerDeclarations(api huma.API) { + huma.Register(api, operation(scopePoolsRead, huma.Operation{ + OperationID: "list-environments", Method: http.MethodGet, Path: "/v1/environments", Summary: "List environments", + }), func(ctx context.Context, _ *struct{}) (*environmentsOutput, error) { + list, err := s.svc.ListEnvironments(ctx) + if err != nil { + return nil, mapError(s.log, err) + } + if list == nil { + list = []model.Environment{} + } + return &environmentsOutput{Body: list}, nil + }) + huma.Register(api, operation(scopePoolsRead, huma.Operation{ + OperationID: "get-environment", Method: http.MethodGet, Path: "/v1/environments/{name}", Summary: "Get an environment", + }), func(ctx context.Context, in *nameInput) (*environmentOutput, error) { + e, err := s.svc.GetEnvironment(ctx, in.Name) + if err != nil { + return nil, mapError(s.log, err) + } + return &environmentOutput{Body: e}, nil + }) + huma.Register(api, operation(scopePoolsWrite, huma.Operation{ + OperationID: "put-environment", Method: http.MethodPut, Path: "/v1/environments/{name}", + Summary: "Create or replace an environment", + Description: "Idempotent. Generation increases when the spec changes." + managedNote, + }), func(ctx context.Context, in *putEnvironmentInput) (*environmentOutput, error) { + e, err := s.svc.PutEnvironment(ctx, in.Name, in.Body) + if err != nil { + return nil, mapError(s.log, err) + } + return &environmentOutput{Body: e}, nil + }) + huma.Register(api, operation(scopePoolsWrite, huma.Operation{ + OperationID: "delete-environment", Method: http.MethodDelete, Path: "/v1/environments/{name}", + Summary: "Delete an environment", Description: "Pools that still name it stop starting instances." + managedNote, + DefaultStatus: http.StatusNoContent, + }), func(ctx context.Context, in *nameInput) (*struct{}, error) { + if err := s.svc.DeleteEnvironment(ctx, in.Name); err != nil { + return nil, mapError(s.log, err) + } + return nil, nil + }) + + huma.Register(api, operation(scopePoolsRead, huma.Operation{ + OperationID: "list-groups", Method: http.MethodGet, Path: "/v1/groups", Summary: "List groups", + }), func(ctx context.Context, _ *struct{}) (*groupsOutput, error) { + list, err := s.svc.ListGroups(ctx) + if err != nil { + return nil, mapError(s.log, err) + } + if list == nil { + list = []model.Group{} + } + return &groupsOutput{Body: list}, nil + }) + huma.Register(api, operation(scopePoolsRead, huma.Operation{ + OperationID: "get-group", Method: http.MethodGet, Path: "/v1/groups/{name}", Summary: "Get a group", + }), func(ctx context.Context, in *nameInput) (*groupOutput, error) { + g, err := s.svc.GetGroup(ctx, in.Name) + if err != nil { + return nil, mapError(s.log, err) + } + return &groupOutput{Body: g}, nil + }) + huma.Register(api, operation(scopePoolsWrite, huma.Operation{ + OperationID: "put-group", Method: http.MethodPut, Path: "/v1/groups/{name}", + Summary: "Create or replace a group", + Description: "Idempotent. Generation increases when the spec changes." + managedNote, + }), func(ctx context.Context, in *putGroupInput) (*groupOutput, error) { + g, err := s.svc.PutGroup(ctx, in.Name, in.Body) + if err != nil { + return nil, mapError(s.log, err) + } + return &groupOutput{Body: g}, nil + }) + huma.Register(api, operation(scopePoolsWrite, huma.Operation{ + OperationID: "delete-group", Method: http.MethodDelete, Path: "/v1/groups/{name}", + Summary: "Delete a group", Description: "Pools that still name it stop starting instances." + managedNote, + DefaultStatus: http.StatusNoContent, + }), func(ctx context.Context, in *nameInput) (*struct{}, error) { + if err := s.svc.DeleteGroup(ctx, in.Name); err != nil { + return nil, mapError(s.log, err) + } + return nil, nil + }) + + huma.Register(api, operation(scopePlayersRead, huma.Operation{ + OperationID: "get-network", Method: http.MethodGet, Path: "/v1/network", Summary: "Get the network player count", + Description: "Players and capacity summed over all Ready and Allocated proxy instances. " + + "The SSE event network.players is published whenever the sum changes.", + }), func(ctx context.Context, _ *struct{}) (*networkOutput, error) { + n, err := s.svc.Network(ctx) + if err != nil { + return nil, mapError(s.log, err) + } + return &networkOutput{Body: n}, nil + }) +} diff --git a/internal/api/declarations_test.go b/internal/api/declarations_test.go new file mode 100644 index 0000000..59894b4 --- /dev/null +++ b/internal/api/declarations_test.go @@ -0,0 +1,103 @@ +package api + +import ( + "encoding/json" + "net/http" + "testing" + + "github.com/OneLiteFeatherNET/grus/internal/controller" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +const validEnvironmentBody = `{"kind":"jvm","jvm":{"jar":"paper.jar","flags":["-XX:+UseG1GC"]},"readiness":"tcp","gracePeriod":"45s"}` + +func TestAdminPutsEnvironmentAndGetsItBack(t *testing.T) { + fx := newFixture(t, Config{}, nil) + rec := fx.call(t, http.MethodPut, "/v1/environments/paper", adminToken, "application/json", validEnvironmentBody) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body %s", rec.Code, rec.Body) + } + var env model.Environment + if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil { + t.Fatalf("decode environment: %v", err) + } + if env.Name != "paper" || env.Source != model.SourceAPI || fx.svc.envSpec.JVM == nil || fx.svc.envSpec.JVM.Jar != "paper.jar" { + t.Errorf("environment = %+v, spec passed to service = %+v", env, fx.svc.envSpec) + } + if got := fx.call(t, http.MethodGet, "/v1/environments/paper", adminToken, "", ""); got.Code != http.StatusOK { + t.Errorf("get status = %d, want 200", got.Code) + } + if got := fx.call(t, http.MethodGet, "/v1/environments", adminToken, "", ""); got.Body.String() != "[]\n" { + t.Errorf("empty list body = %q, want a top-level empty array", got.Body.String()) + } +} + +func TestPutGroupAndDeleteRoutes(t *testing.T) { + fx := newFixture(t, Config{}, nil) + rec := fx.call(t, http.MethodPut, "/v1/groups/base", adminToken, "application/json", `{"env":{"A":"1"}}`) + if rec.Code != http.StatusOK || fx.svc.groupName != "base" { + t.Fatalf("put group status = %d name = %q; body %s", rec.Code, fx.svc.groupName, rec.Body) + } + if got := fx.call(t, http.MethodDelete, "/v1/groups/base", adminToken, "", ""); got.Code != http.StatusNoContent { + t.Errorf("delete group status = %d, want 204", got.Code) + } + if got := fx.call(t, http.MethodDelete, "/v1/environments/paper", adminToken, "", ""); got.Code != http.StatusNoContent || fx.svc.deletedEnv != "paper" { + t.Errorf("delete environment status = %d deleted = %q", got.Code, fx.svc.deletedEnv) + } +} + +func TestKubernetesManagedObjectReturns409(t *testing.T) { + fx := newFixture(t, Config{}, nil) + fx.svc.putErr = controller.ErrManagedElsewhere + for _, tc := range []struct{ method, path, body string }{ + {http.MethodPut, "/v1/environments/paper", validEnvironmentBody}, + {http.MethodPut, "/v1/groups/base", `{}`}, + {http.MethodPut, "/v1/pools/lobby", validPoolBody}, + {http.MethodDelete, "/v1/groups/base", ""}, + } { + ct := "" + if tc.body != "" { + ct = "application/json" + } + if rec := fx.call(t, tc.method, tc.path, adminToken, ct, tc.body); rec.Code != http.StatusConflict { + t.Errorf("%s %s status = %d, want 409; body %s", tc.method, tc.path, rec.Code, rec.Body) + } + } +} + +func TestInvalidEnvironmentReturns422(t *testing.T) { + fx := newFixture(t, Config{}, nil) + fx.svc.putErr = &controller.ValidationError{Kind: "environment", Fields: []model.FieldError{{Field: "kind", Message: "must be jvm, native or container"}}} + rec := fx.call(t, http.MethodPut, "/v1/environments/paper", adminToken, "application/json", `{"kind":"wasm"}`) + if rec.Code != http.StatusUnprocessableEntity { + t.Fatalf("status = %d, want 422; body %s", rec.Code, rec.Body) + } +} + +func TestInstanceTokenCannotWriteEnvironments(t *testing.T) { + fx := newFixture(t, Config{}, nil) + rec := fx.call(t, http.MethodPut, "/v1/environments/paper", gameToken, "application/json", validEnvironmentBody) + if rec.Code != http.StatusForbidden { + t.Fatalf("status = %d, want 403", rec.Code) + } +} + +func TestNetworkIsReadableByProxyButNotByGameInstances(t *testing.T) { + fx := newFixture(t, Config{}, nil) + fx.svc.network = model.NetworkStatus{Players: 12, MaxPlayers: 200, Proxies: 2} + + rec := fx.call(t, http.MethodGet, "/v1/network", proxyToken, "", "") + if rec.Code != http.StatusOK { + t.Fatalf("proxy status = %d, want 200; body %s", rec.Code, rec.Body) + } + var got model.NetworkStatus + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil || got != fx.svc.network { + t.Errorf("network = %+v err=%v, want %+v", got, err, fx.svc.network) + } + if rec := fx.call(t, http.MethodGet, "/v1/network", gameToken, "", ""); rec.Code != http.StatusForbidden { + t.Errorf("game instance status = %d, want 403", rec.Code) + } + if rec := fx.call(t, http.MethodGet, "/v1/network", adminToken, "", ""); rec.Code != http.StatusOK { + t.Errorf("admin status = %d, want 200", rec.Code) + } +} diff --git a/internal/api/errors.go b/internal/api/errors.go index d66ba45..a054219 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -26,7 +26,7 @@ func mapError(log *slog.Logger, err error) huma.StatusError { return huma.Error422UnprocessableEntity(ve.Error(), details...) case errors.Is(err, controller.ErrNotFound), errors.Is(err, store.ErrNotFound), errors.Is(err, templates.ErrNotFound): return huma.Error404NotFound("not found") - case errors.Is(err, controller.ErrHasPlayers), errors.Is(err, controller.ErrInvalidState), errors.Is(err, controller.ErrLimit): + case errors.Is(err, controller.ErrHasPlayers), errors.Is(err, controller.ErrInvalidState), errors.Is(err, controller.ErrLimit), errors.Is(err, controller.ErrManagedElsewhere): return huma.Error409Conflict(err.Error()) default: log.Error("api: request failed", "err", err) diff --git a/internal/api/fakes_test.go b/internal/api/fakes_test.go index b9e8f63..ee8b92a 100644 --- a/internal/api/fakes_test.go +++ b/internal/api/fakes_test.go @@ -36,6 +36,13 @@ type fakeService struct { putName string putSpec model.PoolSpec + env model.Environment + envName string + envSpec model.EnvironmentSpec + deletedEnv string + groupName string + network model.NetworkStatus + listFilter store.InstanceFilter listed []model.Instance @@ -78,6 +85,43 @@ func (f *fakeService) SetMaintenance(_ context.Context, name string, enabled boo return model.Pool{Name: name, Maintenance: enabled}, nil } +func (f *fakeService) PutEnvironment(_ context.Context, name string, spec model.EnvironmentSpec) (model.Environment, error) { + f.envName, f.envSpec = name, spec + if f.putErr != nil { + return model.Environment{}, f.putErr + } + return model.Environment{Name: name, Spec: spec, Source: model.SourceAPI, Generation: 1}, nil +} + +func (f *fakeService) GetEnvironment(context.Context, string) (model.Environment, error) { + return f.env, nil +} + +func (f *fakeService) ListEnvironments(context.Context) ([]model.Environment, error) { return nil, nil } + +func (f *fakeService) DeleteEnvironment(_ context.Context, name string) error { + f.deletedEnv = name + return f.putErr +} + +func (f *fakeService) PutGroup(_ context.Context, name string, spec model.GroupSpec) (model.Group, error) { + f.groupName = name + if f.putErr != nil { + return model.Group{}, f.putErr + } + return model.Group{Name: name, Spec: spec, Source: model.SourceAPI, Generation: 1}, nil +} + +func (f *fakeService) GetGroup(context.Context, string) (model.Group, error) { + return model.Group{}, nil +} + +func (f *fakeService) ListGroups(context.Context) ([]model.Group, error) { return nil, nil } + +func (f *fakeService) DeleteGroup(context.Context, string) error { return f.putErr } + +func (f *fakeService) Network(context.Context) (model.NetworkStatus, error) { return f.network, nil } + func (f *fakeService) ListInstances(_ context.Context, filter store.InstanceFilter) ([]model.Instance, error) { f.listFilter = filter return f.listed, nil diff --git a/internal/controller/controller.go b/internal/controller/controller.go index 1a30ad5..bdd0171 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -57,6 +57,8 @@ type Controller struct { trigger chan struct{} belowSince map[string]*time.Time // per pool: when desired < active was first seen 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 } // New builds a controller. Call Adopt (or Run, which adopts first) before reconciling. @@ -87,6 +89,7 @@ func New(cfg Config, st store.Store, drv driver.Driver, tpl templates.Store, pub trigger: make(chan struct{}, 1), belowSince: make(map[string]*time.Time), lastPublished: make(map[string]time.Time), + resolveWarned: make(map[string]string), } } @@ -208,6 +211,9 @@ func (c *Controller) apply(ctx context.Context, inst model.Instance, in state.In Address: next.Address, Reason: reason, }) + if next.Role == model.RoleProxy { + c.publishNetwork(ctx) + } return next, nil } @@ -258,7 +264,12 @@ func (c *Controller) lifecycleOf(ctx context.Context, pool string) model.Lifecyc if err != nil { return model.PoolSpec{}.WithDefaults().Lifecycle } - return p.Spec.WithDefaults().Lifecycle + lc := p.Spec.WithDefaults().Lifecycle + if eff, err := c.effective(ctx, p.Spec); err == nil { + lc.StopCommand = eff.StopCommand + lc.GracePeriod = eff.GracePeriod + } + return lc } // createInstance records a new Requested instance, resolves templates, schedules it and starts it through @@ -267,6 +278,12 @@ func (c *Controller) createInstance(ctx context.Context, pool model.Pool) (model spec := pool.Spec.WithDefaults() now := c.clock.Now() + eff, err := c.effective(ctx, pool.Spec) + c.noteResolve(pool.Name, err) + if err != nil { + return model.Instance{}, err + } + token, err := newToken() if err != nil { return model.Instance{}, err @@ -279,7 +296,7 @@ func (c *Controller) createInstance(ctx context.Context, pool model.Pool) (model return model.Instance{}, err } - resolved, err := c.resolveTemplates(ctx, spec.Templates) + resolved, err := c.resolveTemplates(ctx, eff.Templates) if err != nil { return c.apply(ctx, inst, state.InFailed, "template: "+err.Error()) } @@ -292,7 +309,8 @@ func (c *Controller) createInstance(ctx context.Context, pool model.Pool) (model Instance: inst, Pool: model.Pool{Name: pool.Name, Spec: spec, Generation: pool.Generation}, Token: token, - Env: instanceEnv(c.cfg.PublicURL, spec, inst), + Effective: eff, + Env: instanceEnv(c.cfg.PublicURL, spec, eff, inst), Templates: resolved, }) if err != nil { @@ -377,16 +395,16 @@ func (c *Controller) resolveTemplates(ctx context.Context, refs []model.Template } // instanceEnv builds the GRUS_* variables on top of the pool env. The token is added by the driver. -func instanceEnv(publicURL string, spec model.PoolSpec, inst model.Instance) map[string]string { - env := make(map[string]string, len(spec.Env)+6) - for k, v := range spec.Env { +func instanceEnv(publicURL string, spec model.PoolSpec, eff model.EffectiveSpec, inst model.Instance) map[string]string { + env := make(map[string]string, len(eff.Env)+6) + for k, v := range eff.Env { env[k] = v } env["GRUS_URL"] = publicURL env["GRUS_INSTANCE"] = inst.ID env["GRUS_POOL"] = inst.Pool env["GRUS_ROLE"] = string(inst.Role) - env["GRUS_PORT"] = fmt.Sprint(spec.Port) + env["GRUS_PORT"] = fmt.Sprint(eff.Port) if spec.Scaling.Capacity > 0 { env["GRUS_MAX_PLAYERS"] = fmt.Sprint(spec.Scaling.Capacity) } diff --git a/internal/controller/declarations.go b/internal/controller/declarations.go new file mode 100644 index 0000000..9981bfc --- /dev/null +++ b/internal/controller/declarations.go @@ -0,0 +1,239 @@ +package controller + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/OneLiteFeatherNET/grus/internal/model" + "github.com/OneLiteFeatherNET/grus/internal/store" +) + +var _ Applier = (*Controller)(nil) + +// checkOwner rejects a change by source when the stored object belongs to Kubernetes. +func checkOwner(stored, source model.Source, kind, name string) error { + if stored == model.SourceKubernetes && source != model.SourceKubernetes { + return fmt.Errorf("%w: %s %q", ErrManagedElsewhere, kind, name) + } + return nil +} + +func validateName(name string) []model.FieldError { + if poolNameRE.MatchString(name) { + return nil + } + return []model.FieldError{{Field: "name", Message: "must match ^[a-z0-9][a-z0-9-]{0,30}$"}} +} + +// PutEnvironment validates and stores an environment owned by the api. +func (c *Controller) PutEnvironment(ctx context.Context, name string, spec model.EnvironmentSpec) (model.Environment, error) { + return c.ApplyEnvironment(ctx, model.SourceAPI, name, spec) +} + +// ApplyEnvironment is PutEnvironment for a declaration owned by source; see Applier. +func (c *Controller) ApplyEnvironment(ctx context.Context, source model.Source, name string, spec model.EnvironmentSpec) (model.Environment, error) { + fields := append(validateName(name), spec.WithDefaults().Validate()...) + if len(fields) > 0 { + return model.Environment{}, &ValidationError{Kind: "environment", Fields: fields} + } + c.mu.Lock() + defer c.mu.Unlock() + if cur, err := c.st.GetEnvironment(ctx, name); err == nil { + if err := checkOwner(cur.Source, source, "environment", name); err != nil { + return model.Environment{}, err + } + } + env, changed, err := c.st.PutEnvironment(ctx, name, spec, source) + if err != nil { + return model.Environment{}, mapErr(err) + } + if changed { + c.pub.Publish(model.EventPoolUpdated, map[string]any{"environment": name, "generation": env.Generation}) + c.Trigger() + } + return env, nil +} + +func (c *Controller) GetEnvironment(ctx context.Context, name string) (model.Environment, error) { + e, err := c.st.GetEnvironment(ctx, name) + return e, mapErr(err) +} + +func (c *Controller) ListEnvironments(ctx context.Context) ([]model.Environment, error) { + es, err := c.st.ListEnvironments(ctx) + return es, mapErr(err) +} + +// DeleteEnvironment removes an environment owned by the api. Pools that still name it stop starting instances. +func (c *Controller) DeleteEnvironment(ctx context.Context, name string) error { + return c.RemoveEnvironment(ctx, model.SourceAPI, name) +} + +// RemoveEnvironment is DeleteEnvironment on behalf of source; see Applier. +func (c *Controller) RemoveEnvironment(ctx context.Context, source model.Source, name string) error { + c.mu.Lock() + defer c.mu.Unlock() + cur, err := c.st.GetEnvironment(ctx, name) + if err != nil { + return mapErr(err) + } + if err := checkOwner(cur.Source, source, "environment", name); err != nil { + return err + } + return mapErr(c.st.DeleteEnvironment(ctx, name)) +} + +// PutGroup validates and stores a group owned by the api. +func (c *Controller) PutGroup(ctx context.Context, name string, spec model.GroupSpec) (model.Group, error) { + return c.ApplyGroup(ctx, model.SourceAPI, name, spec) +} + +// ApplyGroup is PutGroup for a declaration owned by source; see Applier. +func (c *Controller) ApplyGroup(ctx context.Context, source model.Source, name string, spec model.GroupSpec) (model.Group, error) { + fields := append(validateName(name), spec.Validate()...) + if len(fields) > 0 { + return model.Group{}, &ValidationError{Kind: "group", Fields: fields} + } + c.mu.Lock() + defer c.mu.Unlock() + if cur, err := c.st.GetGroup(ctx, name); err == nil { + if err := checkOwner(cur.Source, source, "group", name); err != nil { + return model.Group{}, err + } + } + g, changed, err := c.st.PutGroup(ctx, name, spec, source) + if err != nil { + return model.Group{}, mapErr(err) + } + if changed { + c.pub.Publish(model.EventPoolUpdated, map[string]any{"group": name, "generation": g.Generation}) + c.Trigger() + } + return g, nil +} + +func (c *Controller) GetGroup(ctx context.Context, name string) (model.Group, error) { + g, err := c.st.GetGroup(ctx, name) + return g, mapErr(err) +} + +func (c *Controller) ListGroups(ctx context.Context) ([]model.Group, error) { + gs, err := c.st.ListGroups(ctx) + return gs, mapErr(err) +} + +// DeleteGroup removes a group owned by the api. Pools that still name it stop starting instances. +func (c *Controller) DeleteGroup(ctx context.Context, name string) error { + return c.RemoveGroup(ctx, model.SourceAPI, name) +} + +// RemoveGroup is DeleteGroup on behalf of source; see Applier. +func (c *Controller) RemoveGroup(ctx context.Context, source model.Source, name string) error { + c.mu.Lock() + defer c.mu.Unlock() + cur, err := c.st.GetGroup(ctx, name) + if err != nil { + return mapErr(err) + } + if err := checkOwner(cur.Source, source, "group", name); err != nil { + return err + } + return mapErr(c.st.DeleteGroup(ctx, name)) +} + +// effective resolves a pool spec against its stored environment and groups. Unknown references and specs +// that cannot be run come back as a *ValidationError. +func (c *Controller) effective(ctx context.Context, spec model.PoolSpec) (model.EffectiveSpec, error) { + var env *model.EnvironmentSpec + var missing []model.FieldError + if spec.Environment != "" { + e, err := c.st.GetEnvironment(ctx, spec.Environment) + switch { + case err == nil: + env = &e.Spec + case errors.Is(err, store.ErrNotFound): + missing = append(missing, model.FieldError{Field: "environment", Message: fmt.Sprintf("environment %q does not exist", spec.Environment)}) + default: + return model.EffectiveSpec{}, err + } + } + groups := make([]model.GroupSpec, 0, len(spec.Groups)) + for i, name := range spec.Groups { + g, err := c.st.GetGroup(ctx, name) + switch { + case err == nil: + groups = append(groups, g.Spec) + case errors.Is(err, store.ErrNotFound): + missing = append(missing, model.FieldError{Field: fmt.Sprintf("groups[%d]", i), Message: fmt.Sprintf("group %q does not exist", name)}) + default: + return model.EffectiveSpec{}, err + } + } + if len(missing) > 0 { + return model.EffectiveSpec{}, &ValidationError{Fields: missing} + } + eff, errs := model.ResolvePool(spec, env, groups) + if len(errs) > 0 { + return model.EffectiveSpec{}, &ValidationError{Fields: errs} + } + return eff, nil +} + +// noteResolve records why a pool cannot start instances, once per distinct reason, as log line and +// pool.condition event. A successful resolve (empty reason) clears the memory. +func (c *Controller) noteResolve(pool string, err error) { + if err == nil { + delete(c.resolveWarned, pool) + return + } + var ve *ValidationError + msg := err.Error() + if errors.As(err, &ve) { + parts := make([]string, 0, len(ve.Fields)) + for _, f := range ve.Fields { + parts = append(parts, f.Field+": "+f.Message) + } + msg = strings.Join(parts, "; ") + } + if c.resolveWarned[pool] == msg { + return + } + c.resolveWarned[pool] = msg + c.log.Warn("pool cannot start instances", "pool", pool, "reason", msg) + c.pub.Publish(model.EventPoolCondition, model.PoolConditionData{Pool: pool, Type: "Unresolvable", Message: msg}) +} + +// Network sums the players of all Ready and Allocated proxy instances. +func (c *Controller) Network(ctx context.Context) (model.NetworkStatus, error) { + insts, err := c.st.ListInstances(ctx, store.InstanceFilter{Role: model.RoleProxy}) + if err != nil { + return model.NetworkStatus{}, mapErr(err) + } + var n model.NetworkStatus + for _, inst := range insts { + if inst.State != model.StateReady && inst.State != model.StateAllocated { + continue + } + n.Proxies++ + n.Players += inst.Players + n.MaxPlayers += inst.MaxPlayers + } + return n, nil +} + +// publishNetwork emits network.players when the summed count differs from the last published one. +// Callers hold c.mu and call it after a proxy's players or state changed. +func (c *Controller) publishNetwork(ctx context.Context) { + n, err := c.Network(ctx) + if err != nil { + c.log.Error("compute network player count", "error", err) + return + } + if n == c.lastNetwork { + return + } + c.lastNetwork = n + c.pub.Publish(model.EventNetworkPlayers, n) +} diff --git a/internal/controller/declarations_test.go b/internal/controller/declarations_test.go new file mode 100644 index 0000000..78ebf6d --- /dev/null +++ b/internal/controller/declarations_test.go @@ -0,0 +1,289 @@ +package controller + +import ( + "errors" + "reflect" + "testing" + + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +func paperEnv() model.EnvironmentSpec { + return model.EnvironmentSpec{ + Kind: model.KindJVM, Image: "registry.test/paper:1", Port: 25570, + JVM: &model.JVM{Jar: "paper.jar"}, Env: map[string]string{"EULA": "true", "TIER": "env"}, + StopCommand: "stop", + } +} + +func v2Spec() model.PoolSpec { + s := dynamicSpec(1, 0) + s.Driver, s.Image = "", "" + s.Placement = model.Placement{Driver: "kubernetes"} + s.Environment = "paper" + s.Groups = []string{"base"} + s.Env = map[string]string{"TIER": "pool"} + return s +} + +func (f *fixture) putEnv(name string, spec model.EnvironmentSpec) { + f.t.Helper() + if _, err := f.c.PutEnvironment(f.ctx, name, spec); err != nil { + f.t.Fatalf("put environment %s: %v", name, err) + } +} + +func (f *fixture) putGroup(name string, spec model.GroupSpec) { + f.t.Helper() + if _, err := f.c.PutGroup(f.ctx, name, spec); err != nil { + f.t.Fatalf("put group %s: %v", name, err) + } +} + +func TestPoolWithEnvironmentAndGroupStartsWithTheEffectiveSpec(t *testing.T) { + f := newFixture(t, Config{}) + f.putEnv("paper", paperEnv()) + f.putGroup("base", model.GroupSpec{Env: map[string]string{"REGION": "fr"}, Labels: map[string]string{"team": "olf"}}) + f.putPool("lobby", v2Spec()) + + f.reconcile() + + started := f.drv.Started() + if len(started) != 1 { + t.Fatalf("started = %d, want 1", len(started)) + } + eff := started[0].Effective + if eff.Image != "registry.test/paper:1" || eff.Port != 25570 || eff.StopCommand != "stop" { + t.Errorf("effective = %+v, want image, port and stop command from the environment", eff) + } + wantEnv := map[string]string{"EULA": "true", "TIER": "pool", "REGION": "fr"} + if !reflect.DeepEqual(eff.Env, wantEnv) { + t.Errorf("effective env = %v, want %v", eff.Env, wantEnv) + } + if eff.Labels["team"] != "olf" { + t.Errorf("effective labels = %v, want team=olf from the group", eff.Labels) + } + if got := started[0].Env["GRUS_PORT"]; got != "25570" { + t.Errorf("GRUS_PORT = %q, want 25570 from the environment", got) + } + if got := started[0].Env["REGION"]; got != "fr" { + t.Errorf("instance env REGION = %q, want fr from the group", got) + } +} + +func TestPoolWithUnknownEnvironmentStartsNothingAndReportsOnce(t *testing.T) { + f := newFixture(t, Config{}) + f.putGroup("base", model.GroupSpec{}) + f.putPool("lobby", v2Spec()) + + f.reconcile() + f.reconcile() + + if n := len(f.drv.Started()); n != 0 { + t.Fatalf("started = %d, want 0 while the environment is missing", n) + } + if n := f.pub.count(model.EventPoolCondition); n != 1 { + t.Errorf("pool.condition events = %d, want 1 (reported once per reason)", n) + } + + f.putEnv("paper", paperEnv()) + f.reconcile() + if n := len(f.drv.Started()); n != 1 { + t.Errorf("started = %d after creating the environment, want 1", n) + } +} + +func TestPoolWithUnknownGroupStartsNothing(t *testing.T) { + f := newFixture(t, Config{}) + f.putEnv("paper", paperEnv()) + f.putPool("lobby", v2Spec()) + + f.reconcile() + + if n := len(f.drv.Started()); n != 0 { + t.Fatalf("started = %d, want 0 while group base is missing", n) + } + if n := f.pub.count(model.EventPoolCondition); n != 1 { + t.Errorf("pool.condition events = %d, want 1", n) + } +} + +func TestV1PoolStillStartsWithItsInlineFields(t *testing.T) { + f := newFixture(t, Config{}) + spec := dynamicSpec(1, 0) + spec.Port = 25999 + f.putPool("lobby", spec) + + f.reconcile() + + started := f.drv.Started() + if len(started) != 1 || started[0].Effective.Image != "registry.test/lobby:1" || started[0].Env["GRUS_PORT"] != "25999" { + t.Fatalf("v1 pool did not start with its inline fields: %+v", started) + } +} + +func TestAPICannotChangeOrDeleteKubernetesManagedObjects(t *testing.T) { + f := newFixture(t, Config{}) + if _, err := f.c.ApplyPool(f.ctx, model.SourceKubernetes, "lobby", dynamicSpec(1, 0)); err != nil { + t.Fatalf("apply from kubernetes: %v", err) + } + if _, err := f.c.ApplyEnvironment(f.ctx, model.SourceKubernetes, "paper", paperEnv()); err != nil { + t.Fatalf("apply environment from kubernetes: %v", err) + } + if _, err := f.c.ApplyGroup(f.ctx, model.SourceKubernetes, "base", model.GroupSpec{}); err != nil { + t.Fatalf("apply group from kubernetes: %v", err) + } + + checks := map[string]error{ + "put pool": second(f.c.PutPool(f.ctx, "lobby", dynamicSpec(2, 0))), + "delete pool": f.c.DeletePool(f.ctx, "lobby", false), + "put environment": second(f.c.PutEnvironment(f.ctx, "paper", paperEnv())), + "delete environment": f.c.DeleteEnvironment(f.ctx, "paper"), + "put group": second(f.c.PutGroup(f.ctx, "base", model.GroupSpec{})), + "delete group": f.c.DeleteGroup(f.ctx, "base"), + "file source": second(f.c.ApplyPool(f.ctx, model.SourceFile, "lobby", dynamicSpec(2, 0))), + } + for name, err := range checks { + if !errors.Is(err, ErrManagedElsewhere) { + t.Errorf("%s: error = %v, want ErrManagedElsewhere", name, err) + } + } + if p, _ := f.st.GetPool(f.ctx, "lobby"); p.Spec.Scaling.Min != 1 || p.Source != model.SourceKubernetes { + t.Errorf("pool changed despite the rejection: %+v", p) + } + + if _, err := f.c.ApplyPool(f.ctx, model.SourceKubernetes, "lobby", dynamicSpec(2, 0)); err != nil { + t.Errorf("kubernetes source updating its own pool: %v", err) + } + if err := f.c.RemoveEnvironment(f.ctx, model.SourceKubernetes, "paper"); err != nil { + t.Errorf("kubernetes source removing its own environment: %v", err) + } + if err := f.c.RemoveGroup(f.ctx, model.SourceKubernetes, "base"); err != nil { + t.Errorf("kubernetes source removing its own group: %v", err) + } + if err := f.c.RemovePool(f.ctx, model.SourceKubernetes, "lobby", false); err != nil { + t.Errorf("kubernetes source removing its own pool: %v", err) + } +} + +func TestAPIObjectsAreMutableThroughTheAPI(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("lobby", dynamicSpec(1, 0)) + f.putEnv("paper", paperEnv()) + + if _, err := f.c.PutPool(f.ctx, "lobby", dynamicSpec(2, 0)); err != nil { + t.Errorf("put own pool: %v", err) + } + if err := f.c.DeleteEnvironment(f.ctx, "paper"); err != nil { + t.Errorf("delete own environment: %v", err) + } + if _, err := f.c.GetEnvironment(f.ctx, "paper"); !errors.Is(err, ErrNotFound) { + t.Errorf("get deleted environment = %v, want ErrNotFound", err) + } + if err := f.c.DeleteGroup(f.ctx, "nope"); !errors.Is(err, ErrNotFound) { + t.Errorf("delete missing group = %v, want ErrNotFound", err) + } +} + +func TestPutEnvironmentAndGroupRejectInvalidSpecs(t *testing.T) { + f := newFixture(t, Config{}) + var ve *ValidationError + if _, err := f.c.PutEnvironment(f.ctx, "paper", model.EnvironmentSpec{Kind: "wasm"}); !errors.As(err, &ve) || ve.Kind != "environment" { + t.Errorf("invalid environment error = %v, want ValidationError of kind environment", err) + } + bad := model.GroupSpec{Templates: []model.TemplateRef{{Name: "x"}}} + if _, err := f.c.PutGroup(f.ctx, "Bad_Name", bad); !errors.As(err, &ve) || len(ve.Fields) != 2 { + t.Errorf("invalid group error = %v, want name and template field errors", err) + } +} + +func proxySpec() model.PoolSpec { + s := dynamicSpec(2, 0) + s.Role = model.RoleProxy + return s +} + +func (f *fixture) networkEvents() []model.NetworkStatus { + var out []model.NetworkStatus + for i, typ := range f.pub.types { + if typ == model.EventNetworkPlayers { + out = append(out, f.pub.data[i].(model.NetworkStatus)) + } + } + return out +} + +func TestNetworkSumsPlayersOfReadyAndAllocatedProxies(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("proxy", proxySpec()) + f.putPool("lobby", dynamicSpec(1, 0)) + f.reconcile() + for _, s := range f.drv.Started() { + f.bringUp(s.Instance.ID, "10.0.0.1:25565") + } + var proxies []string + for _, inst := range f.instancesOf("proxy") { + proxies = append(proxies, inst.ID) + } + f.c.SelfStatus(f.ctx, proxies[0], StatusUpdate{Players: 7, MaxPlayers: 100}) + f.c.SelfStatus(f.ctx, proxies[1], StatusUpdate{Players: 5, MaxPlayers: 100}) + for _, inst := range f.instancesOf("lobby") { + f.c.SelfStatus(f.ctx, inst.ID, StatusUpdate{Players: 99}) + } + + got, err := f.c.Network(f.ctx) + if err != nil { + t.Fatalf("Network: %v", err) + } + if want := (model.NetworkStatus{Players: 12, MaxPlayers: 200, Proxies: 2}); got != want { + t.Errorf("network = %+v, want %+v (game instances do not count)", got, want) + } +} + +func TestNetworkPlayersEventIsPublishedOnlyOnChange(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("proxy", proxySpec()) + f.reconcile() + var ids []string + for _, s := range f.drv.Started() { + f.bringUp(s.Instance.ID, "10.0.0.1:25565") + ids = append(ids, s.Instance.ID) + } + base := len(f.networkEvents()) + + f.c.SelfStatus(f.ctx, ids[0], StatusUpdate{Players: 3, MaxPlayers: 50}) + f.c.SelfStatus(f.ctx, ids[0], StatusUpdate{Players: 3, MaxPlayers: 50}) + f.c.SelfStatus(f.ctx, ids[1], StatusUpdate{Players: 4, MaxPlayers: 50}) + + events := f.networkEvents() + if len(events)-base != 2 { + t.Fatalf("network.players events = %d, want 2 (unchanged status must not publish)", len(events)-base) + } + if last := events[len(events)-1]; last.Players != 7 || last.Proxies != 2 { + t.Errorf("last event = %+v, want 7 players on 2 proxies", last) + } +} + +func TestNetworkPlayersEventFollowsProxyStateChanges(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("proxy", proxySpec()) + f.reconcile() + var ids []string + for _, s := range f.drv.Started() { + f.bringUp(s.Instance.ID, "10.0.0.1:25565") + ids = append(ids, s.Instance.ID) + } + f.c.SelfStatus(f.ctx, ids[0], StatusUpdate{Players: 3, MaxPlayers: 50}) + f.c.SelfStatus(f.ctx, ids[1], StatusUpdate{Players: 4, MaxPlayers: 50}) + + if _, err := f.c.StopInstance(f.ctx, ids[0], StopOptions{Force: true}); err != nil { + t.Fatalf("stop: %v", err) + } + + events := f.networkEvents() + if last := events[len(events)-1]; last.Players != 4 || last.Proxies != 1 { + t.Errorf("last event = %+v, want 4 players on 1 proxy after a proxy stopped", last) + } +} + +func second[T any](_ T, err error) error { return err } diff --git a/internal/controller/reconcile.go b/internal/controller/reconcile.go index ba1345b..a0b0387 100644 --- a/internal/controller/reconcile.go +++ b/internal/controller/reconcile.go @@ -175,6 +175,10 @@ func (c *Controller) ReconcileOnce(ctx context.Context) error { break } if _, err := c.createInstance(ctx, p); err != nil { + var ve *ValidationError + if errors.As(err, &ve) { + break // unknown environment or group: reported once as pool.condition, retried next cycle + } errs = append(errs, fmt.Errorf("create instance of pool %s: %w", p.Name, err)) break } @@ -244,11 +248,11 @@ func (c *Controller) reconcileInstance(ctx context.Context, inst model.Instance, } case model.StateUnhealthy: if spec.Mode == model.ModeDynamic && now.Sub(inst.StateSince) > lc.HeartbeatTimeout.D() { - return c.stop(ctx, inst, state.InStop, "unhealthy", lc) + return c.stop(ctx, inst, state.InStop, "unhealthy", c.lifecycleOf(ctx, inst.Pool)) } case model.StateDraining: if inst.Players == 0 || now.Sub(inst.StateSince) > spec.Scaling.DrainTimeout.D() { - return c.stop(ctx, inst, state.InStop, "drained", lc) + return c.stop(ctx, inst, state.InStop, "drained", c.lifecycleOf(ctx, inst.Pool)) } } return inst, nil diff --git a/internal/controller/service.go b/internal/controller/service.go index 85fca54..aa527a2 100644 --- a/internal/controller/service.go +++ b/internal/controller/service.go @@ -20,12 +20,23 @@ var ( ErrNotFound = errors.New("not found") // ErrLimit: the namespace instance limit would be exceeded (HTTP 409). ErrLimit = errors.New("instance limit reached") + // ErrManagedElsewhere: the object is owned by Kubernetes and cannot be changed through the API (HTTP 409). + ErrManagedElsewhere = errors.New("managed by kubernetes") ) -// ValidationError carries field errors of a pool spec (HTTP 422). -type ValidationError struct{ Fields []model.FieldError } +// ValidationError carries field errors of a pool, environment or group spec (HTTP 422). +type ValidationError struct { + // Kind names the invalid object ("pool", "environment", "group"); empty means pool. + Kind string + Fields []model.FieldError +} -func (e *ValidationError) Error() string { return "invalid pool spec" } +func (e *ValidationError) Error() string { + if e.Kind == "" { + return "invalid pool spec" + } + return "invalid " + e.Kind + " spec" +} // StatusUpdate is the body of PUT /v1/self/status (and the admin debug variant). type StatusUpdate struct { @@ -49,6 +60,19 @@ type Service interface { DeletePool(ctx context.Context, name string, drain bool) error SetMaintenance(ctx context.Context, name string, enabled bool) (model.Pool, error) + PutEnvironment(ctx context.Context, name string, spec model.EnvironmentSpec) (model.Environment, error) + GetEnvironment(ctx context.Context, name string) (model.Environment, error) + ListEnvironments(ctx context.Context) ([]model.Environment, error) + DeleteEnvironment(ctx context.Context, name string) error + + PutGroup(ctx context.Context, name string, spec model.GroupSpec) (model.Group, error) + GetGroup(ctx context.Context, name string) (model.Group, error) + ListGroups(ctx context.Context) ([]model.Group, error) + DeleteGroup(ctx context.Context, name string) error + + // Network sums the players of all Ready and Allocated proxy instances. + Network(ctx context.Context) (model.NetworkStatus, error) + ListInstances(ctx context.Context, f store.InstanceFilter) ([]model.Instance, error) GetInstance(ctx context.Context, id string) (model.Instance, error) CreateInstance(ctx context.Context, pool string) (model.Instance, error) @@ -63,3 +87,15 @@ type Service interface { SelfAllocate(ctx context.Context, id string) (model.Instance, error) SelfShutdown(ctx context.Context, id string) (model.Instance, error) } + +// Applier is the entry point for declaration sources other than the REST API (the Kubernetes CRD watcher, +// declaration files). The source owns what it applies: an object whose stored source is kubernetes can only +// be changed or removed by the kubernetes source, everything else fails with ErrManagedElsewhere. +type Applier interface { + ApplyPool(ctx context.Context, source model.Source, name string, spec model.PoolSpec) (model.Pool, error) + RemovePool(ctx context.Context, source model.Source, name string, drain bool) error + ApplyEnvironment(ctx context.Context, source model.Source, name string, spec model.EnvironmentSpec) (model.Environment, error) + RemoveEnvironment(ctx context.Context, source model.Source, name string) error + ApplyGroup(ctx context.Context, source model.Source, name string, spec model.GroupSpec) (model.Group, error) + RemoveGroup(ctx context.Context, source model.Source, name string) error +} diff --git a/internal/controller/service_impl.go b/internal/controller/service_impl.go index 138287b..43408a8 100644 --- a/internal/controller/service_impl.go +++ b/internal/controller/service_impl.go @@ -30,8 +30,13 @@ func mapErr(err error) error { return err } -// PutPool validates and stores a pool. The spec is stored as sent; defaults apply when it is used. +// PutPool validates and stores a pool owned by the api. The spec is stored as sent; defaults apply when it is used. func (c *Controller) PutPool(ctx context.Context, name string, spec model.PoolSpec) (model.Pool, error) { + return c.ApplyPool(ctx, model.SourceAPI, name, spec) +} + +// ApplyPool is PutPool for a declaration owned by source; see Applier. +func (c *Controller) ApplyPool(ctx context.Context, source model.Source, name string, spec model.PoolSpec) (model.Pool, error) { var fields []model.FieldError if !poolNameRE.MatchString(name) { fields = append(fields, model.FieldError{Field: "name", Message: "must match ^[a-z0-9][a-z0-9-]{0,30}$"}) @@ -43,7 +48,12 @@ func (c *Controller) PutPool(ctx context.Context, name string, spec model.PoolSp c.mu.Lock() defer c.mu.Unlock() - pool, _, err := c.st.PutPool(ctx, name, spec) + if cur, err := c.st.GetPool(ctx, name); err == nil { + if err := checkOwner(cur.Source, source, "pool", name); err != nil { + return model.Pool{}, err + } + } + pool, _, err := c.st.PutPoolAs(ctx, name, spec, source) if err != nil { return model.Pool{}, mapErr(err) } @@ -65,11 +75,20 @@ func (c *Controller) ListPools(ctx context.Context) ([]model.Pool, error) { // DeletePool removes the pool. With drain, Ready instances are drained instead of stopped; the reconcile // cycle stops every other instance of a pool that no longer exists. func (c *Controller) DeletePool(ctx context.Context, name string, drain bool) error { + return c.RemovePool(ctx, model.SourceAPI, name, drain) +} + +// RemovePool is DeletePool on behalf of source; see Applier. +func (c *Controller) RemovePool(ctx context.Context, source model.Source, name string, drain bool) error { c.mu.Lock() defer c.mu.Unlock() - if _, err := c.st.GetPool(ctx, name); err != nil { + cur, err := c.st.GetPool(ctx, name) + if err != nil { return mapErr(err) } + if err := checkOwner(cur.Source, source, "pool", name); err != nil { + return err + } if drain { insts, err := c.st.ListInstances(ctx, store.InstanceFilter{Pool: name}) if err != nil { @@ -264,6 +283,9 @@ func (c *Controller) SelfStatus(ctx context.Context, id string, u StatusUpdate) if changed { c.Trigger() } + if inst.Role == model.RoleProxy { + c.publishNetwork(ctx) + } return inst, nil } diff --git a/internal/driver/driver.go b/internal/driver/driver.go index 32abdd1..f7863f7 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -31,6 +31,9 @@ const ( type StartSpec struct { Instance model.Instance Pool model.Pool + // Effective is the pool merged with its environment and groups. Zero for specs built by hand (tests); + // drivers use EffectiveOrV1 to read it. + Effective model.EffectiveSpec // Token is the plain per-instance token, injected as GRUS_TOKEN. Never logged. Token string // Env are the GRUS_* variables (GRUS_URL, GRUS_INSTANCE, GRUS_POOL, GRUS_ROLE) plus spec env. @@ -90,3 +93,24 @@ type Driver interface { // Command writes one console line to the instance's stdin. Command(ctx context.Context, ref string, line string) error } + +// EffectiveOrV1 returns Effective, or the v1 inline fields of the pool when no effective spec was resolved. +func (s StartSpec) EffectiveOrV1() model.EffectiveSpec { + if s.Effective.Driver != "" { + return s.Effective + } + p := s.Pool.Spec + return model.EffectiveSpec{ + Driver: p.EffectiveDriver(), + Image: p.Image, + Command: p.Command, + Args: p.Args, + Env: p.Env, + Port: p.Port, + Readiness: model.ReadinessSelf, + StopCommand: p.Lifecycle.StopCommand, + GracePeriod: p.WithDefaults().Lifecycle.GracePeriod, + Templates: p.Templates, + Labels: p.Labels, + } +} diff --git a/internal/driver/kubernetes/kubernetes.go b/internal/driver/kubernetes/kubernetes.go index 324694d..366365e 100644 --- a/internal/driver/kubernetes/kubernetes.go +++ b/internal/driver/kubernetes/kubernetes.go @@ -179,7 +179,11 @@ func mapNotFound(ref string, err error) error { // podFor builds the bare pod for one instance. func (d *Driver) podFor(spec driver.StartSpec) (*corev1.Pod, error) { pool := spec.Pool.Spec.WithDefaults() - grace := time.Duration(pool.Lifecycle.GracePeriod) + eff := spec.EffectiveOrV1() + if eff.Port == 0 { + eff.Port = model.DefaultPort + } + grace := time.Duration(eff.GracePeriod) graceSeconds := int64(grace / time.Second) poolName := spec.Instance.Pool @@ -190,14 +194,14 @@ func (d *Driver) podFor(spec driver.StartSpec) (*corev1.Pod, error) { server := corev1.Container{ Name: serverContainer, - Image: pool.Image, - Command: pool.Command, - Args: pool.Args, + Image: eff.Image, + Command: eff.Command, + Args: eff.Args, WorkingDir: dataMountPath, Stdin: true, TTY: false, Env: serverEnv(spec, pool), - Ports: []corev1.ContainerPort{{Name: portName, ContainerPort: int32(pool.Port), Protocol: corev1.ProtocolTCP}}, + Ports: []corev1.ContainerPort{{Name: portName, ContainerPort: int32(eff.Port), Protocol: corev1.ProtocolTCP}}, Resources: resources, VolumeMounts: []corev1.VolumeMount{dataMount()}, SecurityContext: containerSecurityContext(), @@ -336,11 +340,11 @@ func serverResources(r model.Resources) (corev1.ResourceRequirements, error) { } func (d *Driver) labels(spec driver.StartSpec, poolName string, pool model.PoolSpec) map[string]string { - labels := make(map[string]string, len(d.cfg.PodLabels)+len(pool.Labels)+4) + labels := make(map[string]string, len(d.cfg.PodLabels)+len(spec.EffectiveOrV1().Labels)+4) for k, v := range d.cfg.PodLabels { labels[k] = v } - for k, v := range pool.Labels { + for k, v := range spec.EffectiveOrV1().Labels { labels[k] = v } // Driver labels win over user labels, so adoption by label keeps working. diff --git a/internal/driver/kubernetes/kubernetes_test.go b/internal/driver/kubernetes/kubernetes_test.go index 5e62b49..b7d6379 100644 --- a/internal/driver/kubernetes/kubernetes_test.go +++ b/internal/driver/kubernetes/kubernetes_test.go @@ -729,3 +729,25 @@ func listOne(t *testing.T, pod *corev1.Pod) driver.Observed { } return obs[0] } + +func TestStartPrefersEffectiveSpecOverV1PoolFields(t *testing.T) { + d, _ := newTestDriver(t) + spec := testStartSpec(false) + spec.Effective = model.EffectiveSpec{ + Driver: "kubernetes", Image: "registry.example/paper:9", Command: []string{"run"}, Args: []string{"--x"}, + Port: 30000, GracePeriod: model.Duration(45 * time.Second), Labels: map[string]string{"from": "group"}, + } + pod := startPod(t, d, spec) + + server := containerNamed(t, pod.Spec.Containers, "server") + if server.Image != "registry.example/paper:9" || !reflect.DeepEqual(server.Command, []string{"run"}) || + !reflect.DeepEqual(server.Args, []string{"--x"}) || server.Ports[0].ContainerPort != 30000 { + t.Errorf("server container ignores the effective spec: %+v", server) + } + if pod.Labels["from"] != "group" { + t.Errorf("labels = %v, want the effective labels", pod.Labels) + } + if pod.Spec.TerminationGracePeriodSeconds == nil || *pod.Spec.TerminationGracePeriodSeconds != 45 { + t.Errorf("termination grace = %v, want 45", pod.Spec.TerminationGracePeriodSeconds) + } +} diff --git a/internal/driver/process/process.go b/internal/driver/process/process.go index ed02797..245650e 100644 --- a/internal/driver/process/process.go +++ b/internal/driver/process/process.go @@ -101,7 +101,8 @@ func (d *Driver) Start(ctx context.Context, spec driver.StartSpec) (string, erro if err := checkID(id); err != nil { return "", err } - if len(spec.Pool.Spec.Command) == 0 { + eff := spec.EffectiveOrV1() + if len(eff.Command) == 0 { return "", errors.New("process: pool spec has no command") } if err := ctx.Err(); err != nil { @@ -170,8 +171,8 @@ 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(spec.Pool.Spec.Command[1:]), spec.Pool.Spec.Args...) - cmd := exec.Command(spec.Pool.Spec.Command[0], args...) + args := append(slices.Clone(eff.Command[1:]), eff.Args...) + cmd := exec.Command(eff.Command[0], args...) cmd.Dir = workdir cmd.Env = buildEnv(spec.Env, spec.Token, port) cmd.Stdout = outW @@ -508,8 +509,8 @@ func buildEnv(extra map[string]string, token string, port int) []string { // pickPort returns the fixed port of a static pool, or a free loopback port otherwise. func pickPort(spec driver.StartSpec) (int, error) { - if spec.Pool.Spec.Mode == model.ModeStatic && spec.Pool.Spec.Port > 0 { - return spec.Pool.Spec.Port, nil + if port := spec.EffectiveOrV1().Port; spec.Pool.Spec.Mode == model.ModeStatic && port > 0 { + return port, nil } l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { diff --git a/internal/driver/process/process_test.go b/internal/driver/process/process_test.go index f0f0041..8332710 100644 --- a/internal/driver/process/process_test.go +++ b/internal/driver/process/process_test.go @@ -425,3 +425,16 @@ func TestForgetRefusesRunningInstance(t *testing.T) { t.Error("Forget of a running instance returned nil error, want an error") } } + +func TestStartRunsTheEffectiveCommandInsteadOfThePoolCommand(t *testing.T) { + h := newHarness(t, nil) + spec := h.spec("inst-eff", nil) + spec.Pool.Spec.Command = []string{"/nonexistent/v1-binary"} + spec.Effective = model.EffectiveSpec{Driver: "process", Command: []string{os.Args[0]}} + + ref, err := h.d.Start(h.ctx, spec) + if err != nil { + t.Fatalf("Start: %v", err) + } + h.waitPhase(ref, driver.PhaseRunning) +} diff --git a/internal/model/environment.go b/internal/model/environment.go new file mode 100644 index 0000000..4a9ab78 --- /dev/null +++ b/internal/model/environment.go @@ -0,0 +1,128 @@ +package model + +import ( + "fmt" + "time" +) + +// Environment kinds. +const ( + KindJVM = "jvm" + KindNative = "native" + KindContainer = "container" +) + +// Readiness modes: self means the instance calls POST /v1/self/ready, tcp means Grus marks it Ready once +// the port accepts connections. +const ( + ReadinessSelf = "self" + ReadinessTCP = "tcp" +) + +// JVM describes how a jvm environment is started by the process and agent drivers. The heap size is +// derived from the pool's memory (see ResolvePool). +type JVM struct { + Jar string `json:"jar,omitempty" doc:"Jar file inside the instance directory"` + Flags []string `json:"flags,omitempty" doc:"JVM flags placed before -Xmx and -jar"` +} + +// EnvironmentSpec says HOW a service runs, independent of what it serves. +type EnvironmentSpec struct { + Kind string `json:"kind"` + Image string `json:"image,omitempty"` + Command []string `json:"command,omitempty"` + Args []string `json:"args,omitempty"` + JVM *JVM `json:"jvm,omitempty"` + Env map[string]string `json:"env,omitempty"` + Port int `json:"port,omitempty"` + Readiness string `json:"readiness,omitempty"` + StopCommand string `json:"stopCommand,omitempty"` + GracePeriod Duration `json:"gracePeriod,omitempty"` +} + +// WithDefaults returns a copy with Port and Readiness defaulted. +func (s EnvironmentSpec) WithDefaults() EnvironmentSpec { + if s.Port == 0 { + s.Port = DefaultPort + } + if s.Readiness == "" { + s.Readiness = ReadinessSelf + } + return s +} + +// Validate checks a spec and returns every problem found. +func (s EnvironmentSpec) Validate() []FieldError { + var errs []FieldError + add := func(f, m string) { errs = append(errs, FieldError{Field: f, Message: m}) } + switch s.Kind { + case KindJVM, KindNative, KindContainer: + default: + add("kind", "must be jvm, native or container") + } + if s.JVM != nil && s.Kind != KindJVM { + add("jvm", "is only allowed for kind jvm") + } + if s.Kind == KindContainer && s.Image == "" { + add("image", "is required for kind container") + } + if s.Kind == KindNative && len(s.Command) == 0 && s.Image == "" { + add("command", "is required for kind native unless an image is set") + } + if s.Kind == KindJVM && s.Image == "" && len(s.Command) == 0 && (s.JVM == nil || s.JVM.Jar == "") { + add("jvm.jar", "is required for kind jvm unless an image or command is set") + } + if s.Port < 0 || s.Port > 65535 { + add("port", "must be in 0..65535") + } + switch s.Readiness { + case "", ReadinessSelf, ReadinessTCP: + default: + add("readiness", "must be self or tcp") + } + if s.GracePeriod < 0 { + add("gracePeriod", "must not be negative") + } + return errs +} + +// GroupSpec bundles templates, env and labels shared by many pools. +type GroupSpec struct { + Templates []TemplateRef `json:"templates,omitempty"` + Env map[string]string `json:"env,omitempty"` + Labels map[string]string `json:"labels,omitempty"` +} + +// Validate checks a spec and returns every problem found. +func (s GroupSpec) Validate() []FieldError { + var errs []FieldError + for i, t := range s.Templates { + if t.Name == "" { + errs = append(errs, FieldError{Field: fmt.Sprintf("templates[%d].name", i), Message: "is required"}) + } + if (t.Tag == "") == (t.Digest == "") { + errs = append(errs, FieldError{Field: fmt.Sprintf("templates[%d]", i), Message: "needs exactly one of tag or digest"}) + } + } + return errs +} + +// Environment is a stored environment; Generation increases on every spec change. +type Environment struct { + Name string `json:"name"` + Spec EnvironmentSpec `json:"spec"` + Source Source `json:"source"` + Generation int64 `json:"generation"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +// Group is a stored group; Generation increases on every spec change. +type Group struct { + Name string `json:"name"` + Spec GroupSpec `json:"spec"` + Source Source `json:"source"` + Generation int64 `json:"generation"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} diff --git a/internal/model/model.go b/internal/model/model.go index ac31677..049f61c 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -109,11 +109,56 @@ type Lifecycle struct { StartTimeout Duration `json:"startTimeout,omitempty"` } -// PoolSpec is the declarative template for the instances of a pool. +// Source says who owns a declaration. Objects owned by kubernetes are read-only through the REST API. +type Source string + +const ( + SourceAPI Source = "api" + SourceKubernetes Source = "kubernetes" + SourceFile Source = "file" +) + +// Valid reports whether s is a known source. +func (s Source) Valid() bool { + return s == SourceAPI || s == SourceKubernetes || s == SourceFile +} + +// Placement drivers. +const ( + DriverKubernetes = "kubernetes" + DriverAgent = "agent" + DriverProcess = "process" +) + +// Placement says where the instances of a pool run. Host names the agent for the agent driver. +type Placement struct { + Driver string `json:"driver,omitempty"` + Host string `json:"host,omitempty"` +} + +// Sharding splits a pool's world into cells (spec only; behaviour follows later). +type Sharding struct { + CellSize int `json:"cellSize,omitempty" doc:"Cell edge length in chunks"` + Cells []string `json:"cells,omitempty" doc:"Explicit cell names"` +} + +// Private lets owners run their own instance of a pool (spec only; behaviour follows later). +type Private struct { + QuotaPerOwner int `json:"quotaPerOwner,omitempty"` + IdleTimeout Duration `json:"idleTimeout,omitempty"` +} + +// PoolSpec is the declarative template for the instances of a pool. Without Environment the inline +// v1 fields (Image, Command, Args, Env, Port) describe how to run; Driver is the v1 spelling of Placement.Driver. type PoolSpec struct { Role Role `json:"role"` Mode Mode `json:"mode"` - Driver string `json:"driver"` + Driver string `json:"driver,omitempty"` + Placement Placement `json:"placement,omitempty"` + Environment string `json:"environment,omitempty"` + Groups []string `json:"groups,omitempty"` + Sharding *Sharding `json:"sharding,omitempty"` + Private *Private `json:"private,omitempty"` Image string `json:"image,omitempty"` Command []string `json:"command,omitempty"` Args []string `json:"args,omitempty"` @@ -189,17 +234,23 @@ func (s PoolSpec) Validate() []FieldError { default: add("mode", "must be dynamic or static") } - switch s.Driver { - case "kubernetes": - if s.Image == "" { - add("image", "is required for the kubernetes driver") + if s.Driver != "" && s.Placement.Driver != "" && s.Driver != s.Placement.Driver { + add("driver", "conflicts with placement.driver; set only placement.driver") + } + switch s.EffectiveDriver() { + case DriverKubernetes: + if s.Environment == "" && s.Image == "" { + add("image", "is required for the kubernetes driver without an environment") + } + case DriverProcess, DriverAgent: + if s.Environment == "" && len(s.Command) == 0 { + add("command", "is required for the "+s.EffectiveDriver()+" driver without an environment") } - case "process": - if len(s.Command) == 0 { - add("command", "is required for the process driver") + if s.EffectiveDriver() == DriverAgent && s.EffectivePlacement().Host == "" { + add("placement.host", "is required for the agent driver") } default: - add("driver", "must be kubernetes or process") + add("placement.driver", "must be kubernetes, agent or process") } if s.Resources.MemoryMiB <= 0 { add("resources.memoryMiB", "must be greater than 0") @@ -230,10 +281,23 @@ func (s PoolSpec) Validate() []FieldError { return errs } +// EffectivePlacement returns the placement with the v1 driver filled in when placement.driver is empty. +func (s PoolSpec) EffectivePlacement() Placement { + p := s.Placement + if p.Driver == "" { + p.Driver = s.Driver + } + return p +} + +// EffectiveDriver is placement.driver, or the v1 driver when placement is empty. +func (s PoolSpec) EffectiveDriver() string { return s.EffectivePlacement().Driver } + // Pool is a stored pool with its spec generation; Generation increases on every spec change. type Pool struct { Name string `json:"name"` Spec PoolSpec `json:"spec"` + Source Source `json:"source,omitempty"` Generation int64 `json:"generation"` Maintenance bool `json:"maintenance"` CreatedAt time.Time `json:"createdAt"` @@ -270,6 +334,8 @@ const ( EventPoolUpdated = "pool.updated" EventPoolScaled = "pool.scaled" EventTemplateTagged = "template.tagged" + EventNetworkPlayers = "network.players" + EventPoolCondition = "pool.condition" EventResync = "resync" ) @@ -302,6 +368,20 @@ type PoolScaledData struct { Inputs map[string]int `json:"inputs"` } +// NetworkStatus is the player count summed over all Ready and Allocated proxy instances. +type NetworkStatus struct { + Players int `json:"players"` + MaxPlayers int `json:"maxPlayers"` + Proxies int `json:"proxies"` +} + +// PoolConditionData is the payload of pool.condition: a pool cannot start instances for the given reason. +type PoolConditionData struct { + Pool string `json:"pool"` + Type string `json:"type"` + Message string `json:"message"` +} + // Publisher sends events to stream subscribers. Implemented by events.Hub. type Publisher interface { Publish(eventType string, data any) diff --git a/internal/model/resolve.go b/internal/model/resolve.go new file mode 100644 index 0000000..eae176a --- /dev/null +++ b/internal/model/resolve.go @@ -0,0 +1,165 @@ +package model + +import ( + "fmt" + "strconv" +) + +// HeapPercent is the share of a pool's memory given to the JVM heap (-Xmx). The rest is left for metaspace, +// thread stacks, direct buffers and the JVM itself, so the process stays below its memory limit. +const HeapPercent = 85 + +// EffectiveSpec is what a driver actually runs: the pool merged with its environment and groups. +type EffectiveSpec struct { + Kind string `json:"kind,omitempty"` + Driver string `json:"driver"` + Host string `json:"host,omitempty"` + Image string `json:"image,omitempty"` + Command []string `json:"command,omitempty"` + Args []string `json:"args,omitempty"` + Env map[string]string `json:"env,omitempty"` + Port int `json:"port"` + Readiness string `json:"readiness"` + StopCommand string `json:"stopCommand,omitempty"` + GracePeriod Duration `json:"gracePeriod"` + Templates []TemplateRef `json:"templates,omitempty"` + Labels map[string]string `json:"labels,omitempty"` +} + +// ResolvePool merges pool, environment and groups into the effective run spec. +// +// Merge rules: environment defaults, then the groups in order, then the pool; later wins for env and +// labels; templates are concatenated group1..groupN, then the pool's. Pool image, command, args, port and +// lifecycle stop command or grace period override the environment's when set. env may be nil only when the +// pool names no environment (v1 inline fields). groups must be the specs named by pool.Groups, in order. +// +// For kind jvm on the process and agent drivers without an explicit command the command line is +// `java -Xmxm -jar `; pool and environment args are appended after it. +func ResolvePool(pool PoolSpec, env *EnvironmentSpec, groups []GroupSpec) (EffectiveSpec, []FieldError) { + var errs []FieldError + add := func(f, m string) { errs = append(errs, FieldError{Field: f, Message: m}) } + + pl := pool.EffectivePlacement() + eff := EffectiveSpec{Driver: pl.Driver, Host: pl.Host} + + var e EnvironmentSpec + switch { + case pool.Environment != "" && env == nil: + add("environment", fmt.Sprintf("environment %q does not exist", pool.Environment)) + case env != nil: + e = env.WithDefaults() + } + if len(groups) != len(pool.Groups) { + add("groups", "resolved groups do not match the pool's group list") + } + if len(errs) > 0 { + return EffectiveSpec{}, errs + } + + eff.Kind = e.Kind + eff.Image = firstNonEmpty(pool.Image, e.Image) + eff.Command = cloneStrings(pickStrings(pool.Command, e.Command)) + eff.Args = cloneStrings(append(append([]string{}, e.Args...), pool.Args...)) + if len(pool.Command) > 0 { + eff.Args = cloneStrings(pool.Args) // a pool command replaces the environment's and brings its own args + } + eff.Env = mergeMaps(e.Env) + for _, g := range groups { + eff.Env = mergeMaps(eff.Env, g.Env) + eff.Labels = mergeMaps(eff.Labels, g.Labels) + eff.Templates = append(eff.Templates, g.Templates...) + } + eff.Env = mergeMaps(eff.Env, pool.Env) + eff.Labels = mergeMaps(eff.Labels, pool.Labels) + eff.Templates = append(eff.Templates, pool.Templates...) + + eff.Port = firstPositive(pool.Port, e.Port, DefaultPort) + eff.Readiness = firstNonEmpty(e.Readiness, ReadinessSelf) + eff.StopCommand = firstNonEmpty(pool.Lifecycle.StopCommand, e.StopCommand) + eff.GracePeriod = Duration(firstPositiveDuration(pool.Lifecycle.GracePeriod, e.GracePeriod, Duration(DefaultGracePeriod))) + + if e.Kind == KindJVM && e.JVM != nil && len(eff.Command) == 0 && (pl.Driver == DriverProcess || pl.Driver == DriverAgent) { + if e.JVM.Jar == "" { + add("environment.jvm.jar", "is required to start a jvm environment with the "+pl.Driver+" driver") + } else { + eff.Command = javaCommand(*e.JVM, pool.Resources.MemoryMiB) + } + } + switch pl.Driver { + case DriverKubernetes: + if eff.Image == "" { + add("image", "no image: set it on the pool or its environment") + } + case DriverProcess, DriverAgent: + if len(eff.Command) == 0 && len(errs) == 0 { + add("command", "no command: set it on the pool or its environment") + } + } + if len(errs) > 0 { + return EffectiveSpec{}, errs + } + return eff, nil +} + +func javaCommand(j JVM, memoryMiB int) []string { + cmd := append([]string{"java"}, j.Flags...) + if memoryMiB > 0 { + cmd = append(cmd, "-Xmx"+strconv.Itoa(memoryMiB*HeapPercent/100)+"m") + } + return append(cmd, "-jar", j.Jar) +} + +func firstNonEmpty(vals ...string) string { + for _, v := range vals { + if v != "" { + return v + } + } + return "" +} + +func firstPositive(vals ...int) int { + for _, v := range vals { + if v > 0 { + return v + } + } + return 0 +} + +func firstPositiveDuration(vals ...Duration) Duration { + for _, v := range vals { + if v > 0 { + return v + } + } + return 0 +} + +func pickStrings(pool, env []string) []string { + if len(pool) > 0 { + return pool + } + return env +} + +func cloneStrings(s []string) []string { + if len(s) == 0 { + return nil + } + return append([]string(nil), s...) +} + +// mergeMaps returns a new map with every later map overriding the earlier ones; nil when all are empty. +func mergeMaps(maps ...map[string]string) map[string]string { + var out map[string]string + for _, m := range maps { + for k, v := range m { + if out == nil { + out = make(map[string]string) + } + out[k] = v + } + } + return out +} diff --git a/internal/model/resolve_test.go b/internal/model/resolve_test.go new file mode 100644 index 0000000..3610083 --- /dev/null +++ b/internal/model/resolve_test.go @@ -0,0 +1,228 @@ +package model + +import ( + "reflect" + "testing" + "time" +) + +func tpl(name string) TemplateRef { return TemplateRef{Name: name, Tag: "latest"} } + +func TestResolvePool(t *testing.T) { + jvmEnv := &EnvironmentSpec{ + Kind: KindJVM, Image: "ghcr.io/x/paper:1", Port: 25570, + JVM: &JVM{Jar: "paper.jar", Flags: []string{"-XX:+UseG1GC"}}, + Env: map[string]string{"A": "env", "B": "env"}, + Args: []string{"--nogui"}, StopCommand: "stop", GracePeriod: Duration(45 * time.Second), + } + tests := []struct { + name string + pool PoolSpec + env *EnvironmentSpec + groups []GroupSpec + want EffectiveSpec + errs []string + }{ + { + name: "v1 inline spec without environment", + pool: PoolSpec{Driver: "kubernetes", Image: "img", Command: []string{"run"}, Args: []string{"-x"}, + Env: map[string]string{"K": "v"}, Port: 1234}, + want: EffectiveSpec{Driver: "kubernetes", Image: "img", Command: []string{"run"}, Args: []string{"-x"}, + Env: map[string]string{"K": "v"}, Port: 1234, Readiness: ReadinessSelf, + GracePeriod: Duration(DefaultGracePeriod)}, + }, + { + name: "jvm on process builds the java command with 85 percent heap", + pool: PoolSpec{Placement: Placement{Driver: "process"}, Environment: "paper", Resources: Resources{MemoryMiB: 2048}, + Args: []string{"--port", "1"}}, + env: jvmEnv, + want: EffectiveSpec{Kind: KindJVM, Driver: "process", Image: "ghcr.io/x/paper:1", + Command: []string{"java", "-XX:+UseG1GC", "-Xmx1740m", "-jar", "paper.jar"}, + Args: []string{"--nogui", "--port", "1"}, Env: map[string]string{"A": "env", "B": "env"}, + Port: 25570, Readiness: ReadinessSelf, StopCommand: "stop", GracePeriod: Duration(45 * time.Second)}, + }, + { + name: "jvm on agent keeps the host", + pool: PoolSpec{Placement: Placement{Driver: "agent", Host: "mc01"}, Environment: "paper", Resources: Resources{MemoryMiB: 1000}}, + env: jvmEnv, + want: EffectiveSpec{Kind: KindJVM, Driver: "agent", Host: "mc01", Image: "ghcr.io/x/paper:1", + Command: []string{"java", "-XX:+UseG1GC", "-Xmx850m", "-jar", "paper.jar"}, Args: []string{"--nogui"}, + Env: map[string]string{"A": "env", "B": "env"}, Port: 25570, Readiness: ReadinessSelf, + StopCommand: "stop", GracePeriod: Duration(45 * time.Second)}, + }, + { + name: "jvm on kubernetes runs the image and builds no command", + pool: PoolSpec{Placement: Placement{Driver: "kubernetes"}, Environment: "paper", Resources: Resources{MemoryMiB: 1000}}, + env: jvmEnv, + want: EffectiveSpec{Kind: KindJVM, Driver: "kubernetes", Image: "ghcr.io/x/paper:1", Args: []string{"--nogui"}, + Env: map[string]string{"A": "env", "B": "env"}, Port: 25570, Readiness: ReadinessSelf, + StopCommand: "stop", GracePeriod: Duration(45 * time.Second)}, + }, + { + name: "env and labels: environment, then groups in order, then pool", + pool: PoolSpec{Driver: "kubernetes", Environment: "paper", Groups: []string{"g1", "g2"}, + Env: map[string]string{"B": "pool"}, Labels: map[string]string{"l": "pool"}}, + env: jvmEnv, + groups: []GroupSpec{ + {Env: map[string]string{"A": "g1", "C": "g1"}, Labels: map[string]string{"l": "g1", "m": "g1"}}, + {Env: map[string]string{"C": "g2"}, Labels: map[string]string{"m": "g2"}}, + }, + want: EffectiveSpec{Kind: KindJVM, Driver: "kubernetes", Image: "ghcr.io/x/paper:1", Args: []string{"--nogui"}, + Env: map[string]string{"A": "g1", "B": "pool", "C": "g2"}, + Port: 25570, Readiness: ReadinessSelf, StopCommand: "stop", GracePeriod: Duration(45 * time.Second), + Labels: map[string]string{"l": "pool", "m": "g2"}}, + }, + { + name: "templates: groups in order, then the pool", + pool: PoolSpec{Driver: "kubernetes", Image: "i", Groups: []string{"g1", "g2"}, Templates: []TemplateRef{tpl("p")}}, + groups: []GroupSpec{ + {Templates: []TemplateRef{tpl("a"), tpl("b")}}, + {Templates: []TemplateRef{tpl("c")}}, + }, + want: EffectiveSpec{Driver: "kubernetes", Image: "i", Port: DefaultPort, Readiness: ReadinessSelf, + GracePeriod: Duration(DefaultGracePeriod), + Templates: []TemplateRef{tpl("a"), tpl("b"), tpl("c"), tpl("p")}}, + }, + { + name: "pool fields override the environment", + pool: PoolSpec{Driver: "process", Environment: "paper", Port: 1, Image: "own", Command: []string{"bin"}, + Args: []string{"-p"}, + Lifecycle: Lifecycle{StopCommand: "end", GracePeriod: Duration(5 * time.Second)}}, + env: jvmEnv, + want: EffectiveSpec{Kind: KindJVM, Driver: "process", Image: "own", Command: []string{"bin"}, Args: []string{"-p"}, + Env: map[string]string{"A": "env", "B": "env"}, Port: 1, Readiness: ReadinessSelf, + StopCommand: "end", GracePeriod: Duration(5 * time.Second)}, + }, + { + name: "tcp readiness comes from the environment", + pool: PoolSpec{Driver: "kubernetes", Environment: "n"}, + env: &EnvironmentSpec{Kind: KindNative, Image: "i", Readiness: ReadinessTCP}, + want: EffectiveSpec{Kind: KindNative, Driver: "kubernetes", Image: "i", Port: DefaultPort, + Readiness: ReadinessTCP, GracePeriod: Duration(DefaultGracePeriod)}, + }, + { + name: "unknown environment is an error", + pool: PoolSpec{Driver: "kubernetes", Environment: "missing"}, + errs: []string{"environment"}, + }, + { + name: "jvm without jar on process is an error", + pool: PoolSpec{Driver: "process", Environment: "e"}, + env: &EnvironmentSpec{Kind: KindJVM, JVM: &JVM{}}, + errs: []string{"environment.jvm.jar"}, + }, + { + name: "kubernetes without any image is an error", + pool: PoolSpec{Driver: "kubernetes", Environment: "e"}, + env: &EnvironmentSpec{Kind: KindNative, Command: []string{"x"}}, + errs: []string{"image"}, + }, + { + name: "group list mismatch is an error", + pool: PoolSpec{Driver: "kubernetes", Image: "i", Groups: []string{"g"}}, + groups: nil, + errs: []string{"groups"}, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got, errs := ResolvePool(tc.pool, tc.env, tc.groups) + var fields []string + for _, e := range errs { + fields = append(fields, e.Field) + } + if !reflect.DeepEqual(fields, tc.errs) { + t.Fatalf("error fields = %v, want %v", fields, tc.errs) + } + if tc.errs == nil && !reflect.DeepEqual(got, tc.want) { + t.Errorf("effective spec mismatch\n got: %+v\nwant: %+v", got, tc.want) + } + }) + } +} + +func TestResolvePoolDoesNotAliasInputs(t *testing.T) { + env := &EnvironmentSpec{Kind: KindNative, Command: []string{"bin"}, Env: map[string]string{"A": "1"}} + got, errs := ResolvePool(PoolSpec{Driver: "process", Environment: "e"}, env, nil) + if len(errs) > 0 { + t.Fatalf("unexpected errors: %v", errs) + } + got.Env["A"] = "changed" + got.Command[0] = "changed" + if env.Env["A"] != "1" || env.Command[0] != "bin" { + t.Errorf("mutating the effective spec changed the environment: %+v", env) + } +} + +func TestPoolSpecPlacementValidation(t *testing.T) { + base := PoolSpec{Role: RoleGame, Mode: ModeDynamic, Image: "i", Command: []string{"c"}, + Resources: Resources{MemoryMiB: 1}, Scaling: Scaling{Min: 0, Max: 1}} + tests := []struct { + name string + mut func(*PoolSpec) + field string + }{ + {"v1 driver kubernetes is valid", func(s *PoolSpec) { s.Driver = "kubernetes" }, ""}, + {"placement driver process is valid", func(s *PoolSpec) { s.Placement.Driver = "process" }, ""}, + {"agent with host is valid", func(s *PoolSpec) { s.Placement = Placement{Driver: "agent", Host: "mc01"} }, ""}, + {"agent without host is rejected", func(s *PoolSpec) { s.Placement.Driver = "agent" }, "placement.host"}, + {"unknown driver is rejected", func(s *PoolSpec) { s.Placement.Driver = "nomad" }, "placement.driver"}, + {"missing driver is rejected", func(s *PoolSpec) {}, "placement.driver"}, + {"conflicting drivers are rejected", func(s *PoolSpec) { s.Driver = "process"; s.Placement.Driver = "kubernetes" }, "driver"}, + {"environment replaces image requirement", func(s *PoolSpec) { s.Driver = "kubernetes"; s.Image = ""; s.Environment = "e" }, ""}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + s := base + tc.mut(&s) + errs := s.WithDefaults().Validate() + if tc.field == "" { + if len(errs) > 0 { + t.Fatalf("unexpected errors: %v", errs) + } + return + } + for _, e := range errs { + if e.Field == tc.field { + return + } + } + t.Fatalf("no error for field %q in %v", tc.field, errs) + }) + } +} + +func TestEnvironmentSpecValidate(t *testing.T) { + tests := []struct { + name string + spec EnvironmentSpec + field string + }{ + {"jvm with jar", EnvironmentSpec{Kind: KindJVM, JVM: &JVM{Jar: "a.jar"}}, ""}, + {"jvm without anything", EnvironmentSpec{Kind: KindJVM}, "jvm.jar"}, + {"native with command", EnvironmentSpec{Kind: KindNative, Command: []string{"x"}}, ""}, + {"container needs image", EnvironmentSpec{Kind: KindContainer}, "image"}, + {"unknown kind", EnvironmentSpec{Kind: "wasm"}, "kind"}, + {"jvm block on native", EnvironmentSpec{Kind: KindNative, Command: []string{"x"}, JVM: &JVM{}}, "jvm"}, + {"bad readiness", EnvironmentSpec{Kind: KindNative, Command: []string{"x"}, Readiness: "http"}, "readiness"}, + {"bad port", EnvironmentSpec{Kind: KindNative, Command: []string{"x"}, Port: 70000}, "port"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + errs := tc.spec.Validate() + if tc.field == "" && len(errs) > 0 { + t.Fatalf("unexpected errors: %v", errs) + } + if tc.field != "" && (len(errs) == 0 || errs[0].Field != tc.field) { + t.Fatalf("errors = %v, want first field %q", errs, tc.field) + } + }) + } +} + +func TestEnvironmentSpecWithDefaults(t *testing.T) { + got := EnvironmentSpec{Kind: KindNative}.WithDefaults() + if got.Port != DefaultPort || got.Readiness != ReadinessSelf { + t.Errorf("defaults = port %d readiness %q", got.Port, got.Readiness) + } +} diff --git a/internal/store/declarations.go b/internal/store/declarations.go new file mode 100644 index 0000000..79a3f84 --- /dev/null +++ b/internal/store/declarations.go @@ -0,0 +1,240 @@ +package store + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +// declaration is the shared row shape of environments and groups. +type declaration struct { + name string + specText string + source model.Source + generation int64 + createdAt string + updatedAt string +} + +// Table names are constants of this package, never user input. +const ( + tableEnvironments = "environments" + tableGroups = "groups" +) + +func declSelect(table string) string { + return "SELECT name, spec, source, generation, created_at, updated_at FROM " + table +} + +func scanDecl(sc rowScanner) (declaration, error) { + var d declaration + var source string + if err := sc.Scan(&d.name, &d.specText, &source, &d.generation, &d.createdAt, &d.updatedAt); err != nil { + return declaration{}, err + } + d.source = model.Source(source) + return d, nil +} + +// putDecl stores a declaration with the generation rules of PutPool and returns the stored row. +func (s *SQLite) putDecl(ctx context.Context, table, name string, spec any, source model.Source) (declaration, bool, error) { + canon, err := canonicalJSON(spec) + if err != nil { + return declaration{}, false, fmt.Errorf("encode spec of %s %q: %w", table, name, err) + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return declaration{}, false, fmt.Errorf("begin %s transaction: %w", table, err) + } + defer func() { _ = tx.Rollback() }() + + now := s.clock.Now().UTC() + cur, err := scanDecl(tx.QueryRowContext(ctx, declSelect(table)+" WHERE name = ?", name)) + changed := true + switch { + case errors.Is(err, sql.ErrNoRows): + _, err = tx.ExecContext(ctx, + "INSERT INTO "+table+" (name, spec, source, generation, created_at, updated_at) VALUES (?, ?, ?, 1, ?, ?)", + name, canon, string(source), formatTime(now), formatTime(now)) + if err != nil { + return declaration{}, false, fmt.Errorf("insert %s %q: %w", table, name, err) + } + cur = declaration{name: name, generation: 1, createdAt: formatTime(now), updatedAt: formatTime(now)} + case err != nil: + return declaration{}, false, fmt.Errorf("load %s %q: %w", table, name, err) + case cur.specText == canon: + changed = false + if cur.source != source { + if _, err := tx.ExecContext(ctx, "UPDATE "+table+" SET source = ? WHERE name = ?", string(source), name); err != nil { + return declaration{}, false, fmt.Errorf("update source of %s %q: %w", table, name, err) + } + } + default: + _, err = tx.ExecContext(ctx, + "UPDATE "+table+" SET spec = ?, source = ?, generation = generation + 1, updated_at = ? WHERE name = ?", + canon, string(source), formatTime(now), name) + if err != nil { + return declaration{}, false, fmt.Errorf("update %s %q: %w", table, name, err) + } + cur.generation++ + cur.updatedAt = formatTime(now) + } + if err := tx.Commit(); err != nil { + return declaration{}, false, fmt.Errorf("commit %s %q: %w", table, name, err) + } + cur.specText, cur.source = canon, source + return cur, changed, nil +} + +func (s *SQLite) getDecl(ctx context.Context, table, name string) (declaration, error) { + d, err := scanDecl(s.db.QueryRowContext(ctx, declSelect(table)+" WHERE name = ?", name)) + if errors.Is(err, sql.ErrNoRows) { + return declaration{}, fmt.Errorf("get %s %q: %w", table, name, ErrNotFound) + } + if err != nil { + return declaration{}, fmt.Errorf("get %s %q: %w", table, name, err) + } + return d, nil +} + +func (s *SQLite) listDecls(ctx context.Context, table string) ([]declaration, error) { + rows, err := s.db.QueryContext(ctx, declSelect(table)+" ORDER BY name") + if err != nil { + return nil, fmt.Errorf("list %s: %w", table, err) + } + defer rows.Close() + var out []declaration + for rows.Next() { + d, err := scanDecl(rows) + if err != nil { + return nil, fmt.Errorf("list %s: %w", table, err) + } + out = append(out, d) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("list %s: %w", table, err) + } + return out, nil +} + +func (s *SQLite) deleteDecl(ctx context.Context, table, name string) error { + res, err := s.db.ExecContext(ctx, "DELETE FROM "+table+" WHERE name = ?", name) + if err != nil { + return fmt.Errorf("delete %s %q: %w", table, name, err) + } + return requireAffected(res, fmt.Sprintf("delete %s %q", table, name)) +} + +func (d declaration) decode(spec any) (created, updated time.Time, err error) { + if err = json.Unmarshal([]byte(d.specText), spec); err != nil { + return created, updated, fmt.Errorf("decode spec of %q: %w", d.name, err) + } + if created, err = parseTime(d.createdAt); err != nil { + return created, updated, fmt.Errorf("%q created_at: %w", d.name, err) + } + if updated, err = parseTime(d.updatedAt); err != nil { + return created, updated, fmt.Errorf("%q updated_at: %w", d.name, err) + } + return created, updated, nil +} + +func (d declaration) environment() (model.Environment, error) { + e := model.Environment{Name: d.name, Source: d.source, Generation: d.generation} + var err error + e.CreatedAt, e.UpdatedAt, err = d.decode(&e.Spec) + return e, err +} + +func (d declaration) group() (model.Group, error) { + g := model.Group{Name: d.name, Source: d.source, Generation: d.generation} + var err error + g.CreatedAt, g.UpdatedAt, err = d.decode(&g.Spec) + return g, err +} + +// PutEnvironment creates or replaces an environment; generation rules as in PutPool. +func (s *SQLite) PutEnvironment(ctx context.Context, name string, spec model.EnvironmentSpec, source model.Source) (model.Environment, bool, error) { + d, changed, err := s.putDecl(ctx, tableEnvironments, name, spec, source) + if err != nil { + return model.Environment{}, false, err + } + e, err := d.environment() + return e, changed, err +} + +// GetEnvironment returns the environment; ErrNotFound if it does not exist. +func (s *SQLite) GetEnvironment(ctx context.Context, name string) (model.Environment, error) { + d, err := s.getDecl(ctx, tableEnvironments, name) + if err != nil { + return model.Environment{}, err + } + return d.environment() +} + +// ListEnvironments returns all environments ordered by name. +func (s *SQLite) ListEnvironments(ctx context.Context) ([]model.Environment, error) { + ds, err := s.listDecls(ctx, tableEnvironments) + if err != nil { + return nil, err + } + out := make([]model.Environment, 0, len(ds)) + for _, d := range ds { + e, err := d.environment() + if err != nil { + return nil, err + } + out = append(out, e) + } + return out, nil +} + +// DeleteEnvironment removes the environment; ErrNotFound if it does not exist. +func (s *SQLite) DeleteEnvironment(ctx context.Context, name string) error { + return s.deleteDecl(ctx, tableEnvironments, name) +} + +// PutGroup creates or replaces a group; generation rules as in PutPool. +func (s *SQLite) PutGroup(ctx context.Context, name string, spec model.GroupSpec, source model.Source) (model.Group, bool, error) { + d, changed, err := s.putDecl(ctx, tableGroups, name, spec, source) + if err != nil { + return model.Group{}, false, err + } + g, err := d.group() + return g, changed, err +} + +// GetGroup returns the group; ErrNotFound if it does not exist. +func (s *SQLite) GetGroup(ctx context.Context, name string) (model.Group, error) { + d, err := s.getDecl(ctx, tableGroups, name) + if err != nil { + return model.Group{}, err + } + return d.group() +} + +// ListGroups returns all groups ordered by name. +func (s *SQLite) ListGroups(ctx context.Context) ([]model.Group, error) { + ds, err := s.listDecls(ctx, tableGroups) + if err != nil { + return nil, err + } + out := make([]model.Group, 0, len(ds)) + for _, d := range ds { + g, err := d.group() + if err != nil { + return nil, err + } + out = append(out, g) + } + return out, nil +} + +// DeleteGroup removes the group; ErrNotFound if it does not exist. +func (s *SQLite) DeleteGroup(ctx context.Context, name string) error { + return s.deleteDecl(ctx, tableGroups, name) +} diff --git a/internal/store/declarations_test.go b/internal/store/declarations_test.go new file mode 100644 index 0000000..0beb1b6 --- /dev/null +++ b/internal/store/declarations_test.go @@ -0,0 +1,142 @@ +package store + +import ( + "context" + "errors" + "reflect" + "testing" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +func envSpec() model.EnvironmentSpec { + return model.EnvironmentSpec{Kind: model.KindJVM, JVM: &model.JVM{Jar: "paper.jar"}, Port: 25565} +} + +func TestPutEnvironmentGenerationRules(t *testing.T) { + clock := &fakeClock{now: startTime} + s := newTestStore(t, clock) + ctx := context.Background() + + first, changed, err := s.PutEnvironment(ctx, "paper", envSpec(), model.SourceAPI) + if err != nil || !changed || first.Generation != 1 || first.Source != model.SourceAPI { + t.Fatalf("insert = %+v changed=%v err=%v, want generation 1, source api, changed", first, changed, err) + } + clock.advance(time.Minute) + same, changed, err := s.PutEnvironment(ctx, "paper", envSpec(), model.SourceAPI) + if err != nil || changed || same.Generation != 1 || !same.UpdatedAt.Equal(first.UpdatedAt) { + t.Errorf("same spec = %+v changed=%v err=%v, want unchanged generation and updatedAt", same, changed, err) + } + spec := envSpec() + spec.Port = 25570 + next, changed, err := s.PutEnvironment(ctx, "paper", spec, model.SourceAPI) + if err != nil || !changed || next.Generation != 2 || !next.UpdatedAt.Equal(clock.now) || !next.CreatedAt.Equal(first.CreatedAt) { + t.Errorf("changed spec = %+v changed=%v err=%v, want generation 2, new updatedAt, kept createdAt", next, changed, err) + } + got, err := s.GetEnvironment(ctx, "paper") + if err != nil || !reflect.DeepEqual(got, next) { + t.Errorf("GetEnvironment = %+v err=%v, want %+v", got, err, next) + } +} + +func TestPutEnvironmentSourceChangeKeepsGeneration(t *testing.T) { + s := newTestStore(t, &fakeClock{now: startTime}) + ctx := context.Background() + if _, _, err := s.PutEnvironment(ctx, "paper", envSpec(), model.SourceAPI); err != nil { + t.Fatal(err) + } + e, changed, err := s.PutEnvironment(ctx, "paper", envSpec(), model.SourceKubernetes) + if err != nil || changed || e.Generation != 1 || e.Source != model.SourceKubernetes { + t.Fatalf("source takeover = %+v changed=%v err=%v", e, changed, err) + } + got, _ := s.GetEnvironment(ctx, "paper") + if got.Source != model.SourceKubernetes { + t.Errorf("stored source = %q, want kubernetes", got.Source) + } +} + +func TestEnvironmentListDeleteAndNotFound(t *testing.T) { + s := newTestStore(t, &fakeClock{now: startTime}) + ctx := context.Background() + for _, n := range []string{"velocity", "paper"} { + if _, _, err := s.PutEnvironment(ctx, n, envSpec(), model.SourceAPI); err != nil { + t.Fatal(err) + } + } + list, err := s.ListEnvironments(ctx) + if err != nil || len(list) != 2 || list[0].Name != "paper" || list[1].Name != "velocity" { + t.Fatalf("ListEnvironments = %+v err=%v, want paper, velocity", list, err) + } + if err := s.DeleteEnvironment(ctx, "paper"); err != nil { + t.Fatalf("DeleteEnvironment: %v", err) + } + if _, err := s.GetEnvironment(ctx, "paper"); !errors.Is(err, ErrNotFound) { + t.Errorf("GetEnvironment after delete = %v, want ErrNotFound", err) + } + if err := s.DeleteEnvironment(ctx, "paper"); !errors.Is(err, ErrNotFound) { + t.Errorf("second delete = %v, want ErrNotFound", err) + } +} + +func TestGroupCRUD(t *testing.T) { + clock := &fakeClock{now: startTime} + s := newTestStore(t, clock) + ctx := context.Background() + spec := model.GroupSpec{ + Templates: []model.TemplateRef{{Name: "plugins", Tag: "latest"}}, + Env: map[string]string{"A": "1"}, + Labels: map[string]string{"team": "olf"}, + } + g, changed, err := s.PutGroup(ctx, "base", spec, model.SourceFile) + if err != nil || !changed || g.Generation != 1 || g.Source != model.SourceFile { + t.Fatalf("PutGroup = %+v changed=%v err=%v", g, changed, err) + } + spec.Env["A"] = "2" + g, changed, err = s.PutGroup(ctx, "base", spec, model.SourceFile) + if err != nil || !changed || g.Generation != 2 { + t.Fatalf("changed PutGroup = %+v changed=%v err=%v, want generation 2", g, changed, err) + } + got, err := s.GetGroup(ctx, "base") + if err != nil || !reflect.DeepEqual(got.Spec, spec) { + t.Errorf("GetGroup = %+v err=%v, want spec %+v", got, err, spec) + } + list, err := s.ListGroups(ctx) + if err != nil || len(list) != 1 { + t.Errorf("ListGroups = %+v err=%v, want one group", list, err) + } + if err := s.DeleteGroup(ctx, "base"); err != nil { + t.Fatalf("DeleteGroup: %v", err) + } + if _, err := s.GetGroup(ctx, "base"); !errors.Is(err, ErrNotFound) { + t.Errorf("GetGroup after delete = %v, want ErrNotFound", err) + } +} + +func TestPoolSourceIsStoredAndDefaultsToAPI(t *testing.T) { + s := newTestStore(t, &fakeClock{now: startTime}) + ctx := context.Background() + p, _, err := s.PutPool(ctx, "lobby", validSpec()) + if err != nil || p.Source != model.SourceAPI { + t.Fatalf("PutPool = %+v err=%v, want source api", p, err) + } + p, changed, err := s.PutPoolAs(ctx, "lobby", validSpec(), model.SourceKubernetes) + if err != nil || changed || p.Source != model.SourceKubernetes || p.Generation != 1 { + t.Fatalf("PutPoolAs same spec = %+v changed=%v err=%v", p, changed, err) + } + got, _ := s.GetPool(ctx, "lobby") + if got.Source != model.SourceKubernetes { + t.Errorf("stored pool source = %q, want kubernetes", got.Source) + } + spec := validSpec() + spec.Placement = model.Placement{Driver: "agent", Host: "mc01"} + spec.Environment = "paper" + spec.Groups = []string{"base"} + if _, _, err := s.PutPoolAs(ctx, "lobby", spec, model.SourceKubernetes); err != nil { + t.Fatal(err) + } + got, _ = s.GetPool(ctx, "lobby") + if !reflect.DeepEqual(got.Spec, spec) { + t.Errorf("v2 pool fields did not round-trip: got %+v want %+v", got.Spec, spec) + } +} diff --git a/internal/store/migrations/00002_environments_groups.sql b/internal/store/migrations/00002_environments_groups.sql new file mode 100644 index 0000000..b7e41e2 --- /dev/null +++ b/internal/store/migrations/00002_environments_groups.sql @@ -0,0 +1,25 @@ +-- +goose Up +ALTER TABLE pools ADD COLUMN source TEXT NOT NULL DEFAULT 'api'; + +CREATE TABLE environments ( + name TEXT PRIMARY KEY, + spec TEXT NOT NULL, + source TEXT NOT NULL DEFAULT 'api', + generation INTEGER NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE TABLE groups ( + name TEXT PRIMARY KEY, + spec TEXT NOT NULL, + source TEXT NOT NULL DEFAULT 'api', + generation INTEGER NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +-- +goose Down +DROP TABLE groups; +DROP TABLE environments; +ALTER TABLE pools DROP COLUMN source; diff --git a/internal/store/sqlite.go b/internal/store/sqlite.go index e3c05a9..d1c7bf9 100644 --- a/internal/store/sqlite.go +++ b/internal/store/sqlite.go @@ -94,6 +94,11 @@ type rowScanner interface { // an unchanged spec keeps generation and updated_at, a changed spec increments the generation. // Maintenance and created_at are never changed by PutPool. func (s *SQLite) PutPool(ctx context.Context, name string, spec model.PoolSpec) (model.Pool, bool, error) { + return s.PutPoolAs(ctx, name, spec, model.SourceAPI) +} + +// PutPoolAs is PutPool for a declaration owned by source. A changed source alone does not bump the generation. +func (s *SQLite) PutPoolAs(ctx context.Context, name string, spec model.PoolSpec, source model.Source) (model.Pool, bool, error) { canon, err := canonicalJSON(spec) if err != nil { return model.Pool{}, false, fmt.Errorf("encode spec of pool %q: %w", name, err) @@ -109,8 +114,8 @@ func (s *SQLite) PutPool(ctx context.Context, name string, spec model.PoolSpec) switch { case errors.Is(err, sql.ErrNoRows): _, err = tx.ExecContext(ctx, - `INSERT INTO pools (name, spec, generation, maintenance, created_at, updated_at) VALUES (?, ?, 1, 0, ?, ?)`, - name, canon, formatTime(now), formatTime(now)) + `INSERT INTO pools (name, spec, source, generation, maintenance, created_at, updated_at) VALUES (?, ?, ?, 1, 0, ?, ?)`, + name, canon, string(source), formatTime(now), formatTime(now)) if err != nil { return model.Pool{}, false, fmt.Errorf("insert pool %q: %w", name, err) } @@ -118,14 +123,20 @@ func (s *SQLite) PutPool(ctx context.Context, name string, spec model.PoolSpec) case err != nil: return model.Pool{}, false, fmt.Errorf("load pool %q: %w", name, err) case storedSpec == canon: + if cur.Source != source { + if _, err := tx.ExecContext(ctx, `UPDATE pools SET source = ? WHERE name = ?`, string(source), name); err != nil { + return model.Pool{}, false, fmt.Errorf("update source of pool %q: %w", name, err) + } + cur.Source = source + } if err := tx.Commit(); err != nil { return model.Pool{}, false, fmt.Errorf("commit pool %q: %w", name, err) } return cur, false, nil default: _, err = tx.ExecContext(ctx, - `UPDATE pools SET spec = ?, generation = generation + 1, updated_at = ? WHERE name = ?`, - canon, formatTime(now), name) + `UPDATE pools SET spec = ?, source = ?, generation = generation + 1, updated_at = ? WHERE name = ?`, + canon, string(source), formatTime(now), name) if err != nil { return model.Pool{}, false, fmt.Errorf("update spec of pool %q: %w", name, err) } @@ -136,11 +147,12 @@ func (s *SQLite) PutPool(ctx context.Context, name string, spec model.PoolSpec) return model.Pool{}, false, fmt.Errorf("commit pool %q: %w", name, err) } cur.Spec = spec + cur.Source = source cur.UpdatedAt = now return cur, true, nil } -const poolSelect = `SELECT name, spec, generation, maintenance, created_at, updated_at FROM pools` +const poolSelect = `SELECT name, spec, source, generation, maintenance, created_at, updated_at FROM pools` // GetPool returns the pool; ErrNotFound if it does not exist. func (s *SQLite) GetPool(ctx context.Context, name string) (model.Pool, error) { @@ -329,15 +341,16 @@ func (s *SQLite) SetMeta(ctx context.Context, key, value string) error { // scanPool reads one pool row and also returns the stored spec text, which PutPool compares against. func scanPool(sc rowScanner) (model.Pool, string, error) { var p model.Pool - var specText, createdAt, updatedAt string + var specText, source, createdAt, updatedAt string var maintenance int64 - if err := sc.Scan(&p.Name, &specText, &p.Generation, &maintenance, &createdAt, &updatedAt); err != nil { + if err := sc.Scan(&p.Name, &specText, &source, &p.Generation, &maintenance, &createdAt, &updatedAt); err != nil { return model.Pool{}, "", err } if err := json.Unmarshal([]byte(specText), &p.Spec); err != nil { return model.Pool{}, "", fmt.Errorf("decode spec of pool %q: %w", p.Name, err) } var err error + p.Source = model.Source(source) p.Maintenance = maintenance != 0 if p.CreatedAt, err = parseTime(createdAt); err != nil { return model.Pool{}, "", fmt.Errorf("pool %q created_at: %w", p.Name, err) diff --git a/internal/store/store.go b/internal/store/store.go index 861b4bc..f0cc4bb 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -27,11 +27,23 @@ type Store interface { // (first insert = 1); maintenance and created_at are preserved. Returns the stored pool and // whether the spec changed. PutPool(ctx context.Context, name string, spec model.PoolSpec) (model.Pool, bool, error) + // PutPoolAs is PutPool for a declaration owned by source; the stored source is updated as well. + PutPoolAs(ctx context.Context, name string, spec model.PoolSpec, source model.Source) (model.Pool, bool, error) GetPool(ctx context.Context, name string) (model.Pool, error) ListPools(ctx context.Context) ([]model.Pool, error) DeletePool(ctx context.Context, name string) error SetMaintenance(ctx context.Context, name string, enabled bool) (model.Pool, error) + // PutEnvironment and PutGroup create or replace a declaration with the same generation rules as PutPool. + PutEnvironment(ctx context.Context, name string, spec model.EnvironmentSpec, source model.Source) (model.Environment, bool, error) + GetEnvironment(ctx context.Context, name string) (model.Environment, error) + ListEnvironments(ctx context.Context) ([]model.Environment, error) + DeleteEnvironment(ctx context.Context, name string) error + PutGroup(ctx context.Context, name string, spec model.GroupSpec, source model.Source) (model.Group, bool, error) + GetGroup(ctx context.Context, name string) (model.Group, error) + ListGroups(ctx context.Context) ([]model.Group, error) + DeleteGroup(ctx context.Context, name string) error + // CreateInstance inserts a new instance; ErrConflict if the id exists. CreateInstance(ctx context.Context, inst model.Instance) error // UpdateInstance replaces all fields of an existing instance; ErrNotFound if missing. diff --git a/web/app/types/grus-api.d.ts b/web/app/types/grus-api.d.ts index 87ba2d1..a9bf0ca 100644 --- a/web/app/types/grus-api.d.ts +++ b/web/app/types/grus-api.d.ts @@ -38,6 +38,48 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/environments": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** List environments */ + get: operations["list-environments"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/environments/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Get an environment */ + get: operations["get-environment"]; + /** + * Create or replace an environment + * @description Idempotent. Generation increases when the spec changes. Objects owned by Kubernetes answer 409. + */ + put: operations["put-environment"]; + post?: never; + /** + * Delete an environment + * @description Pools that still name it stop starting instances. Objects owned by Kubernetes answer 409. + */ + delete: operations["delete-environment"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/events": { parameters: { query?: never; @@ -58,6 +100,48 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/groups": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** List groups */ + get: operations["list-groups"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/groups/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Get a group */ + get: operations["get-group"]; + /** + * Create or replace a group + * @description Idempotent. Generation increases when the spec changes. Objects owned by Kubernetes answer 409. + */ + put: operations["put-group"]; + post?: never; + /** + * Delete a group + * @description Pools that still name it stop starting instances. Objects owned by Kubernetes answer 409. + */ + delete: operations["delete-group"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/instances": { parameters: { query?: never; @@ -164,6 +248,26 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/network": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get the network player count + * @description Players and capacity summed over all Ready and Allocated proxy instances. The SSE event network.players is published whenever the sum changes. + */ + get: operations["get-network"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/pools": { parameters: { query?: never; @@ -400,6 +504,44 @@ export interface components { /** @description Pool that gets the new instance */ pool: string; }; + Environment: { + /** + * Format: uri + * @description A URL to the JSON Schema for this object. + * @example https://example.com/schemas/Environment.json + */ + readonly $schema?: string; + /** Format: date-time */ + createdAt: string; + /** Format: int64 */ + generation: number; + name: string; + source: string; + spec: components["schemas"]["EnvironmentSpec"]; + /** Format: date-time */ + updatedAt: string; + }; + EnvironmentSpec: { + /** + * Format: uri + * @description A URL to the JSON Schema for this object. + * @example https://example.com/schemas/EnvironmentSpec.json + */ + readonly $schema?: string; + args?: string[] | null; + command?: string[] | null; + env?: { + [key: string]: string; + }; + gracePeriod?: string; + image?: string; + jvm?: components["schemas"]["JVM"]; + kind: string; + /** Format: int64 */ + port?: number; + readiness?: string; + stopCommand?: string; + }; ErrorDetail: { /** @description Where the error occurred, e.g. 'body.items[3].tags' or 'path.thing-id' */ location?: string; @@ -447,6 +589,38 @@ export interface components { */ type: string; }; + Group: { + /** + * Format: uri + * @description A URL to the JSON Schema for this object. + * @example https://example.com/schemas/Group.json + */ + readonly $schema?: string; + /** Format: date-time */ + createdAt: string; + /** Format: int64 */ + generation: number; + name: string; + source: string; + spec: components["schemas"]["GroupSpec"]; + /** Format: date-time */ + updatedAt: string; + }; + GroupSpec: { + /** + * Format: uri + * @description A URL to the JSON Schema for this object. + * @example https://example.com/schemas/GroupSpec.json + */ + readonly $schema?: string; + env?: { + [key: string]: string; + }; + labels?: { + [key: string]: string; + }; + templates?: components["schemas"]["TemplateRef"][] | null; + }; Instance: { /** * Format: uri @@ -480,6 +654,12 @@ export interface components { /** Format: date-time */ stateSince: string; }; + JVM: { + /** @description JVM flags placed before -Xmx and -jar */ + flags?: string[] | null; + /** @description Jar file inside the instance directory */ + jar?: string; + }; Lifecycle: { gracePeriod?: string; heartbeatTimeout?: string; @@ -495,6 +675,24 @@ export interface components { readonly $schema?: string; enabled: boolean; }; + NetworkStatus: { + /** + * Format: uri + * @description A URL to the JSON Schema for this object. + * @example https://example.com/schemas/NetworkStatus.json + */ + readonly $schema?: string; + /** Format: int64 */ + maxPlayers: number; + /** Format: int64 */ + players: number; + /** Format: int64 */ + proxies: number; + }; + Placement: { + driver?: string; + host?: string; + }; Pool: { /** * Format: uri @@ -508,6 +706,7 @@ export interface components { generation: number; maintenance: boolean; name: string; + source?: string; spec: components["schemas"]["PoolSpec"]; /** Format: date-time */ updatedAt: string; @@ -521,25 +720,35 @@ export interface components { readonly $schema?: string; args?: string[] | null; command?: string[] | null; - driver: string; + driver?: string; env?: { [key: string]: string; }; + environment?: string; + groups?: string[] | null; image?: string; labels?: { [key: string]: string; }; lifecycle?: components["schemas"]["Lifecycle"]; mode: string; + placement?: components["schemas"]["Placement"]; /** Format: int64 */ port?: number; priorityClassName?: string; + private?: components["schemas"]["Private"]; resources: components["schemas"]["Resources"]; role: string; scaling: components["schemas"]["Scaling"]; secretEnv?: components["schemas"]["SecretRef"][] | null; + sharding?: components["schemas"]["Sharding"]; templates?: components["schemas"]["TemplateRef"][] | null; }; + Private: { + idleTimeout?: string; + /** Format: int64 */ + quotaPerOwner?: number; + }; Resources: { cpu?: string; /** Format: int64 */ @@ -566,6 +775,15 @@ export interface components { name: string; secret: string; }; + Sharding: { + /** + * Format: int64 + * @description Cell edge length in chunks + */ + cellSize?: number; + /** @description Explicit cell names */ + cells?: string[] | null; + }; StatusUpdate: { /** * Format: uri @@ -664,6 +882,133 @@ export interface operations { }; }; }; + "list-environments": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Environment"][] | null; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; + "get-environment": { + parameters: { + query?: never; + header?: never; + path: { + /** @description Object name */ + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Environment"]; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; + "put-environment": { + parameters: { + query?: never; + header?: never; + path: { + /** @description Environment name */ + name: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["EnvironmentSpec"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Environment"]; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; + "delete-environment": { + parameters: { + query?: never; + header?: never; + path: { + /** @description Object name */ + name: string; + }; + cookie?: never; + }; + requestBody?: never; + 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"]; + }; + }; + }; + }; "stream-events": { parameters: { query?: never; @@ -702,6 +1047,133 @@ export interface operations { }; }; }; + "list-groups": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Group"][] | null; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; + "get-group": { + parameters: { + query?: never; + header?: never; + path: { + /** @description Object name */ + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Group"]; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; + "put-group": { + parameters: { + query?: never; + header?: never; + path: { + /** @description Group name */ + name: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["GroupSpec"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Group"]; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; + "delete-group": { + parameters: { + query?: never; + header?: never; + path: { + /** @description Object name */ + name: string; + }; + cookie?: never; + }; + requestBody?: never; + 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-instances": { parameters: { query?: { @@ -953,6 +1425,35 @@ export interface operations { }; }; }; + "get-network": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["NetworkStatus"]; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; "list-pools": { parameters: { query?: never;