From 5982fbebe23c7d8c6c803401ad2c25550e0d0b39 Mon Sep 17 00:00:00 2001 From: TheMeinerLP Date: Wed, 25 Nov 2026 10:36:40 +0100 Subject: [PATCH 1/5] feat(controller): name the custom resource in the managed-by-kubernetes conflict --- internal/controller/declarations.go | 12 +++++++++++- internal/controller/declarations_test.go | 12 ++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/internal/controller/declarations.go b/internal/controller/declarations.go index 9981bfc..16795be 100644 --- a/internal/controller/declarations.go +++ b/internal/controller/declarations.go @@ -15,11 +15,21 @@ 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 &managedError{kind: kind, name: name} } return nil } +// managedError is ErrManagedElsewhere with the custom resource the caller has to edit instead. +type managedError struct{ kind, name string } + +func (e *managedError) Error() string { + kind := strings.ToUpper(e.kind[:1]) + e.kind[1:] + return fmt.Sprintf("managed by Kubernetes custom resource %s/%s; edit it with kubectl", kind, e.name) +} + +func (e *managedError) Is(target error) bool { return target == ErrManagedElsewhere } + func validateName(name string) []model.FieldError { if poolNameRE.MatchString(name) { return nil diff --git a/internal/controller/declarations_test.go b/internal/controller/declarations_test.go index 78ebf6d..7da8c45 100644 --- a/internal/controller/declarations_test.go +++ b/internal/controller/declarations_test.go @@ -122,6 +122,18 @@ func TestV1PoolStillStartsWithItsInlineFields(t *testing.T) { } } +func TestManagedByKubernetesErrorNamesTheCustomResource(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) + } + err := f.c.DeletePool(f.ctx, "lobby", false) + want := "managed by Kubernetes custom resource Pool/lobby; edit it with kubectl" + if err == nil || err.Error() != want { + t.Errorf("error = %v, want %q", err, want) + } +} + func TestAPICannotChangeOrDeleteKubernetesManagedObjects(t *testing.T) { f := newFixture(t, Config{}) if _, err := f.c.ApplyPool(f.ctx, model.SourceKubernetes, "lobby", dynamicSpec(1, 0)); err != nil { From e3affe144b1a9ff3f16202924578161cce9f3800 Mon Sep 17 00:00:00 2001 From: TheMeinerLP Date: Wed, 25 Nov 2026 10:40:48 +0100 Subject: [PATCH 2/5] feat(crds): add the environment, group and pool custom resource definitions --- .../environments.grus.onelitefeather.net.yaml | 98 ++++++++++ .../crds/groups.grus.onelitefeather.net.yaml | 72 ++++++++ .../crds/pools.grus.onelitefeather.net.yaml | 170 ++++++++++++++++++ examples/crds/environment-minestom.yaml | 15 ++ examples/crds/group-lobby.yaml | 12 ++ examples/crds/pool-lobby.yaml | 21 +++ examples/crds/pool-mc01-lobby.yaml | 19 ++ 7 files changed, 407 insertions(+) create mode 100644 deploy/crds/environments.grus.onelitefeather.net.yaml create mode 100644 deploy/crds/groups.grus.onelitefeather.net.yaml create mode 100644 deploy/crds/pools.grus.onelitefeather.net.yaml create mode 100644 examples/crds/environment-minestom.yaml create mode 100644 examples/crds/group-lobby.yaml create mode 100644 examples/crds/pool-lobby.yaml create mode 100644 examples/crds/pool-mc01-lobby.yaml diff --git a/deploy/crds/environments.grus.onelitefeather.net.yaml b/deploy/crds/environments.grus.onelitefeather.net.yaml new file mode 100644 index 0000000..aae12f6 --- /dev/null +++ b/deploy/crds/environments.grus.onelitefeather.net.yaml @@ -0,0 +1,98 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: environments.grus.onelitefeather.net +spec: + group: grus.onelitefeather.net + scope: Namespaced + names: + kind: Environment + listKind: EnvironmentList + plural: environments + singular: environment + shortNames: [genv] + categories: [grus] + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Kind + type: string + jsonPath: .spec.kind + - name: Image + type: string + jsonPath: .spec.image + - name: Port + type: integer + jsonPath: .spec.port + - name: Ready + type: string + jsonPath: .status.conditions[?(@.type=="Ready")].status + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + description: How a Grus service runs, independent of what it serves. + required: [spec] + properties: + spec: + type: object + required: [kind] + properties: + kind: + type: string + enum: [jvm, native, container] + image: + type: string + command: + type: array + items: {type: string} + args: + type: array + items: {type: string} + jvm: + type: object + properties: + jar: + type: string + flags: + type: array + items: {type: string} + env: + type: object + additionalProperties: {type: string} + port: + type: integer + minimum: 0 + maximum: 65535 + readiness: + type: string + enum: [self, tcp] + stopCommand: + type: string + gracePeriod: + type: string + description: Go duration such as 30s. + status: + type: object + properties: + observedGeneration: + type: integer + format: int64 + conditions: + type: array + items: + type: object + required: [type, status] + properties: + type: {type: string} + status: {type: string} + reason: {type: string} + message: {type: string} + observedGeneration: {type: integer, format: int64} + lastTransitionTime: {type: string, format: date-time} diff --git a/deploy/crds/groups.grus.onelitefeather.net.yaml b/deploy/crds/groups.grus.onelitefeather.net.yaml new file mode 100644 index 0000000..63c310e --- /dev/null +++ b/deploy/crds/groups.grus.onelitefeather.net.yaml @@ -0,0 +1,72 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: groups.grus.onelitefeather.net +spec: + group: grus.onelitefeather.net + scope: Namespaced + names: + kind: Group + listKind: GroupList + plural: groups + singular: group + shortNames: [ggroup] + categories: [grus] + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Templates + type: string + jsonPath: .spec.templates[*].name + - name: Ready + type: string + jsonPath: .status.conditions[?(@.type=="Ready")].status + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + description: Templates, env and labels shared by many pools. + required: [spec] + properties: + spec: + type: object + properties: + templates: + type: array + items: + type: object + required: [name] + properties: + name: {type: string} + tag: {type: string} + digest: {type: string} + env: + type: object + additionalProperties: {type: string} + labels: + type: object + additionalProperties: {type: string} + status: + type: object + properties: + observedGeneration: + type: integer + format: int64 + conditions: + type: array + items: + type: object + required: [type, status] + properties: + type: {type: string} + status: {type: string} + reason: {type: string} + message: {type: string} + observedGeneration: {type: integer, format: int64} + lastTransitionTime: {type: string, format: date-time} diff --git a/deploy/crds/pools.grus.onelitefeather.net.yaml b/deploy/crds/pools.grus.onelitefeather.net.yaml new file mode 100644 index 0000000..adca039 --- /dev/null +++ b/deploy/crds/pools.grus.onelitefeather.net.yaml @@ -0,0 +1,170 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: pools.grus.onelitefeather.net +spec: + group: grus.onelitefeather.net + scope: Namespaced + names: + kind: Pool + listKind: PoolList + plural: pools + singular: pool + shortNames: [gpool] + categories: [grus] + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Environment + type: string + jsonPath: .spec.environment + - name: Placement + type: string + jsonPath: .spec.placement.driver + - name: Min + type: integer + jsonPath: .spec.scaling.min + - name: Max + type: integer + jsonPath: .spec.scaling.max + - name: Ready + type: integer + jsonPath: .status.readyReplicas + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + description: A set of interchangeable (dynamic) or fixed (static) instances of one service. + required: [spec] + properties: + spec: + type: object + required: [role, mode, resources, scaling] + properties: + role: + type: string + enum: [proxy, game, other] + mode: + type: string + enum: [dynamic, static] + driver: + type: string + description: v1 spelling of placement.driver. + placement: + type: object + properties: + driver: + type: string + enum: [kubernetes, agent, process] + host: + type: string + description: Agent host name, required for the agent driver. + environment: + type: string + groups: + type: array + items: {type: string} + sharding: + type: object + properties: + cellSize: {type: integer} + cells: + type: array + items: {type: string} + private: + type: object + properties: + quotaPerOwner: {type: integer} + idleTimeout: + type: string + description: Go duration such as 10m. + image: + type: string + command: + type: array + items: {type: string} + args: + type: array + items: {type: string} + env: + type: object + additionalProperties: {type: string} + secretEnv: + type: array + items: + type: object + required: [name, secret, key] + properties: + name: {type: string} + secret: {type: string} + key: {type: string} + resources: + type: object + required: [memoryMiB] + properties: + memoryMiB: {type: integer} + cpu: {type: string} + port: + type: integer + minimum: 0 + maximum: 65535 + templates: + type: array + items: + type: object + required: [name] + properties: + name: {type: string} + tag: {type: string} + digest: {type: string} + scaling: + type: object + required: [min, max] + properties: + min: {type: integer, minimum: 0} + max: {type: integer, minimum: 0} + buffer: {type: integer, minimum: 0} + capacity: {type: integer} + targetUtilization: {type: number} + scaleDownDelay: {type: string} + drainTimeout: {type: string} + maxSurge: {type: integer} + lifecycle: + type: object + properties: + stopCommand: {type: string} + gracePeriod: {type: string} + heartbeatTimeout: {type: string} + startTimeout: {type: string} + labels: + type: object + additionalProperties: {type: string} + priorityClassName: + type: string + status: + type: object + properties: + replicas: {type: integer} + readyReplicas: {type: integer} + allocatedReplicas: {type: integer} + observedGeneration: + type: integer + format: int64 + conditions: + type: array + items: + type: object + required: [type, status] + properties: + type: {type: string} + status: {type: string} + reason: {type: string} + message: {type: string} + observedGeneration: {type: integer, format: int64} + lastTransitionTime: {type: string, format: date-time} diff --git a/examples/crds/environment-minestom.yaml b/examples/crds/environment-minestom.yaml new file mode 100644 index 0000000..40c813f --- /dev/null +++ b/examples/crds/environment-minestom.yaml @@ -0,0 +1,15 @@ +apiVersion: grus.onelitefeather.net/v1alpha1 +kind: Environment +metadata: + name: minestom +spec: + kind: jvm + image: harbor.onelitefeather.dev/onelitefeather/grus-demo-minestom:IMAGE_TAG + jvm: + jar: server.jar + flags: ["-XX:+UseZGC"] + env: + JAVA_TOOL_OPTIONS: "-XX:MaxRAMPercentage=75" + port: 25565 + readiness: self + gracePeriod: 20s diff --git a/examples/crds/group-lobby.yaml b/examples/crds/group-lobby.yaml new file mode 100644 index 0000000..4b6d0df --- /dev/null +++ b/examples/crds/group-lobby.yaml @@ -0,0 +1,12 @@ +apiVersion: grus.onelitefeather.net/v1alpha1 +kind: Group +metadata: + name: lobby +spec: + templates: + - name: lobby-config + tag: stable + env: + GRUS_REGION: eu + labels: + network: onelitefeather diff --git a/examples/crds/pool-lobby.yaml b/examples/crds/pool-lobby.yaml new file mode 100644 index 0000000..49f79bd --- /dev/null +++ b/examples/crds/pool-lobby.yaml @@ -0,0 +1,21 @@ +# Runs in the cluster; the Kubernetes driver creates one pod per instance. +apiVersion: grus.onelitefeather.net/v1alpha1 +kind: Pool +metadata: + name: lobby +spec: + role: game + mode: dynamic + environment: minestom + groups: [lobby] + placement: + driver: kubernetes + resources: + memoryMiB: 512 + cpu: 250m + scaling: + min: 1 + max: 4 + buffer: 1 + capacity: 20 + scaleDownDelay: 2m diff --git a/examples/crds/pool-mc01-lobby.yaml b/examples/crds/pool-mc01-lobby.yaml new file mode 100644 index 0000000..ecb9b55 --- /dev/null +++ b/examples/crds/pool-mc01-lobby.yaml @@ -0,0 +1,19 @@ +# Runs on the registered agent host mc01 outside Kubernetes. +apiVersion: grus.onelitefeather.net/v1alpha1 +kind: Pool +metadata: + name: mc01-lobby +spec: + role: game + mode: dynamic + environment: minestom + groups: [lobby] + placement: + driver: agent + host: mc01 + resources: + memoryMiB: 1024 + scaling: + min: 1 + max: 2 + capacity: 20 From 5006abc9c39e083ee5a09d977f753a7b2f767149 Mon Sep 17 00:00:00 2001 From: TheMeinerLP Date: Wed, 25 Nov 2026 10:40:48 +0100 Subject: [PATCH 3/5] feat(controller): sync custom resources into the controller --- go.mod | 1 + go.sum | 2 + internal/kube/crdsync/convert.go | 38 +++ internal/kube/crdsync/doc.go | 10 + internal/kube/crdsync/helpers_test.go | 9 + internal/kube/crdsync/schema_test.go | 181 ++++++++++ internal/kube/crdsync/status.go | 182 ++++++++++ internal/kube/crdsync/syncer.go | 353 ++++++++++++++++++++ internal/kube/crdsync/syncer_test.go | 459 ++++++++++++++++++++++++++ 9 files changed, 1235 insertions(+) create mode 100644 internal/kube/crdsync/convert.go create mode 100644 internal/kube/crdsync/doc.go create mode 100644 internal/kube/crdsync/helpers_test.go create mode 100644 internal/kube/crdsync/schema_test.go create mode 100644 internal/kube/crdsync/status.go create mode 100644 internal/kube/crdsync/syncer.go create mode 100644 internal/kube/crdsync/syncer_test.go diff --git a/go.mod b/go.mod index 7002f8a..9390231 100644 --- a/go.mod +++ b/go.mod @@ -41,6 +41,7 @@ require ( github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/ncruces/go-strftime v1.1.0 // indirect github.com/philhofer/fwd v1.2.1 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/rs/xid v1.6.0 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect diff --git a/go.sum b/go.sum index 568c813..e80a33f 100644 --- a/go.sum +++ b/go.sum @@ -121,6 +121,8 @@ github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= diff --git a/internal/kube/crdsync/convert.go b/internal/kube/crdsync/convert.go new file mode 100644 index 0000000..13ac29c --- /dev/null +++ b/internal/kube/crdsync/convert.go @@ -0,0 +1,38 @@ +package crdsync + +import ( + "encoding/json" + "fmt" + "strings" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +// decodeSpec converts the spec of a custom resource into the domain spec through a JSON round trip. Unknown +// fields are ignored on purpose (the CRD schema prunes them anyway); a field of the wrong type is a +// decoding error that is reported to the user like a validation error. +func decodeSpec(obj *unstructured.Unstructured, into any) error { + spec, found, err := unstructured.NestedFieldNoCopy(obj.Object, "spec") + if err != nil || !found || spec == nil { + return nil + } + raw, err := json.Marshal(spec) + if err != nil { + return fmt.Errorf("spec: %w", err) + } + if err := json.Unmarshal(raw, into); err != nil { + return fmt.Errorf("spec: %w", err) + } + return nil +} + +// fieldMessage joins field errors into one condition message. +func fieldMessage(fields []model.FieldError) string { + parts := make([]string, 0, len(fields)) + for _, f := range fields { + parts = append(parts, f.Field+": "+f.Message) + } + return strings.Join(parts, "; ") +} diff --git a/internal/kube/crdsync/doc.go b/internal/kube/crdsync/doc.go new file mode 100644 index 0000000..574d2eb --- /dev/null +++ b/internal/kube/crdsync/doc.go @@ -0,0 +1,10 @@ +// Package crdsync mirrors the Grus custom resources (Environment, Group, Pool of API group +// grus.onelitefeather.net) of one namespace into the controller. A custom resource is applied with source +// kubernetes, which makes the stored object read-only through the REST API; deleting the resource removes +// it again. The outcome of every apply, and for pools the replica counts, are written back to the status +// subresource. +// +// The syncer is level-based: every event only triggers a reconcile of that one object from the informer +// cache, so a missed or reordered event cannot leave the store behind. Only the controller imports this +// package; the agent never touches Kubernetes. +package crdsync diff --git a/internal/kube/crdsync/helpers_test.go b/internal/kube/crdsync/helpers_test.go new file mode 100644 index 0000000..c64e08b --- /dev/null +++ b/internal/kube/crdsync/helpers_test.go @@ -0,0 +1,9 @@ +package crdsync + +import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + +var ( + metaGet = metav1.GetOptions{} + metaCreate = metav1.CreateOptions{} + metaDelete = metav1.DeleteOptions{} +) diff --git a/internal/kube/crdsync/schema_test.go b/internal/kube/crdsync/schema_test.go new file mode 100644 index 0000000..f3e66e3 --- /dev/null +++ b/internal/kube/crdsync/schema_test.go @@ -0,0 +1,181 @@ +package crdsync + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "sigs.k8s.io/yaml" + + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +// schemaNode is the part of an OpenAPI v3 schema these tests look at. +type schemaNode struct { + Type string `json:"type"` + Properties map[string]schemaNode `json:"properties"` + Items *schemaNode `json:"items"` + AdditionalProperties *schemaNode `json:"additionalProperties"` +} + +type crdFile struct { + Spec struct { + Group string `json:"group"` + Scope string `json:"scope"` + Names struct{ Kind, Plural string } + Versions []struct { + Name string `json:"name"` + Served bool `json:"served"` + Storage bool `json:"storage"` + Subresources struct { + Status *struct{} `json:"status"` + } `json:"subresources"` + Schema struct { + OpenAPIV3Schema schemaNode `json:"openAPIV3Schema"` + } `json:"schema"` + } `json:"versions"` + } `json:"spec"` +} + +func loadCRD(t *testing.T, name string) crdFile { + t.Helper() + raw, err := os.ReadFile(filepath.Join("..", "..", "..", "deploy", "crds", name+".grus.onelitefeather.net.yaml")) + if err != nil { + t.Fatalf("read CRD: %v", err) + } + var crd crdFile + if err := yaml.Unmarshal(raw, &crd); err != nil { + t.Fatalf("parse CRD %s: %v", name, err) + } + return crd +} + +// jsonFields maps the JSON field names of a struct type to the type of the field. +func jsonFields(t reflect.Type) map[string]reflect.Type { + out := map[string]reflect.Type{} + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + name := strings.Split(f.Tag.Get("json"), ",")[0] + if name == "" || name == "-" { + continue + } + out[name] = f.Type + } + return out +} + +// element strips pointers, slices and maps so that a struct inside them is found. +func element(t reflect.Type) reflect.Type { + for t.Kind() == reflect.Pointer || t.Kind() == reflect.Slice || t.Kind() == reflect.Map { + t = t.Elem() + } + return t +} + +// checkSchema compares a Go struct with a schema in both directions: every JSON field needs a schema +// property and every schema property a JSON field, recursively through nested structs. +func checkSchema(t *testing.T, path string, typ reflect.Type, node schemaNode) { + t.Helper() + fields := jsonFields(typ) + for name, ft := range fields { + prop, ok := node.Properties[name] + if !ok { + t.Errorf("%s.%s is a JSON field of %s but missing from the CRD schema", path, name, typ.Name()) + continue + } + if inner := element(ft); inner.Kind() == reflect.Struct && inner.PkgPath() == typ.PkgPath() { + sub := prop + if prop.Items != nil { + sub = *prop.Items + } + checkSchema(t, path+"."+name, inner, sub) + } + } + for name := range node.Properties { + if _, ok := fields[name]; !ok { + t.Errorf("%s.%s is in the CRD schema but not a JSON field of %s", path, name, typ.Name()) + } + } +} + +func TestCRDSchemasMatchTheDomainSpecs(t *testing.T) { + for _, tc := range []struct { + plural, kind string + spec reflect.Type + }{ + {"environments", "Environment", reflect.TypeOf(model.EnvironmentSpec{})}, + {"groups", "Group", reflect.TypeOf(model.GroupSpec{})}, + {"pools", "Pool", reflect.TypeOf(model.PoolSpec{})}, + } { + t.Run(tc.kind, func(t *testing.T) { + crd := loadCRD(t, tc.plural) + if crd.Spec.Group != Group || crd.Spec.Scope != "Namespaced" || crd.Spec.Names.Kind != tc.kind || crd.Spec.Names.Plural != tc.plural { + t.Fatalf("CRD identity = %+v", crd.Spec) + } + if len(crd.Spec.Versions) != 1 { + t.Fatalf("versions = %d, want 1", len(crd.Spec.Versions)) + } + v := crd.Spec.Versions[0] + if v.Name != Version || !v.Served || !v.Storage || v.Subresources.Status == nil { + t.Errorf("version = %+v, want served and stored %s with a status subresource", v, Version) + } + spec, ok := v.Schema.OpenAPIV3Schema.Properties["spec"] + if !ok { + t.Fatal("schema has no spec") + } + checkSchema(t, "spec", tc.spec, spec) + }) + } +} + +// strictDecode decodes a YAML document with unknown fields rejected. +func strictDecode(t *testing.T, raw []byte, into any) { + t.Helper() + js, err := yaml.YAMLToJSON(raw) + if err != nil { + t.Fatalf("yaml: %v", err) + } + var doc struct { + Spec json.RawMessage `json:"spec"` + } + if err := json.Unmarshal(js, &doc); err != nil { + t.Fatalf("json: %v", err) + } + dec := json.NewDecoder(bytes.NewReader(doc.Spec)) + dec.DisallowUnknownFields() + if err := dec.Decode(into); err != nil { + t.Fatalf("decode spec: %v", err) + } +} + +func TestExampleCustomResourcesAreValid(t *testing.T) { + dir := filepath.Join("..", "..", "..", "examples", "crds") + read := func(name string) []byte { + raw, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + return raw + } + var env model.EnvironmentSpec + strictDecode(t, read("environment-minestom.yaml"), &env) + if errs := env.WithDefaults().Validate(); len(errs) > 0 { + t.Errorf("environment-minestom: %v", errs) + } + var grp model.GroupSpec + strictDecode(t, read("group-lobby.yaml"), &grp) + if errs := grp.Validate(); len(errs) > 0 { + t.Errorf("group-lobby: %v", errs) + } + for _, name := range []string{"pool-lobby.yaml", "pool-mc01-lobby.yaml"} { + var pool model.PoolSpec + strictDecode(t, read(name), &pool) + if errs := pool.WithDefaults().Validate(); len(errs) > 0 { + t.Errorf("%s: %v", name, errs) + } + } +} diff --git a/internal/kube/crdsync/status.go b/internal/kube/crdsync/status.go new file mode 100644 index 0000000..89d57b0 --- /dev/null +++ b/internal/kube/crdsync/status.go @@ -0,0 +1,182 @@ +package crdsync + +import ( + "context" + "encoding/json" + "errors" + "time" + + "k8s.io/apimachinery/pkg/api/equality" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" + + "github.com/OneLiteFeatherNET/grus/internal/controller" + "github.com/OneLiteFeatherNET/grus/internal/model" + "github.com/OneLiteFeatherNET/grus/internal/store" +) + +// Reasons of the Ready condition. +const ( + ReasonApplied = "Applied" + ReasonProgressing = "Progressing" + ReasonInvalid = "Invalid" + ReasonConflict = "Conflict" + ReasonError = "Error" +) + +const conditionReady = "Ready" + +// result is the outcome of the last apply of one custom resource. +type result struct { + ok bool + reason string + message string +} + +func resultOf(err error) result { + var ve *controller.ValidationError + var de *decodeError + switch { + case err == nil: + return result{ok: true, reason: ReasonApplied} + case errors.As(err, &ve): + return result{reason: ReasonInvalid, message: fieldMessage(ve.Fields)} + case errors.As(err, &de): + return result{reason: ReasonInvalid, message: de.Error()} + case errors.Is(err, controller.ErrManagedElsewhere): + return result{reason: ReasonConflict, message: err.Error()} + default: + return result{reason: ReasonError, message: err.Error()} + } +} + +// writeStatus computes the status of obj and patches it into the status subresource when it changed. With +// force false, a change that only affects replica counts is skipped while the last write is younger than +// StatusInterval. The caller holds s.mu. +func (s *Syncer) writeStatus(ctx context.Context, k kindDef, obj *unstructured.Unstructured, force bool) { + name := obj.GetName() + id := key(k, name) + now := s.clock.Now() + res, ok := s.results[id] + if !ok { + return + } + // The informer cache lags behind our own writes, so the last written status is the better baseline. + current, ok := s.written[id] + if !ok { + current, _, _ = unstructured.NestedMap(obj.Object, "status") + } + desired, err := s.desiredStatus(ctx, k, obj, current, res, now) + if err != nil { + s.log.Error("crdsync: compute status", "kind", k.kind, "name", name, "error", err) + return + } + if equality.Semantic.DeepEqual(current, desired) { + return + } + if !force && sameButCounts(current, desired) && now.Sub(s.lastWrite[id]) < s.cfg.StatusInterval { + return + } + body, err := json.Marshal(map[string]any{"status": desired}) + if err != nil { + s.log.Error("crdsync: encode status", "kind", k.kind, "name", name, "error", err) + return + } + if _, err := s.client.Resource(k.gvr).Namespace(s.cfg.Namespace).Patch(ctx, name, types.MergePatchType, body, metav1.PatchOptions{}, "status"); err != nil { + s.log.Warn("crdsync: write status", "kind", k.kind, "name", name, "error", err) + return + } + s.lastWrite[id] = now + s.written[id] = desired +} + +// desiredStatus builds the status of obj from the apply result and, for pools, the instance counts. A +// condition whose status is unchanged keeps its lastTransitionTime. +func (s *Syncer) desiredStatus(ctx context.Context, k kindDef, obj *unstructured.Unstructured, current map[string]any, res result, now time.Time) (map[string]any, error) { + status := map[string]any{"observedGeneration": obj.GetGeneration()} + cond := map[string]any{ + "type": conditionReady, + "status": "True", + "reason": res.reason, + "message": res.message, + "observedGeneration": obj.GetGeneration(), + } + if !res.ok { + cond["status"] = "False" + } + if k.kind == "Pool" { + replicas, ready, allocated, err := s.countInstances(ctx, obj.GetName()) + if err != nil { + return nil, err + } + status["replicas"], status["readyReplicas"], status["allocatedReplicas"] = replicas, ready, allocated + if res.ok { + if min := minReplicas(obj); ready+allocated < min { + cond["status"] = "False" + cond["reason"] = ReasonProgressing + cond["message"] = "fewer instances are ready than scaling.min" + } + } + } + cond["lastTransitionTime"] = transitionTime(current, cond, now) + status["conditions"] = []any{cond} + return status, nil +} + +// transitionTime keeps the previous lastTransitionTime while the Ready status stays the same. +func transitionTime(current map[string]any, cond map[string]any, now time.Time) string { + conds, _ := current["conditions"].([]any) + for _, c := range conds { + m, ok := c.(map[string]any) + if !ok || m["type"] != conditionReady { + continue + } + if t, _ := m["lastTransitionTime"].(string); t != "" && m["status"] == cond["status"] { + return t + } + } + return now.UTC().Format(time.RFC3339) +} + +// minReplicas reads spec.scaling.min; a pool is Ready once that many instances are Ready or Allocated. +func minReplicas(obj *unstructured.Unstructured) int64 { + v, _, _ := unstructured.NestedInt64(obj.Object, "spec", "scaling", "min") + return v +} + +func (s *Syncer) countInstances(ctx context.Context, pool string) (replicas, ready, allocated int64, err error) { + insts, err := s.be.ListInstances(ctx, store.InstanceFilter{Pool: pool}) + if err != nil { + return 0, 0, 0, err + } + for _, i := range insts { + if i.State.Terminal() { + continue + } + replicas++ + switch i.State { + case model.StateReady: + ready++ + case model.StateAllocated: + allocated++ + } + } + return replicas, ready, allocated, nil +} + +// sameButCounts reports whether two statuses differ in nothing but the replica counts. +func sameButCounts(a, b map[string]any) bool { + strip := func(m map[string]any) map[string]any { + c := make(map[string]any, len(m)) + for k, v := range m { + switch k { + case "replicas", "readyReplicas", "allocatedReplicas": + default: + c[k] = v + } + } + return c + } + return equality.Semantic.DeepEqual(strip(a), strip(b)) +} diff --git a/internal/kube/crdsync/syncer.go b/internal/kube/crdsync/syncer.go new file mode 100644 index 0000000..90597d3 --- /dev/null +++ b/internal/kube/crdsync/syncer.go @@ -0,0 +1,353 @@ +package crdsync + +import ( + "context" + "errors" + "fmt" + "log/slog" + "sync" + "time" + + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/dynamic/dynamicinformer" + "k8s.io/client-go/tools/cache" + + "github.com/OneLiteFeatherNET/grus/internal/controller" + "github.com/OneLiteFeatherNET/grus/internal/model" + "github.com/OneLiteFeatherNET/grus/internal/store" +) + +// Group and Version of the custom resources. +const ( + Group = "grus.onelitefeather.net" + Version = "v1alpha1" +) + +const defaultStatusInterval = 10 * time.Second + +// Backend is what the syncer needs from the controller: the Applier to declare objects and read access to +// find the objects it owns and to count instances for the pool status. +type Backend interface { + controller.Applier + ListPools(ctx context.Context) ([]model.Pool, error) + ListEnvironments(ctx context.Context) ([]model.Environment, error) + ListGroups(ctx context.Context) ([]model.Group, error) + ListInstances(ctx context.Context, f store.InstanceFilter) ([]model.Instance, error) +} + +// Config holds the syncer settings. +type Config struct { + Namespace string // the only namespace that is watched (required) + Clock model.Clock // default model.SystemClock + Logger *slog.Logger // default slog.Default() + // StatusInterval is how often Tick runs in Run, and the minimum gap between two status writes of one + // pool that only differ in replica counts. Default 10s. + StatusInterval time.Duration +} + +// kindDef describes one custom resource kind and how it maps onto the Applier. +type kindDef struct { + kind string + gvr schema.GroupVersionResource + apply func(ctx context.Context, b Backend, name string, obj *unstructured.Unstructured) error + remove func(ctx context.Context, b Backend, name string) error + // owned lists the names of stored objects with source kubernetes. + owned func(ctx context.Context, b Backend) ([]string, error) +} + +func gvr(resource string) schema.GroupVersionResource { + return schema.GroupVersionResource{Group: Group, Version: Version, Resource: resource} +} + +var kinds = []kindDef{ + { + kind: "Environment", gvr: gvr("environments"), + apply: func(ctx context.Context, b Backend, name string, obj *unstructured.Unstructured) error { + var spec model.EnvironmentSpec + if err := decodeSpec(obj, &spec); err != nil { + return &decodeError{err} + } + _, err := b.ApplyEnvironment(ctx, model.SourceKubernetes, name, spec) + return err + }, + remove: func(ctx context.Context, b Backend, name string) error { + return b.RemoveEnvironment(ctx, model.SourceKubernetes, name) + }, + owned: func(ctx context.Context, b Backend) ([]string, error) { + items, err := b.ListEnvironments(ctx) + var names []string + for _, i := range items { + if i.Source == model.SourceKubernetes { + names = append(names, i.Name) + } + } + return names, err + }, + }, + { + kind: "Group", gvr: gvr("groups"), + apply: func(ctx context.Context, b Backend, name string, obj *unstructured.Unstructured) error { + var spec model.GroupSpec + if err := decodeSpec(obj, &spec); err != nil { + return &decodeError{err} + } + _, err := b.ApplyGroup(ctx, model.SourceKubernetes, name, spec) + return err + }, + remove: func(ctx context.Context, b Backend, name string) error { + return b.RemoveGroup(ctx, model.SourceKubernetes, name) + }, + owned: func(ctx context.Context, b Backend) ([]string, error) { + items, err := b.ListGroups(ctx) + var names []string + for _, i := range items { + if i.Source == model.SourceKubernetes { + names = append(names, i.Name) + } + } + return names, err + }, + }, + { + kind: "Pool", gvr: gvr("pools"), + apply: func(ctx context.Context, b Backend, name string, obj *unstructured.Unstructured) error { + var spec model.PoolSpec + if err := decodeSpec(obj, &spec); err != nil { + return &decodeError{err} + } + _, err := b.ApplyPool(ctx, model.SourceKubernetes, name, spec) + return err + }, + remove: func(ctx context.Context, b Backend, name string) error { + // Deleting the custom resource drains the pool like DELETE /v1/pools does. + return b.RemovePool(ctx, model.SourceKubernetes, name, true) + }, + owned: func(ctx context.Context, b Backend) ([]string, error) { + items, err := b.ListPools(ctx) + var names []string + for _, i := range items { + if i.Source == model.SourceKubernetes { + names = append(names, i.Name) + } + } + return names, err + }, + }, +} + +// decodeError is a spec that cannot be read into the domain type (wrong field type). +type decodeError struct{ err error } + +func (e *decodeError) Error() string { return e.err.Error() } + +// Syncer watches the custom resources of one namespace; see the package documentation. +type Syncer struct { + client dynamic.Interface + be Backend + cfg Config + clock model.Clock + log *slog.Logger + + mu sync.Mutex // serialises reconciles and status writes + ctx context.Context + informers map[string]cache.SharedIndexInformer // by kind + results map[string]result // by kind/name: outcome of the last apply + lastWrite map[string]time.Time // by kind/name: time of the last status write + written map[string]map[string]any // by kind/name: the last status written +} + +// New returns a syncer for cfg.Namespace. +func New(client dynamic.Interface, be Backend, cfg Config) *Syncer { + if cfg.Clock == nil { + cfg.Clock = model.SystemClock{} + } + if cfg.Logger == nil { + cfg.Logger = slog.Default() + } + if cfg.StatusInterval <= 0 { + cfg.StatusInterval = defaultStatusInterval + } + return &Syncer{ + client: client, be: be, cfg: cfg, clock: cfg.Clock, log: cfg.Logger, + informers: map[string]cache.SharedIndexInformer{}, + results: map[string]result{}, + lastWrite: map[string]time.Time{}, + written: map[string]map[string]any{}, + } +} + +// Run starts the informers, applies every custom resource, removes stored kubernetes objects whose resource +// is gone, and then keeps the store and the pool statuses in sync until ctx ends. +func (s *Syncer) Run(ctx context.Context) error { + if err := s.Start(ctx); err != nil { + return err + } + t := time.NewTicker(s.cfg.StatusInterval) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return nil + case <-t.C: + s.Tick(ctx) + } + } +} + +// Start runs the informers and the initial full sync and returns once both are done. +func (s *Syncer) Start(ctx context.Context) error { + s.ctx = ctx + factory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(s.client, 0, s.cfg.Namespace, nil) + for _, k := range kinds { + inf := factory.ForResource(k.gvr).Informer() + s.informers[k.kind] = inf + if _, err := inf.AddEventHandler(s.handler(k)); err != nil { + return fmt.Errorf("watch %s: %w", k.gvr.Resource, err) + } + } + factory.Start(ctx.Done()) + for gvr, ok := range factory.WaitForCacheSync(ctx.Done()) { + if !ok { + return fmt.Errorf("cache of %s did not sync", gvr.Resource) + } + } + return s.fullSync(ctx) +} + +// handler reconciles the object of every event except the initial list, which fullSync covers in order. +func (s *Syncer) handler(k kindDef) cache.ResourceEventHandler { + return cache.ResourceEventHandlerDetailedFuncs{ + AddFunc: func(obj any, initial bool) { + if !initial { + s.reconcileObj(k, obj) + } + }, + UpdateFunc: func(oldObj, newObj any) { + oldM, err1 := meta.Accessor(oldObj) + newM, err2 := meta.Accessor(newObj) + if err1 == nil && err2 == nil && oldM.GetGeneration() == newM.GetGeneration() && !s.failed(k, newM.GetName()) { + return // status or metadata only; our own status writes land here + } + s.reconcileObj(k, newObj) + }, + DeleteFunc: func(obj any) { + if t, ok := obj.(cache.DeletedFinalStateUnknown); ok { + obj = t.Obj + } + s.reconcileObj(k, obj) + }, + } +} + +func (s *Syncer) reconcileObj(k kindDef, obj any) { + m, err := meta.Accessor(obj) + if err != nil { + return + } + s.mu.Lock() + defer s.mu.Unlock() + s.reconcile(s.ctx, k, m.GetName()) +} + +func (s *Syncer) failed(k kindDef, name string) bool { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.results[key(k, name)] + return ok && !r.ok +} + +func key(k kindDef, name string) string { return k.kind + "/" + name } + +// fullSync applies every custom resource (environments and groups before pools) and removes the stored +// objects with source kubernetes that no longer have a custom resource. +func (s *Syncer) fullSync(ctx context.Context) error { + s.mu.Lock() + defer s.mu.Unlock() + for _, k := range kinds { + present := map[string]bool{} + for _, o := range s.informers[k.kind].GetStore().List() { + m, err := meta.Accessor(o) + if err != nil { + continue + } + present[m.GetName()] = true + s.reconcile(ctx, k, m.GetName()) + } + names, err := k.owned(ctx, s.be) + if err != nil { + return fmt.Errorf("list stored %s: %w", k.gvr.Resource, err) + } + for _, name := range names { + if !present[name] { + s.reconcile(ctx, k, name) + } + } + } + return nil +} + +// reconcile brings one object in line with its custom resource; the caller holds s.mu. A missing resource +// removes the stored object, but only when it is owned by kubernetes: an api object of the same name stays. +func (s *Syncer) reconcile(ctx context.Context, k kindDef, name string) { + raw, exists, err := s.informers[k.kind].GetStore().GetByKey(s.cfg.Namespace + "/" + name) + if err != nil { + s.log.Error("crdsync: read cache", "kind", k.kind, "name", name, "error", err) + return + } + id := key(k, name) + if !exists { + delete(s.results, id) + delete(s.lastWrite, id) + delete(s.written, id) + names, err := k.owned(ctx, s.be) + if err != nil { + s.log.Error("crdsync: list stored objects", "kind", k.kind, "error", err) + return + } + for _, n := range names { + if n != name { + continue + } + if err := k.remove(ctx, s.be, name); err != nil && !errors.Is(err, controller.ErrNotFound) { + s.log.Error("crdsync: remove", "kind", k.kind, "name", name, "error", err) + } + } + return + } + obj, ok := raw.(*unstructured.Unstructured) + if !ok { + return + } + res := resultOf(k.apply(ctx, s.be, name, obj)) + if !res.ok { + s.log.Warn("crdsync: apply rejected", "kind", k.kind, "name", name, "reason", res.reason, "message", res.message) + } + s.results[id] = res + s.writeStatus(ctx, k, obj, true) +} + +// Tick retries applies that failed and refreshes the pool statuses. Run calls it every StatusInterval. +func (s *Syncer) Tick(ctx context.Context) { + s.mu.Lock() + defer s.mu.Unlock() + for _, k := range kinds { + for _, o := range s.informers[k.kind].GetStore().List() { + m, err := meta.Accessor(o) + if err != nil { + continue + } + if r, ok := s.results[key(k, m.GetName())]; ok && !r.ok { + s.reconcile(ctx, k, m.GetName()) + continue + } + if k.kind == "Pool" { + if u, ok := o.(*unstructured.Unstructured); ok { + s.writeStatus(ctx, k, u, false) + } + } + } + } +} diff --git a/internal/kube/crdsync/syncer_test.go b/internal/kube/crdsync/syncer_test.go new file mode 100644 index 0000000..43385ba --- /dev/null +++ b/internal/kube/crdsync/syncer_test.go @@ -0,0 +1,459 @@ +package crdsync + +import ( + "context" + "fmt" + "io" + "log/slog" + "sync" + "testing" + "time" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + dynamicfake "k8s.io/client-go/dynamic/fake" + + "github.com/OneLiteFeatherNET/grus/internal/controller" + "github.com/OneLiteFeatherNET/grus/internal/model" + "github.com/OneLiteFeatherNET/grus/internal/store" +) + +const ns = "grus" + +var epoch = time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC) + +type fakeClock struct { + mu sync.Mutex + now time.Time +} + +func (c *fakeClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now } +func (c *fakeClock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = c.now.Add(d) +} + +// fakeBackend is an in-memory Backend. It rejects a pool without role like the real validation does and keeps +// the ownership rule of the controller: a kubernetes object cannot be changed by another source. +type fakeBackend struct { + mu sync.Mutex + pools map[string]model.Pool + envs map[string]model.Environment + groups map[string]model.Group + instances []model.Instance + removed []string + drained map[string]bool + changed chan struct{} +} + +func newBackend() *fakeBackend { + return &fakeBackend{ + pools: map[string]model.Pool{}, envs: map[string]model.Environment{}, groups: map[string]model.Group{}, + drained: map[string]bool{}, changed: make(chan struct{}, 100), + } +} + +func (b *fakeBackend) signal() { + select { + case b.changed <- struct{}{}: + default: + } +} + +func (b *fakeBackend) ApplyPool(_ context.Context, src model.Source, name string, spec model.PoolSpec) (model.Pool, error) { + b.mu.Lock() + defer b.mu.Unlock() + defer b.signal() + if spec.Role == "" { + return model.Pool{}, &controller.ValidationError{Fields: []model.FieldError{{Field: "role", Message: "must be proxy, game or other"}, {Field: "mode", Message: "must be dynamic or static"}}} + } + if cur, ok := b.pools[name]; ok && cur.Source == model.SourceKubernetes && src != model.SourceKubernetes { + return model.Pool{}, fmt.Errorf("%w", controller.ErrManagedElsewhere) + } + p := model.Pool{Name: name, Spec: spec, Source: src} + b.pools[name] = p + return p, nil +} + +func (b *fakeBackend) RemovePool(_ context.Context, _ model.Source, name string, drain bool) error { + b.mu.Lock() + defer b.mu.Unlock() + defer b.signal() + delete(b.pools, name) + b.removed = append(b.removed, "pool/"+name) + b.drained[name] = drain + return nil +} + +func (b *fakeBackend) ApplyEnvironment(_ context.Context, src model.Source, name string, spec model.EnvironmentSpec) (model.Environment, error) { + b.mu.Lock() + defer b.mu.Unlock() + defer b.signal() + e := model.Environment{Name: name, Spec: spec, Source: src} + b.envs[name] = e + return e, nil +} + +func (b *fakeBackend) RemoveEnvironment(_ context.Context, _ model.Source, name string) error { + b.mu.Lock() + defer b.mu.Unlock() + defer b.signal() + delete(b.envs, name) + b.removed = append(b.removed, "environment/"+name) + return nil +} + +func (b *fakeBackend) ApplyGroup(_ context.Context, src model.Source, name string, spec model.GroupSpec) (model.Group, error) { + b.mu.Lock() + defer b.mu.Unlock() + defer b.signal() + g := model.Group{Name: name, Spec: spec, Source: src} + b.groups[name] = g + return g, nil +} + +func (b *fakeBackend) RemoveGroup(_ context.Context, _ model.Source, name string) error { + b.mu.Lock() + defer b.mu.Unlock() + defer b.signal() + delete(b.groups, name) + b.removed = append(b.removed, "group/"+name) + return nil +} + +func (b *fakeBackend) ListPools(context.Context) ([]model.Pool, error) { + b.mu.Lock() + defer b.mu.Unlock() + var out []model.Pool + for _, p := range b.pools { + out = append(out, p) + } + return out, nil +} + +func (b *fakeBackend) ListEnvironments(context.Context) ([]model.Environment, error) { + b.mu.Lock() + defer b.mu.Unlock() + var out []model.Environment + for _, e := range b.envs { + out = append(out, e) + } + return out, nil +} + +func (b *fakeBackend) ListGroups(context.Context) ([]model.Group, error) { + b.mu.Lock() + defer b.mu.Unlock() + var out []model.Group + for _, g := range b.groups { + out = append(out, g) + } + return out, nil +} + +func (b *fakeBackend) ListInstances(_ context.Context, f store.InstanceFilter) ([]model.Instance, error) { + b.mu.Lock() + defer b.mu.Unlock() + var out []model.Instance + for _, i := range b.instances { + if f.Pool == "" || i.Pool == f.Pool { + out = append(out, i) + } + } + return out, nil +} + +func (b *fakeBackend) setInstances(i ...model.Instance) { + b.mu.Lock() + defer b.mu.Unlock() + b.instances = i +} + +func (b *fakeBackend) pool(name string) (model.Pool, bool) { + b.mu.Lock() + defer b.mu.Unlock() + p, ok := b.pools[name] + return p, ok +} + +func cr(kind, name string, generation int64, spec map[string]any) *unstructured.Unstructured { + return &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": Group + "/" + Version, + "kind": kind, + "metadata": map[string]any{"name": name, "namespace": ns, "generation": generation}, + "spec": spec, + }} +} + +func poolCR(name string, min int64) *unstructured.Unstructured { + return cr("Pool", name, 1, map[string]any{ + "role": "game", "mode": "dynamic", "environment": "minestom", + "placement": map[string]any{"driver": "kubernetes"}, + "resources": map[string]any{"memoryMiB": int64(512)}, + "scaling": map[string]any{"min": min, "max": int64(4)}, + }) +} + +func newClient(objs ...runtime.Object) *dynamicfake.FakeDynamicClient { + scheme := runtime.NewScheme() + lists := map[schema.GroupVersionResource]string{} + for _, k := range kinds { + lists[k.gvr] = k.kind + "List" + } + return dynamicfake.NewSimpleDynamicClientWithCustomListKinds(scheme, lists, objs...) +} + +func startSyncer(t *testing.T, client *dynamicfake.FakeDynamicClient, b *fakeBackend, clock model.Clock) *Syncer { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + s := New(client, b, Config{Namespace: ns, Clock: clock, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), StatusInterval: time.Minute}) + if err := s.Start(ctx); err != nil { + t.Fatalf("start: %v", err) + } + return s +} + +func getCR(t *testing.T, client *dynamicfake.FakeDynamicClient, kind, name string) *unstructured.Unstructured { + t.Helper() + for _, k := range kinds { + if k.kind == kind { + u, err := client.Resource(k.gvr).Namespace(ns).Get(context.Background(), name, metaGet) + if err != nil { + t.Fatalf("get %s/%s: %v", kind, name, err) + } + return u + } + } + t.Fatalf("unknown kind %s", kind) + return nil +} + +func readyCondition(t *testing.T, u *unstructured.Unstructured) map[string]any { + t.Helper() + conds, found, _ := unstructured.NestedSlice(u.Object, "status", "conditions") + if !found || len(conds) != 1 { + t.Fatalf("status.conditions = %v, want one Ready condition", conds) + } + return conds[0].(map[string]any) +} + +func waitFor(t *testing.T, b *fakeBackend, cond func() bool) { + t.Helper() + deadline := time.After(10 * time.Second) + for !cond() { + select { + case <-b.changed: + case <-deadline: + t.Fatal("timed out waiting for the backend to change") + } + } +} + +func TestStartAppliesEveryCustomResourceWithSourceKubernetes(t *testing.T) { + client := newClient( + cr("Environment", "minestom", 1, map[string]any{"kind": "jvm", "jvm": map[string]any{"jar": "server.jar"}}), + cr("Group", "lobby", 1, map[string]any{"labels": map[string]any{"network": "olf"}}), + poolCR("lobby", 1), + ) + b := newBackend() + startSyncer(t, client, b, &fakeClock{now: epoch}) + + if e := b.envs["minestom"]; e.Source != model.SourceKubernetes || e.Spec.JVM == nil || e.Spec.JVM.Jar != "server.jar" { + t.Errorf("environment = %+v", e) + } + if g := b.groups["lobby"]; g.Source != model.SourceKubernetes || g.Spec.Labels["network"] != "olf" { + t.Errorf("group = %+v", g) + } + p := b.pools["lobby"] + if p.Source != model.SourceKubernetes || p.Spec.Scaling.Max != 4 || p.Spec.EffectiveDriver() != model.DriverKubernetes { + t.Errorf("pool = %+v", p) + } +} + +func TestStartRemovesKubernetesObjectsWithoutCustomResourceButKeepsApiObjects(t *testing.T) { + b := newBackend() + b.pools["stale"] = model.Pool{Name: "stale", Source: model.SourceKubernetes} + b.pools["manual"] = model.Pool{Name: "manual", Source: model.SourceAPI} + b.envs["stale"] = model.Environment{Name: "stale", Source: model.SourceKubernetes} + b.groups["stale"] = model.Group{Name: "stale", Source: model.SourceKubernetes} + startSyncer(t, newClient(), b, &fakeClock{now: epoch}) + + if _, ok := b.pools["stale"]; ok { + t.Error("stale kubernetes pool was kept") + } + if !b.drained["stale"] { + t.Error("stale pool was removed without draining") + } + if _, ok := b.pools["manual"]; !ok { + t.Error("api pool was removed") + } + if len(b.envs) != 0 || len(b.groups) != 0 { + t.Errorf("stale environment or group kept: %v %v", b.envs, b.groups) + } +} + +func TestInvalidSpecIsReportedAsReadyFalseInvalid(t *testing.T) { + client := newClient(cr("Pool", "broken", 3, map[string]any{"resources": map[string]any{"memoryMiB": int64(512)}})) + b := newBackend() + startSyncer(t, client, b, &fakeClock{now: epoch}) + + cond := readyCondition(t, getCR(t, client, "Pool", "broken")) + if cond["status"] != "False" || cond["reason"] != ReasonInvalid { + t.Fatalf("condition = %v, want Ready=False Invalid", cond) + } + want := "role: must be proxy, game or other; mode: must be dynamic or static" + if cond["message"] != want { + t.Errorf("message = %q, want %q", cond["message"], want) + } + if cond["observedGeneration"] != int64(3) { + t.Errorf("observedGeneration = %v, want 3", cond["observedGeneration"]) + } + if _, ok := b.pool("broken"); ok { + t.Error("invalid pool was stored") + } +} + +func TestSpecWithWrongFieldTypeIsReportedAsInvalid(t *testing.T) { + client := newClient(cr("Pool", "typo", 1, map[string]any{"scaling": map[string]any{"min": "many"}})) + startSyncer(t, client, newBackend(), &fakeClock{now: epoch}) + + cond := readyCondition(t, getCR(t, client, "Pool", "typo")) + if cond["reason"] != ReasonInvalid { + t.Errorf("reason = %v, want Invalid; condition %v", cond["reason"], cond) + } +} + +func TestPoolStatusCountsInstancesAndBecomesReadyAtMin(t *testing.T) { + client := newClient(poolCR("lobby", 2)) + b := newBackend() + b.setInstances( + model.Instance{Pool: "lobby", State: model.StateReady}, + model.Instance{Pool: "lobby", State: model.StateAllocated}, + model.Instance{Pool: "lobby", State: model.StateStarting}, + model.Instance{Pool: "lobby", State: model.StateStopped}, + model.Instance{Pool: "other", State: model.StateReady}, + ) + startSyncer(t, client, b, &fakeClock{now: epoch}) + + u := getCR(t, client, "Pool", "lobby") + for field, want := range map[string]int64{"replicas": 3, "readyReplicas": 1, "allocatedReplicas": 1, "observedGeneration": 1} { + if got, _, _ := unstructured.NestedInt64(u.Object, "status", field); got != want { + t.Errorf("status.%s = %d, want %d", field, got, want) + } + } + cond := readyCondition(t, u) + if cond["status"] != "True" || cond["reason"] != ReasonApplied { + t.Errorf("condition = %v, want Ready=True Applied", cond) + } +} + +func TestPoolIsNotReadyBelowMin(t *testing.T) { + client := newClient(poolCR("lobby", 2)) + startSyncer(t, client, newBackend(), &fakeClock{now: epoch}) + + cond := readyCondition(t, getCR(t, client, "Pool", "lobby")) + if cond["status"] != "False" || cond["reason"] != ReasonProgressing { + t.Errorf("condition = %v, want Ready=False Progressing", cond) + } +} + +func TestTickDebouncesCountOnlyChanges(t *testing.T) { + client := newClient(poolCR("lobby", 0)) + b := newBackend() + clock := &fakeClock{now: epoch} + s := startSyncer(t, client, b, clock) + ctx := context.Background() + + b.setInstances(model.Instance{Pool: "lobby", State: model.StateReady}) + clock.advance(10 * time.Second) + s.Tick(ctx) + if got, _, _ := unstructured.NestedInt64(getCR(t, client, "Pool", "lobby").Object, "status", "readyReplicas"); got != 0 { + t.Fatalf("readyReplicas = %d within the debounce window, want the old 0", got) + } + + clock.advance(time.Minute) + s.Tick(ctx) + if got, _, _ := unstructured.NestedInt64(getCR(t, client, "Pool", "lobby").Object, "status", "readyReplicas"); got != 1 { + t.Fatalf("readyReplicas = %d after the debounce window, want 1", got) + } +} + +func TestLastTransitionTimeSurvivesCountChanges(t *testing.T) { + client := newClient(poolCR("lobby", 0)) + b := newBackend() + clock := &fakeClock{now: epoch} + s := startSyncer(t, client, b, clock) + + first := readyCondition(t, getCR(t, client, "Pool", "lobby"))["lastTransitionTime"] + b.setInstances(model.Instance{Pool: "lobby", State: model.StateReady}) + clock.advance(2 * time.Minute) + s.Tick(context.Background()) + if got := readyCondition(t, getCR(t, client, "Pool", "lobby"))["lastTransitionTime"]; got != first { + t.Errorf("lastTransitionTime = %v, want unchanged %v", got, first) + } +} + +func TestNewCustomResourceIsAppliedAndDeletionDrainsThePool(t *testing.T) { + client := newClient() + b := newBackend() + startSyncer(t, client, b, &fakeClock{now: epoch}) + pools := client.Resource(kinds[2].gvr).Namespace(ns) + + if _, err := pools.Create(context.Background(), poolCR("lobby", 1), metaCreate); err != nil { + t.Fatalf("create: %v", err) + } + waitFor(t, b, func() bool { _, ok := b.pool("lobby"); return ok }) + + if err := pools.Delete(context.Background(), "lobby", metaDelete); err != nil { + t.Fatalf("delete: %v", err) + } + waitFor(t, b, func() bool { _, ok := b.pool("lobby"); return !ok }) + b.mu.Lock() + defer b.mu.Unlock() + if !b.drained["lobby"] { + t.Error("pool was removed without drain") + } +} + +func TestDeletingACustomResourceKeepsAnApiObjectOfTheSameName(t *testing.T) { + client := newClient(poolCR("lobby", 1)) + b := newBackend() + s := startSyncer(t, client, b, &fakeClock{now: epoch}) + + b.mu.Lock() + b.pools["lobby"] = model.Pool{Name: "lobby", Source: model.SourceAPI} + b.mu.Unlock() + // Drop the resource from the informer cache, as the watch does when it is deleted. + inf := s.informers["Pool"].GetStore() + cached, _, _ := inf.GetByKey(ns + "/lobby") + if err := inf.Delete(cached); err != nil { + t.Fatalf("drop from cache: %v", err) + } + s.mu.Lock() + s.reconcile(context.Background(), kinds[2], "lobby") + s.mu.Unlock() + + if p, ok := b.pool("lobby"); !ok || p.Source != model.SourceAPI { + t.Errorf("api pool = %+v, %v; want it kept", p, ok) + } +} + +func TestRejectedApplyIsRetriedOnTick(t *testing.T) { + client := newClient(poolCR("lobby", 1)) + b := newBackend() + b.pools["lobby"] = model.Pool{Name: "lobby", Source: model.SourceKubernetes} + s := startSyncer(t, client, b, &fakeClock{now: epoch}) + // A conflicting change by another source cannot happen with this fake; model a transient failure instead. + s.mu.Lock() + s.results["Pool/lobby"] = result{reason: ReasonError, message: "boom"} + s.mu.Unlock() + + s.Tick(context.Background()) + + if cond := readyCondition(t, getCR(t, client, "Pool", "lobby")); cond["reason"] == ReasonError { + t.Errorf("condition = %v, want the retried apply to clear the error", cond) + } +} From 4eef749498fde63e48e0591e064afd9b30f30bcf Mon Sep 17 00:00:00 2001 From: TheMeinerLP Date: Wed, 25 Nov 2026 10:40:48 +0100 Subject: [PATCH 4/5] feat(controller): start the custom resource sync with GRUS_CRDS --- cmd/grus/config.go | 8 ++++++ cmd/grus/config_crds_test.go | 42 ++++++++++++++++++++++++++++++ cmd/grus/controller.go | 1 + cmd/grus/crds.go | 50 ++++++++++++++++++++++++++++++++++++ 4 files changed, 101 insertions(+) create mode 100644 cmd/grus/config_crds_test.go create mode 100644 cmd/grus/crds.go diff --git a/cmd/grus/config.go b/cmd/grus/config.go index 9cc165f..3f1b48d 100644 --- a/cmd/grus/config.go +++ b/cmd/grus/config.go @@ -39,6 +39,7 @@ type config struct { AdminToken string ProcessDir string ReconcileInterval time.Duration + CRDs bool } // loadConfig parses args (the controller flags) on top of the environment read through getenv. @@ -72,6 +73,7 @@ func loadConfig(args []string, getenv func(string) string) (config, error) { debugEndpoints := str("debug-endpoints", "GRUS_DEBUG_ENDPOINTS", "false", "enable the admin debug endpoints (true/false)") hostID := str("host-id", "GRUS_HOST_ID", "", "host id; default k8s- or local") processDir := str("process-dir", "GRUS_PROCESS_DIR", "./instances", "working directories of the process driver") + crds := str("crds", "GRUS_CRDS", "false", "watch the Grus custom resources of the namespace (true/false)") interval := str("reconcile-interval", "GRUS_RECONCILE_INTERVAL", "5s", "reconcile interval") if err := fs.Parse(args); err != nil { @@ -119,6 +121,9 @@ func loadConfig(args []string, getenv func(string) string) (config, error) { if cfg.ReconcileInterval, err = time.ParseDuration(*interval); err != nil { return config{}, fmt.Errorf("GRUS_RECONCILE_INTERVAL: %w", err) } + if cfg.CRDs, err = strconv.ParseBool(*crds); err != nil { + return config{}, fmt.Errorf("GRUS_CRDS: %w", err) + } if cfg.S3Insecure, err = strconv.ParseBool(*s3Insecure); err != nil { return config{}, fmt.Errorf("GRUS_S3_INSECURE: %w", err) } @@ -145,6 +150,9 @@ func (c config) validate() error { if c.PublicURL == "" { return errors.New("GRUS_PUBLIC_URL is required") } + if c.CRDs && c.Namespace == "" { + return errors.New("GRUS_NAMESPACE is required for GRUS_CRDS") + } switch c.TemplatesBackend { case "fs": case "s3": diff --git a/cmd/grus/config_crds_test.go b/cmd/grus/config_crds_test.go new file mode 100644 index 0000000..624faa4 --- /dev/null +++ b/cmd/grus/config_crds_test.go @@ -0,0 +1,42 @@ +package main + +import "testing" + +func TestLoadConfigCRDsDefaultToOff(t *testing.T) { + cfg, err := loadConfig(nil, fakeEnv(validEnv())) + if err != nil { + t.Fatalf("loadConfig: %v", err) + } + if cfg.CRDs { + t.Error("CRDs = true, want false by default") + } +} + +func TestLoadConfigReadsCRDsFlagFromEnvironment(t *testing.T) { + env := validEnv() + env["GRUS_CRDS"] = "true" + env["GRUS_NAMESPACE"] = "grus-dev" + cfg, err := loadConfig(nil, fakeEnv(env)) + if err != nil { + t.Fatalf("loadConfig: %v", err) + } + if !cfg.CRDs { + t.Error("CRDs = false, want true from GRUS_CRDS") + } +} + +func TestLoadConfigRejectsCRDsWithoutNamespace(t *testing.T) { + env := validEnv() + env["GRUS_CRDS"] = "true" + if _, err := loadConfig(nil, fakeEnv(env)); err == nil { + t.Fatal("loadConfig accepted GRUS_CRDS without GRUS_NAMESPACE") + } +} + +func TestLoadConfigRejectsInvalidCRDsValue(t *testing.T) { + env := validEnv() + env["GRUS_CRDS"] = "maybe" + if _, err := loadConfig(nil, fakeEnv(env)); err == nil { + t.Fatal("loadConfig accepted GRUS_CRDS=maybe") + } +} diff --git a/cmd/grus/controller.go b/cmd/grus/controller.go index b2fc718..0864780 100644 --- a/cmd/grus/controller.go +++ b/cmd/grus/controller.go @@ -141,6 +141,7 @@ func runController(args []string) error { ctrlErr = s.ctrl.Run(ctrlCtx) close(ctrlExited) }() + startCRDSync(ctrlCtx, cfg, s, logger) logger.Info("controller started", "listen", cfg.Listen, "driver", s.drv.Name(), "host", s.drv.Host()) var runErr error diff --git a/cmd/grus/crds.go b/cmd/grus/crds.go new file mode 100644 index 0000000..237ef6c --- /dev/null +++ b/cmd/grus/crds.go @@ -0,0 +1,50 @@ +package main + +import ( + "context" + "fmt" + "log/slog" + + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + + "github.com/OneLiteFeatherNET/grus/internal/kube/crdsync" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +// newCRDSyncer builds the custom resource syncer on the in-cluster config. It watches only the controller's +// own namespace, so the chart needs a namespaced Role and no ClusterRole. +func newCRDSyncer(cfg config, s *stack, logger *slog.Logger) (*crdsync.Syncer, error) { + restCfg, err := rest.InClusterConfig() + if err != nil { + return nil, fmt.Errorf("in-cluster config: %w", err) + } + client, err := dynamic.NewForConfig(restCfg) + if err != nil { + return nil, fmt.Errorf("dynamic client: %w", err) + } + return crdsync.New(client, s.ctrl, crdsync.Config{ + Namespace: cfg.Namespace, + Clock: model.SystemClock{}, + Logger: logger, + }), nil +} + +// startCRDSync runs the syncer in the background when GRUS_CRDS is set. A failure is logged and does not stop +// the controller: the REST API and the api-owned declarations keep working without the custom resources. +func startCRDSync(ctx context.Context, cfg config, s *stack, logger *slog.Logger) { + if !cfg.CRDs { + return + } + syncer, err := newCRDSyncer(cfg, s, logger) + if err != nil { + logger.Error("custom resource sync disabled", "error", err) + return + } + go func() { + if err := syncer.Run(ctx); err != nil { + logger.Error("custom resource sync stopped", "error", err) + } + }() + logger.Info("custom resource sync started", "namespace", cfg.Namespace) +} From 3fa49a46208831431a6a9c7cbbc8c9ed6ae77b55 Mon Sep 17 00:00:00 2001 From: TheMeinerLP Date: Wed, 25 Nov 2026 10:40:48 +0100 Subject: [PATCH 5/5] feat(chart): add crds.watch with namespaced rights for the custom resources --- deploy/helm/grus/templates/deployment.yaml | 2 ++ deploy/helm/grus/templates/role.yaml | 9 +++++++++ deploy/helm/grus/values.yaml | 6 ++++++ 3 files changed, 17 insertions(+) diff --git a/deploy/helm/grus/templates/deployment.yaml b/deploy/helm/grus/templates/deployment.yaml index 846079e..fe6dcd5 100644 --- a/deploy/helm/grus/templates/deployment.yaml +++ b/deploy/helm/grus/templates/deployment.yaml @@ -136,6 +136,8 @@ spec: value: {{ int .Values.controller.maxInstances | quote }} - name: GRUS_DEBUG_ENDPOINTS value: {{ ternary "true" "false" .Values.controller.debugEndpoints | quote }} + - name: GRUS_CRDS + value: {{ ternary "true" "false" .Values.crds.watch | quote }} - name: GRUS_HOST_ID value: {{ printf "k8s-%s" .Release.Namespace | quote }} - name: GRUS_ADMIN_TOKEN diff --git a/deploy/helm/grus/templates/role.yaml b/deploy/helm/grus/templates/role.yaml index 0562e1d..f55bdfc 100644 --- a/deploy/helm/grus/templates/role.yaml +++ b/deploy/helm/grus/templates/role.yaml @@ -22,3 +22,12 @@ rules: - apiGroups: [""] resources: ["events"] verbs: ["create"] + {{- if .Values.crds.watch }} + # Custom resources of this namespace only: the controller reads them and reports the status of pools. + - apiGroups: ["grus.onelitefeather.net"] + resources: ["environments", "groups", "pools"] + verbs: ["get", "list", "watch"] + - apiGroups: ["grus.onelitefeather.net"] + resources: ["environments/status", "groups/status", "pools/status"] + verbs: ["get", "update", "patch"] + {{- end }} diff --git a/deploy/helm/grus/values.yaml b/deploy/helm/grus/values.yaml index 0bb8b20..c4c290e 100644 --- a/deploy/helm/grus/values.yaml +++ b/deploy/helm/grus/values.yaml @@ -34,6 +34,12 @@ controller: # Additional controller environment variables, name: value. extraEnv: {} +# Custom resources (Environment, Group, Pool of grus.onelitefeather.net). The chart does not install the +# CRDs: apply deploy/crds of the repository separately (FLUX ships them). With watch enabled the controller +# applies the resources of its own namespace and the namespaced Role gains the matching rights. +crds: + watch: false + # Settings the controller applies to every instance pod it creates. instances: # Names of image pull Secrets the instance pods use (passed on as GRUS_IMAGE_PULL_SECRETS).