diff --git a/changelog/unreleased/1000-load-balancer-class.md b/changelog/unreleased/1000-load-balancer-class.md new file mode 100644 index 000000000..5c76c03d4 --- /dev/null +++ b/changelog/unreleased/1000-load-balancer-class.md @@ -0,0 +1,9 @@ +# Choose a server's load-balancer implementation + +A LoadBalancer server can set `spec.networking.loadBalancerClass` to pick +which load-balancer implementation handles its Service, for a cluster that +runs more than one. Changing it replaces the Service, since Kubernetes +doesn't allow changing a Service's class in place, and the server usually +gets a new external address; see +[Choosing a Load-Balancer Implementation](../../docs/networking.md#choosing-a-load-balancer-implementation). +[PR #1000](https://github.com/GameplanePanel/Gameplane/pull/1000) diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backups.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backups.yaml index 9ecadb2f6..ab6f94ab6 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backups.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backups.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: backups.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupschedules.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupschedules.yaml index 759a17245..16068f43b 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupschedules.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupschedules.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: backupschedules.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_clusters.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_clusters.yaml index f2c756d6a..11799d962 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_clusters.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_clusters.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: clusters.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gameservers.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gameservers.yaml index 2a52c5826..330f7d527 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gameservers.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gameservers.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: gameservers.gameplane.local spec: @@ -1405,6 +1405,25 @@ spec: maxLength: 253 pattern: ^([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?)(\.[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?)*$ type: string + loadBalancerClass: + description: |- + LoadBalancerClass selects the load-balancer implementation for the + fronting Service (service.spec.loadBalancerClass), for a cluster that + runs more than one, or a custom one for game traffic. It only takes + effect when Expose=LoadBalancer. Kubernetes doesn't allow changing a + Service's class, so when this changes the operator replaces the + Service, which gets a new cluster IP and, usually, a new external + address. Unset leaves the Service's class as it is. The value is a + Kubernetes qualified name: an optional DNS-subdomain prefix and a + slash, then a name of at most 63 characters. The prefix is at most 253 + characters, so the whole value is at most 317. + maxLength: 317 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$ + type: string + x-kubernetes-validations: + - message: the loadBalancerClass prefix must be at most 253 characters + rule: '!self.contains(''/'') || self.split(''/'')[0].size() + <= 253' portOverrides: description: |- PortOverrides lets the user pin a specific NodePort or override diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gametemplates.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gametemplates.yaml index 4574c3c4a..decb5f8c5 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gametemplates.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gametemplates.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: gametemplates.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modules.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modules.yaml index c5ae2ed39..2a9063c05 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modules.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modules.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: modules.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modulesources.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modulesources.yaml index 4797a4d40..7d34c746f 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modulesources.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modulesources.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: modulesources.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_networkcaptures.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_networkcaptures.yaml index 02450de8b..a1504a605 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_networkcaptures.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_networkcaptures.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: networkcaptures.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_restores.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_restores.yaml index 96c64f674..3edcd9fca 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_restores.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_restores.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: restores.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_backups.yaml b/charts/gameplane/crd-manifests/gameplane.local_backups.yaml index 9ecadb2f6..ab6f94ab6 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_backups.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_backups.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: backups.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_backupschedules.yaml b/charts/gameplane/crd-manifests/gameplane.local_backupschedules.yaml index 759a17245..16068f43b 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_backupschedules.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_backupschedules.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: backupschedules.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_clusters.yaml b/charts/gameplane/crd-manifests/gameplane.local_clusters.yaml index f2c756d6a..11799d962 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_clusters.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_clusters.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: clusters.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_gameservers.yaml b/charts/gameplane/crd-manifests/gameplane.local_gameservers.yaml index 2a52c5826..330f7d527 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_gameservers.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_gameservers.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: gameservers.gameplane.local spec: @@ -1405,6 +1405,25 @@ spec: maxLength: 253 pattern: ^([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?)(\.[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?)*$ type: string + loadBalancerClass: + description: |- + LoadBalancerClass selects the load-balancer implementation for the + fronting Service (service.spec.loadBalancerClass), for a cluster that + runs more than one, or a custom one for game traffic. It only takes + effect when Expose=LoadBalancer. Kubernetes doesn't allow changing a + Service's class, so when this changes the operator replaces the + Service, which gets a new cluster IP and, usually, a new external + address. Unset leaves the Service's class as it is. The value is a + Kubernetes qualified name: an optional DNS-subdomain prefix and a + slash, then a name of at most 63 characters. The prefix is at most 253 + characters, so the whole value is at most 317. + maxLength: 317 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$ + type: string + x-kubernetes-validations: + - message: the loadBalancerClass prefix must be at most 253 characters + rule: '!self.contains(''/'') || self.split(''/'')[0].size() + <= 253' portOverrides: description: |- PortOverrides lets the user pin a specific NodePort or override diff --git a/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml b/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml index 4574c3c4a..decb5f8c5 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: gametemplates.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_modules.yaml b/charts/gameplane/crd-manifests/gameplane.local_modules.yaml index c5ae2ed39..2a9063c05 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_modules.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_modules.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: modules.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_modulesources.yaml b/charts/gameplane/crd-manifests/gameplane.local_modulesources.yaml index 4797a4d40..7d34c746f 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_modulesources.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_modulesources.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: modulesources.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_networkcaptures.yaml b/charts/gameplane/crd-manifests/gameplane.local_networkcaptures.yaml index 02450de8b..a1504a605 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_networkcaptures.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_networkcaptures.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: networkcaptures.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_restores.yaml b/charts/gameplane/crd-manifests/gameplane.local_restores.yaml index 96c64f674..3edcd9fca 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_restores.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_restores.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: b409bc125837ec9256cb4968d3f98a162c9a145dee35b16c22f39498a9892e64 + gameplane.local/crd-bundle-sha256: 11dd82c4242b31a0d15e684de63c02fcf78f2a316feb2e8dd3ad2a51ff923037 controller-gen.kubebuilder.io/version: v0.22.0 name: restores.gameplane.local spec: diff --git a/docs/networking.md b/docs/networking.md index a28fdaa39..e60750523 100644 --- a/docs/networking.md +++ b/docs/networking.md @@ -302,6 +302,31 @@ created before the upgrade that introduced it. A hostname that doesn't resolve to its server would now be shown to players, so before upgrading, check each such hostname, or clear it where it isn't the name players use. +## Choosing a Load-Balancer Implementation + +A cluster can run more than one load-balancer implementation, each handling +Services of its own class: a cloud's, MetalLB, Tailscale's operator, or a +custom one for game traffic. Set `spec.networking.loadBalancerClass` on a +LoadBalancer server to pick one; it becomes the Service's +`spec.loadBalancerClass`. Unset, the operator doesn't manage the class: a new +Service has none, so the cluster's default implementation handles it, and an +existing Service keeps any class something else gave it. + +Kubernetes doesn't allow changing a Service's class, or adding one to a +LoadBalancer Service that has none, so when the field is set or changes, the +operator deletes the Service and creates it again with the new class. The server keeps running, but its Service gets a new cluster IP and, +usually, a new external address, so players reconnect. Removing the field +leaves the Service's class as it is until the Service is next replaced. The +class is a Kubernetes qualified name, such as `example.com/games`: the part +after the slash is at most 63 characters. The dashboard doesn't edit the +class, and keeps it when you save other networking settings; set it through +the API or `kubectl`. + +An address pool or address (`addressPool`, `address`) is a request to the +configured address manager; a Service of another class is outside that +manager's control, so leave them unset with a class of another +implementation. + ## Related - [`install.md`](install.md) — Helm chart values for `operator.addressManager` and cluster prerequisites. diff --git a/operator/api/v1alpha1/gameserver_types.go b/operator/api/v1alpha1/gameserver_types.go index 605648b85..184b13f26 100644 --- a/operator/api/v1alpha1/gameserver_types.go +++ b/operator/api/v1alpha1/gameserver_types.go @@ -328,6 +328,22 @@ type GameServerNetworking struct { // +optional PortOverrides []PortOverride `json:"portOverrides,omitempty"` + // LoadBalancerClass selects the load-balancer implementation for the + // fronting Service (service.spec.loadBalancerClass), for a cluster that + // runs more than one, or a custom one for game traffic. It only takes + // effect when Expose=LoadBalancer. Kubernetes doesn't allow changing a + // Service's class, so when this changes the operator replaces the + // Service, which gets a new cluster IP and, usually, a new external + // address. Unset leaves the Service's class as it is. The value is a + // Kubernetes qualified name: an optional DNS-subdomain prefix and a + // slash, then a name of at most 63 characters. The prefix is at most 253 + // characters, so the whole value is at most 317. + // +kubebuilder:validation:MaxLength=317 + // +kubebuilder:validation:XValidation:rule="!self.contains('/') || self.split('/')[0].size() <= 253",message="the loadBalancerClass prefix must be at most 253 characters" + // +kubebuilder:validation:Pattern=`^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$` + // +optional + LoadBalancerClass *string `json:"loadBalancerClass,omitempty"` + // SourceRanges is an IP allow-list (CIDRs) for the fronting Service. It // maps to service.spec.loadBalancerSourceRanges and therefore only takes // effect when Expose=LoadBalancer (cloud LBs that honor it); it is diff --git a/operator/api/v1alpha1/zz_generated.deepcopy.go b/operator/api/v1alpha1/zz_generated.deepcopy.go index 40978d948..b10d634f5 100644 --- a/operator/api/v1alpha1/zz_generated.deepcopy.go +++ b/operator/api/v1alpha1/zz_generated.deepcopy.go @@ -983,6 +983,11 @@ func (in *GameServerNetworking) DeepCopyInto(out *GameServerNetworking) { *out = make([]PortOverride, len(*in)) copy(*out, *in) } + if in.LoadBalancerClass != nil { + in, out := &in.LoadBalancerClass, &out.LoadBalancerClass + *out = new(string) + **out = **in + } if in.SourceRanges != nil { in, out := &in.SourceRanges, &out.SourceRanges *out = make([]string, len(*in)) diff --git a/operator/config/crd/gameplane.local_gameservers.yaml b/operator/config/crd/gameplane.local_gameservers.yaml index 483d6c866..e9959ac96 100644 --- a/operator/config/crd/gameplane.local_gameservers.yaml +++ b/operator/config/crd/gameplane.local_gameservers.yaml @@ -1404,6 +1404,25 @@ spec: maxLength: 253 pattern: ^([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?)(\.[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?)*$ type: string + loadBalancerClass: + description: |- + LoadBalancerClass selects the load-balancer implementation for the + fronting Service (service.spec.loadBalancerClass), for a cluster that + runs more than one, or a custom one for game traffic. It only takes + effect when Expose=LoadBalancer. Kubernetes doesn't allow changing a + Service's class, so when this changes the operator replaces the + Service, which gets a new cluster IP and, usually, a new external + address. Unset leaves the Service's class as it is. The value is a + Kubernetes qualified name: an optional DNS-subdomain prefix and a + slash, then a name of at most 63 characters. The prefix is at most 253 + characters, so the whole value is at most 317. + maxLength: 317 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$ + type: string + x-kubernetes-validations: + - message: the loadBalancerClass prefix must be at most 253 characters + rule: '!self.contains(''/'') || self.split(''/'')[0].size() + <= 253' portOverrides: description: |- PortOverrides lets the user pin a specific NodePort or override diff --git a/operator/internal/controller/gameserver_controller.go b/operator/internal/controller/gameserver_controller.go index e91c2925f..f4daafa77 100644 --- a/operator/internal/controller/gameserver_controller.go +++ b/operator/internal/controller/gameserver_controller.go @@ -479,7 +479,14 @@ func (r *GameServerReconciler) Reconcile(ctx context.Context, req ctrl.Request) logger.Error(err, "reconcile tunnel") return ctrl.Result{}, err } - if err := r.reconcileService(ctx, &gs, &tmpl, plan.routeToSentinel); err != nil { + // A Service being replaced for a loadBalancerClass change is a pending + // networking change, not a failure: lifecycle and status keep reconciling + // (so Stop works while the old load balancer cleans up), and the pass + // requeues until the new Service exists. + serviceReplacing := false + if err := r.reconcileService(ctx, &gs, &tmpl, plan.routeToSentinel); errors.Is(err, errServiceReplaced) { + serviceReplacing = true + } else if err != nil { logger.Error(err, "reconcile Service") return ctrl.Result{}, err } @@ -572,6 +579,9 @@ func (r *GameServerReconciler) Reconcile(ctx context.Context, req ctrl.Request) if _, held, _ := lifecycleOwner(&gs); held { hints = append(hints, 5*time.Second) } + if serviceReplacing { + hints = append(hints, serviceReplaceRetry) + } if sentinelBackstopPending(plan) { // Bounded backstop for planSentinel's wait on the sentinel or the // game pod. Both are owned (Owns(&appsv1.Deployment{}), @@ -718,10 +728,14 @@ func (r *GameServerReconciler) reconcileService( ctx context.Context, gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate, routeToSentinel bool, ) error { + if err := r.replaceServiceForClassChange(ctx, gs); err != nil { + return err + } svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{Name: gs.Name, Namespace: gs.Namespace}, } _, err := controllerutil.CreateOrUpdate(ctx, r.Client, svc, func() error { + wasLoadBalancer := svc.ResourceVersion != "" && svc.Spec.Type == corev1.ServiceTypeLoadBalancer svc.Spec.Type = corev1.ServiceTypeClusterIP switch gs.Spec.Networking.Expose { case "NodePort": @@ -729,6 +743,16 @@ func (r *GameServerReconciler) reconcileService( case "LoadBalancer": svc.Spec.Type = corev1.ServiceTypeLoadBalancer } + // The class can only be set as the Service becomes a LoadBalancer + // (Kubernetes clears it when it stops being one, and rejects any + // change after that), so it is set only on that transition. An + // existing LoadBalancer with another class, or none, is replaced + // above. + if svc.Spec.Type == corev1.ServiceTypeLoadBalancer && !wasLoadBalancer && + gs.Spec.Networking.LoadBalancerClass != nil { + class := *gs.Spec.Networking.LoadBalancerClass + svc.Spec.LoadBalancerClass = &class + } // loadBalancerSourceRanges is only valid on LoadBalancer Services; // clear it otherwise so a later Expose change doesn't leave a stale // (and rejected) allow-list behind. @@ -771,6 +795,55 @@ func (r *GameServerReconciler) reconcileService( return err } +// errServiceReplaced asks for a requeue while a Service is replaced for a +// loadBalancerClass change: the old one may linger while its load balancer +// cleans up, and a new one can only be created once it is gone. +var errServiceReplaced = errors.New("replacing the Service for a loadBalancerClass change") + +// serviceReplaceRetry bounds how long a pass waits to see the old Service +// gone. Owns(&corev1.Service{}) normally retriggers the reconcile when it is. +const serviceReplaceRetry = 5 * time.Second + +// replaceServiceForClassChange deletes the game Service when the GameServer +// asks for a different loadBalancerClass than the Service has, including a +// LoadBalancer Service with no class, since Kubernetes doesn't allow +// changing or adding a LoadBalancer Service's class. The next reconcile +// creates the Service again, with the new class. An unset class never +// replaces a Service, so a class set by something else (an admission +// policy, an older operator) is kept. +func (r *GameServerReconciler) replaceServiceForClassChange( + ctx context.Context, gs *gameplanev1alpha1.GameServer, +) error { + want := gs.Spec.Networking.LoadBalancerClass + if want == nil || gs.Spec.Networking.Expose != "LoadBalancer" { + return nil + } + var svc corev1.Service + if err := r.Get(ctx, types.NamespacedName{Namespace: gs.Namespace, Name: gs.Name}, &svc); err != nil { + if apierrors.IsNotFound(err) { + return nil + } + return fmt.Errorf("get Service: %w", err) + } + if !svc.DeletionTimestamp.IsZero() { + return errServiceReplaced + } + if svc.Spec.Type != corev1.ServiceTypeLoadBalancer || + (svc.Spec.LoadBalancerClass != nil && *svc.Spec.LoadBalancerClass == *want) { + return nil + } + if !metav1.IsControlledBy(&svc, gs) { + return nil + } + // The UID precondition keeps the delete to the Service checked above, not + // a same-name one that replaced it in the meantime. + uid := svc.UID + if err := r.Delete(ctx, &svc, client.Preconditions{UID: &uid}); err != nil && !apierrors.IsNotFound(err) { + return fmt.Errorf("delete Service for a loadBalancerClass change: %w", err) + } + return errServiceReplaced +} + // managedServiceAnnotationsKey records which annotation keys the operator // applied from spec.networking.serviceAnnotations on the previous reconcile. const managedServiceAnnotationsKey = "gameplane.local/managed-service-annotations" diff --git a/operator/internal/controller/gameserver_lbclass_envtest_test.go b/operator/internal/controller/gameserver_lbclass_envtest_test.go new file mode 100644 index 000000000..fcf0f12fd --- /dev/null +++ b/operator/internal/controller/gameserver_lbclass_envtest_test.go @@ -0,0 +1,325 @@ +//go:build envtest + +package controller + +import ( + "context" + "slices" + "testing" + + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/util/retry" + "sigs.k8s.io/controller-runtime/pkg/client" + + gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" +) + +// TestGameServer_LoadBalancerClass — the class reaches the Service, and a +// changed class replaces the Service, since Kubernetes doesn't allow +// changing it in place. +func TestGameServer_LoadBalancerClass(t *testing.T) { + ns := newNamespace(t) + startMgr(t, ns, withGameServerReconciler(t, ns)) + + tmpl := buildGameTemplate(uniqueName("minecraft")) + if err := k8sClient.Create(context.Background(), tmpl); err != nil { + t.Fatalf("create template: %v", err) + } + deleteCleanup(t, tmpl) + + first, second := "example.com/first", "example.com/second" + gs := buildGameServer(ns, "smp", tmpl.Name) + gs.Spec.Networking = gameplanev1alpha1.GameServerNetworking{ + Expose: "LoadBalancer", + LoadBalancerClass: &first, + } + if err := k8sClient.Create(context.Background(), gs); err != nil { + t.Fatalf("create gameserver: %v", err) + } + + key := types.NamespacedName{Namespace: ns, Name: "smp"} + var firstUID types.UID + eventually(t, func() (bool, string) { + var svc corev1.Service + if err := k8sClient.Get(context.Background(), key, &svc); err != nil { + return false, err.Error() + } + if svc.Spec.LoadBalancerClass == nil || *svc.Spec.LoadBalancerClass != first { + return false, "class not set" + } + firstUID = svc.UID + return true, "" + }) + + if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + var cur gameplanev1alpha1.GameServer + if err := k8sClient.Get(context.Background(), key, &cur); err != nil { + return err + } + cur.Spec.Networking.LoadBalancerClass = &second + return k8sClient.Update(context.Background(), &cur) + }); err != nil { + t.Fatalf("update class: %v", err) + } + + eventually(t, func() (bool, string) { + var svc corev1.Service + if err := k8sClient.Get(context.Background(), key, &svc); err != nil { + return false, err.Error() + } + if svc.UID == firstUID { + return false, "Service not replaced yet" + } + if svc.Spec.LoadBalancerClass == nil || *svc.Spec.LoadBalancerClass != second { + return false, "new Service lacks the new class" + } + return true, "" + }) +} + +// TestGameServer_LoadBalancerClassUnsetKeepsTheService — a Service whose class +// was set by something else (here, directly) is kept when the GameServer sets +// none. +func TestGameServer_LoadBalancerClassUnsetKeepsTheService(t *testing.T) { + ns := newNamespace(t) + + tmpl := buildGameTemplate(uniqueName("minecraft")) + if err := k8sClient.Create(context.Background(), tmpl); err != nil { + t.Fatalf("create template: %v", err) + } + deleteCleanup(t, tmpl) + + class := "example.com/external" + pre := &corev1.Service{} + pre.Name, pre.Namespace = "smp", ns + pre.Spec.Type = corev1.ServiceTypeLoadBalancer + pre.Spec.LoadBalancerClass = &class + pre.Spec.Ports = []corev1.ServicePort{{Name: "game", Port: 25565}} + if err := k8sClient.Create(context.Background(), pre); err != nil { + t.Fatalf("create Service: %v", err) + } + + startMgr(t, ns, withGameServerReconciler(t, ns)) + gs := buildGameServer(ns, "smp", tmpl.Name) + gs.Spec.Networking = gameplanev1alpha1.GameServerNetworking{Expose: "LoadBalancer"} + if err := k8sClient.Create(context.Background(), gs); err != nil { + t.Fatalf("create gameserver: %v", err) + } + + key := types.NamespacedName{Namespace: ns, Name: "smp"} + eventually(t, func() (bool, string) { + var svc corev1.Service + if err := k8sClient.Get(context.Background(), key, &svc); err != nil { + return false, err.Error() + } + if svc.UID != pre.UID { + return false, "Service was replaced" + } + if len(svc.OwnerReferences) == 0 { + return false, "not adopted yet" + } + if svc.Spec.LoadBalancerClass == nil || *svc.Spec.LoadBalancerClass != class { + return false, "class changed" + } + return true, "" + }) +} + +// TestGameServer_LoadBalancerClassAddedToAnExistingService — a server that +// was already a LoadBalancer without a class gets a new Service with the +// class once one is requested, since Kubernetes rejects adding a class to an +// existing LoadBalancer Service. +func TestGameServer_LoadBalancerClassAddedToAnExistingService(t *testing.T) { + ns := newNamespace(t) + startMgr(t, ns, withGameServerReconciler(t, ns)) + + tmpl := buildGameTemplate(uniqueName("minecraft")) + if err := k8sClient.Create(context.Background(), tmpl); err != nil { + t.Fatalf("create template: %v", err) + } + deleteCleanup(t, tmpl) + + gs := buildGameServer(ns, "smp", tmpl.Name) + gs.Spec.Networking = gameplanev1alpha1.GameServerNetworking{Expose: "LoadBalancer"} + if err := k8sClient.Create(context.Background(), gs); err != nil { + t.Fatalf("create gameserver: %v", err) + } + + key := types.NamespacedName{Namespace: ns, Name: "smp"} + var firstUID types.UID + eventually(t, func() (bool, string) { + var svc corev1.Service + if err := k8sClient.Get(context.Background(), key, &svc); err != nil { + return false, err.Error() + } + if svc.Spec.Type != corev1.ServiceTypeLoadBalancer { + return false, "not a LoadBalancer yet" + } + if svc.Spec.LoadBalancerClass != nil { + return false, "unexpected class" + } + firstUID = svc.UID + return true, "" + }) + + class := "example.com/added" + if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + var cur gameplanev1alpha1.GameServer + if err := k8sClient.Get(context.Background(), key, &cur); err != nil { + return err + } + cur.Spec.Networking.LoadBalancerClass = &class + return k8sClient.Update(context.Background(), &cur) + }); err != nil { + t.Fatalf("update class: %v", err) + } + + eventually(t, func() (bool, string) { + var svc corev1.Service + if err := k8sClient.Get(context.Background(), key, &svc); err != nil { + return false, err.Error() + } + if svc.UID == firstUID { + return false, "Service not replaced yet" + } + if svc.Spec.LoadBalancerClass == nil || *svc.Spec.LoadBalancerClass != class { + return false, "new Service lacks the class" + } + return true, "" + }) +} + +// TestGameServer_StopWhileTheServiceIsReplaced — Stop and status keep +// working while a class change waits for the old Service's load balancer to +// clean up. The test holds the provider's cleanup finalizer, so the old +// Service stays terminating until it is released. +func TestGameServer_StopWhileTheServiceIsReplaced(t *testing.T) { + ns := newNamespace(t) + startMgr(t, ns, withGameServerReconciler(t, ns)) + + tmpl := buildGameTemplate(uniqueName("minecraft")) + if err := k8sClient.Create(context.Background(), tmpl); err != nil { + t.Fatalf("create template: %v", err) + } + deleteCleanup(t, tmpl) + + first, second := "example.com/first", "example.com/second" + gs := buildGameServer(ns, "smp", tmpl.Name) + gs.Spec.Networking = gameplanev1alpha1.GameServerNetworking{ + Expose: "LoadBalancer", + LoadBalancerClass: &first, + } + if err := k8sClient.Create(context.Background(), gs); err != nil { + t.Fatalf("create gameserver: %v", err) + } + + key := types.NamespacedName{Namespace: ns, Name: "smp"} + const cleanup = "service.kubernetes.io/load-balancer-cleanup" + var oldUID types.UID + eventually(t, func() (bool, string) { + var ss appsv1.StatefulSet + if err := k8sClient.Get(context.Background(), key, &ss); err != nil { + return false, err.Error() + } + if ss.Spec.Replicas == nil || *ss.Spec.Replicas != 1 { + return false, "StatefulSet not running yet" + } + var svc corev1.Service + if err := k8sClient.Get(context.Background(), key, &svc); err != nil { + return false, err.Error() + } + oldUID = svc.UID + return true, "" + }) + // Hold the old Service the way a load-balancer provider does. + if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + var svc corev1.Service + if err := k8sClient.Get(context.Background(), key, &svc); err != nil { + return err + } + svc.Finalizers = append(svc.Finalizers, cleanup) + return k8sClient.Update(context.Background(), &svc) + }); err != nil { + t.Fatalf("add cleanup finalizer: %v", err) + } + release := func() { + _ = retry.RetryOnConflict(retry.DefaultRetry, func() error { + var svc corev1.Service + if err := k8sClient.Get(context.Background(), key, &svc); err != nil { + return client.IgnoreNotFound(err) + } + if svc.UID != oldUID || !slices.Contains(svc.Finalizers, cleanup) { + return nil + } + svc.Finalizers = slices.DeleteFunc(svc.Finalizers, func(f string) bool { return f == cleanup }) + return k8sClient.Update(context.Background(), &svc) + }) + } + t.Cleanup(release) + + if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + cur := getGameServer(t, ns, "smp") + cur.Spec.Networking.LoadBalancerClass = &second + return k8sClient.Update(context.Background(), cur) + }); err != nil { + t.Fatalf("update class: %v", err) + } + eventually(t, func() (bool, string) { + var svc corev1.Service + if err := k8sClient.Get(context.Background(), key, &svc); err != nil { + return false, err.Error() + } + if svc.UID != oldUID || svc.DeletionTimestamp.IsZero() { + return false, "old Service not terminating yet" + } + return true, "" + }) + + // Stop while the old Service is still held. + if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + cur := getGameServer(t, ns, "smp") + cur.Spec.Suspend = true + return k8sClient.Update(context.Background(), cur) + }); err != nil { + t.Fatalf("stop: %v", err) + } + eventually(t, func() (bool, string) { + var ss appsv1.StatefulSet + if err := k8sClient.Get(context.Background(), key, &ss); err != nil { + return false, err.Error() + } + if ss.Spec.Replicas == nil || *ss.Spec.Replicas != 0 { + return false, "game not stopped" + } + cur := getGameServer(t, ns, "smp") + if cur.Status.ObservedGeneration != cur.Generation { + return false, "status not updated for the Stop" + } + if cur.Status.Phase != gameplanev1alpha1.GameServerPhaseSuspended { + return false, "phase = " + string(cur.Status.Phase) + } + var svc corev1.Service + if err := k8sClient.Get(context.Background(), key, &svc); err != nil || svc.UID != oldUID { + return false, "old Service gone before the check" + } + return true, "" + }) + + // Once the provider lets go, the new Service gets the new class. + release() + eventually(t, func() (bool, string) { + var svc corev1.Service + if err := k8sClient.Get(context.Background(), key, &svc); err != nil { + return false, err.Error() + } + if svc.UID == oldUID { + return false, "Service not replaced yet" + } + if svc.Spec.LoadBalancerClass == nil || *svc.Spec.LoadBalancerClass != second { + return false, "new Service lacks the new class" + } + return true, "" + }) +} diff --git a/operator/internal/controller/gameserver_lbclass_test.go b/operator/internal/controller/gameserver_lbclass_test.go new file mode 100644 index 000000000..7f5bac6e5 --- /dev/null +++ b/operator/internal/controller/gameserver_lbclass_test.go @@ -0,0 +1,166 @@ +package controller + +import ( + "context" + "errors" + "testing" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" +) + +// TestReplaceServiceForClassChange — only a controlled LoadBalancer Service +// whose class differs from the requested one, or which has none, is deleted; +// every other case keeps the Service. +func TestReplaceServiceForClassChange(t *testing.T) { + first, second := "example.com/first", "example.com/second" + lbService := func(class *string) *corev1.Service { + return &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "games"}, + Spec: corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, LoadBalancerClass: class}, + } + } + cases := []struct { + name string + expose string + want *string + svc *corev1.Service + controlled bool + wantErr error + wantGone bool + }{ + {name: "unset class", expose: "LoadBalancer", svc: lbService(&first), controlled: true}, + {name: "not a LoadBalancer server", expose: "ClusterIP", want: &second, svc: lbService(&first), controlled: true}, + {name: "no Service yet", expose: "LoadBalancer", want: &second}, + {name: "same class", expose: "LoadBalancer", want: &first, svc: lbService(&first), controlled: true}, + {name: "Service without a class", expose: "LoadBalancer", want: &second, svc: lbService(nil), controlled: true, wantErr: errServiceReplaced, wantGone: true}, + {name: "ClusterIP Service", expose: "LoadBalancer", want: &second, svc: &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "games"}, + Spec: corev1.ServiceSpec{Type: corev1.ServiceTypeClusterIP}, + }, controlled: true}, + {name: "Service owned by something else", expose: "LoadBalancer", want: &second, svc: lbService(&first)}, + {name: "changed class", expose: "LoadBalancer", want: &second, svc: lbService(&first), controlled: true, wantErr: errServiceReplaced, wantGone: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := wipeScheme(t) + gs := &gameplanev1alpha1.GameServer{ + ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "games", UID: "server-uid"}, + Spec: gameplanev1alpha1.GameServerSpec{Networking: gameplanev1alpha1.GameServerNetworking{ + Expose: tc.expose, LoadBalancerClass: tc.want, + }}, + } + builder := fake.NewClientBuilder().WithScheme(s).WithObjects(gs) + if tc.svc != nil { + if tc.controlled { + if err := controllerutil.SetControllerReference(gs, tc.svc, s); err != nil { + t.Fatal(err) + } + } + builder = builder.WithObjects(tc.svc) + } + c := builder.Build() + r := &GameServerReconciler{Client: c, Scheme: s} + if err := r.replaceServiceForClassChange(t.Context(), gs); !errors.Is(err, tc.wantErr) { + t.Fatalf("got error %v, want %v", err, tc.wantErr) + } + if tc.svc == nil { + return + } + err := c.Get(t.Context(), client.ObjectKeyFromObject(tc.svc), &corev1.Service{}) + if gone := apierrors.IsNotFound(err); gone != tc.wantGone { + t.Fatalf("Service deleted = %v, want %v (get error %v)", gone, tc.wantGone, err) + } + }) + } +} + +// TestReplaceServiceForClassChange_Deleting — a Service already being deleted +// asks for a requeue without another delete, so the new Service waits for it. +func TestReplaceServiceForClassChange_Deleting(t *testing.T) { + first, second := "example.com/first", "example.com/second" + s := wipeScheme(t) + gs := &gameplanev1alpha1.GameServer{ + ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "games", UID: "server-uid"}, + Spec: gameplanev1alpha1.GameServerSpec{Networking: gameplanev1alpha1.GameServerNetworking{ + Expose: "LoadBalancer", LoadBalancerClass: &second, + }}, + } + now := metav1.Now() + svc := &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: "server", Namespace: "games", + DeletionTimestamp: &now, Finalizers: []string{"service.kubernetes.io/load-balancer-cleanup"}, + }, + Spec: corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, LoadBalancerClass: &first}, + } + deletes := 0 + c := fake.NewClientBuilder().WithScheme(s).WithObjects(gs, svc).WithInterceptorFuncs(interceptor.Funcs{ + Delete: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + deletes++ + return cl.Delete(ctx, obj, opts...) + }, + }).Build() + r := &GameServerReconciler{Client: c, Scheme: s} + if err := r.replaceServiceForClassChange(t.Context(), gs); !errors.Is(err, errServiceReplaced) { + t.Fatalf("got error %v, want errServiceReplaced", err) + } + if deletes != 0 { + t.Fatalf("deleted a Service that was already being deleted (%d deletes)", deletes) + } +} + +// TestReplaceServiceForClassChange_APIErrors — a failed read or delete is +// returned, never mistaken for a missing or replaced Service. +func TestReplaceServiceForClassChange_APIErrors(t *testing.T) { + first, second := "example.com/first", "example.com/second" + boom := apierrors.NewServiceUnavailable("apiserver down") + for _, tc := range []struct { + name string + funcs interceptor.Funcs + }{ + {name: "get", funcs: interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*corev1.Service); ok { + return boom + } + return cl.Get(ctx, key, obj, opts...) + }, + }}, + {name: "delete", funcs: interceptor.Funcs{ + Delete: func(context.Context, client.WithWatch, client.Object, ...client.DeleteOption) error { + return boom + }, + }}, + } { + t.Run(tc.name, func(t *testing.T) { + s := wipeScheme(t) + gs := &gameplanev1alpha1.GameServer{ + ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "games", UID: "server-uid"}, + Spec: gameplanev1alpha1.GameServerSpec{Networking: gameplanev1alpha1.GameServerNetworking{ + Expose: "LoadBalancer", LoadBalancerClass: &second, + }}, + } + svc := &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "games"}, + Spec: corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, LoadBalancerClass: &first}, + } + if err := controllerutil.SetControllerReference(gs, svc, s); err != nil { + t.Fatal(err) + } + c := fake.NewClientBuilder().WithScheme(s).WithObjects(gs, svc).WithInterceptorFuncs(tc.funcs).Build() + r := &GameServerReconciler{Client: c, Scheme: s} + err := r.replaceServiceForClassChange(t.Context(), gs) + if err == nil || errors.Is(err, errServiceReplaced) || !apierrors.IsServiceUnavailable(err) { + t.Fatalf("got error %v, want the API error", err) + } + }) + } +} diff --git a/operator/specs.md b/operator/specs.md index 13fb5af27..fb3a91f92 100644 --- a/operator/specs.md +++ b/operator/specs.md @@ -424,6 +424,7 @@ Primary reconcilers register with the manager in `cmd/main.go` and handle CRD li - Sentinel NetworkPolicies: `GameTemplate.spec.sentinelIsolation` defaults false. When true, reconcile owned `-sentinel-ingress` and `-sentinel-egress` policies joining only the same namespace/server instance on advertised protocol/port tuples. An opted-in template with zero advertised ports revokes its owned game-ingress and sentinel policies plus public/game-direct Services through uncached, UID/resourceVersion-guarded cleanup before reporting actionable `Ready=False`; it creates no workloads or unrestricted grants, preserves foreign resources and the agent Service, and reports the failure even when cleanup needs a retry. Set `gameplane.local/sentinel-isolation=true` on both pod templates, without changing immutable workload selectors. On opt-out, roll the labels off both workloads and retain the per-server grants until uncached reads confirm both controllers observed the unlabeled templates and completed their rollouts, and neither game nor sentinel pods still carry the label. Settled opt-outs first probe cached sentinel policies and skip live rollout reads when no owned grants exist. The owned NetworkPolicy watch must remain enabled: delayed cache visibility enqueues another cleanup pass. The matching chart excludes opted-in sources and destinations from legacy grants; other policies remain additive. - Fixed-name child cleanup: Delete fixed-name objects (`-config` Secret, `-files` Secret, `-rcon` Secret, `-auto` BackupSchedule, `-wipe` Job) only when the GameServer controls them via OwnerReference; unowned objects with these names stay in place (same rule as game-ingress NetworkPolicy). Wipe cleanup carries the verified Job UID as a delete precondition; a foreign Job cannot acknowledge a pending wipe or resume its server. - **Conflict requeue:** When reconcileStatefulSet or reconcileWipe encounters an apierrors.IsConflict error (concurrent update races), requeue without error logging — conflicts are expected and transient. Idle-transition and restart-acknowledgment conflicts, including wrapped errors, also return before logging and retry after one second with fresh state. Other errors retain their identity, error logging and controller-runtime backoff. The Module, NetworkCapture and Backup reconcilers apply the conflict rule to every error they return, via `requeueOnConflict` (`conflict.go`). + - **Load-balancer class (`spec.networking.loadBalancerClass`):** honored only when `expose` is `LoadBalancer`. Kubernetes accepts a Service's `spec.loadBalancerClass` only as the Service becomes a LoadBalancer and rejects any later change, including adding one to a LoadBalancer Service that has none, so `reconcileService` sets the class only on that transition (a new Service, or one changing type to LoadBalancer). Before that, `replaceServiceForClassChange` deletes a GameServer-controlled LoadBalancer Service whose class differs from the requested one, or which has none, with the checked UID as a delete precondition, and returns `errServiceReplaced`; while the old Service is terminating (its load-balancer finalizer can hold it) it returns the same without deleting again. `Reconcile` treats `errServiceReplaced` as a pending networking change, not a failure: the rest of the pass (replicas and the StatefulSet, so Stop works; status) still runs, and the pass requeues after `serviceReplaceRetry` until the next reconcile creates the Service with the new class. The replacement gets a new cluster IP and usually a new external address. An unset class never replaces a Service, so a class set by something else (an admission policy, an older operator) is kept, and a Service the GameServer doesn't control is never deleted. Validation matches Kubernetes' qualified-name rule (a prefix of at most 253 characters and a name part of at most 63, so at most 317 in all), so a rejected class can't delete a working Service and then fail to create its replacement. The dashboard's Networking settings don't edit the class but keep it through a save. Tests: `TestReplaceServiceForClassChange*` (`gameserver_lbclass_test.go`), `TestGameServer_LoadBalancerClass*` and `TestGameServer_StopWhileTheServiceIsReplaced` (envtest), `TestGameServer_LoadBalancerClassReplacesTheService` and `TestCRD_Validation_LoadBalancerClassNameLength` (E2E). - Load-balancer address management: translate spec.networking.addressPool / .address preferences onto the Service based on the cluster's address-manager flavor (MetalLB, Cilium, or none), report assignment status via the AddressAssignment condition. - **Network capture foundation** (**Phase 2 Foundational**): Pre-provision a `captures` emptyDir (1 GiB) unconditionally on every game pod's StatefulSet template (required because pod.spec.volumes is immutable on running pods; a rolling restart of all existing game pods is incurred once on upgrade). Extend the `-agent` Service with a second numeric ServicePort 9091 for the capture sidecar's control endpoint. RBAC markers grant `pods/ephemeralcontainers` access (get, list, watch, patch, update) and full CRUD on `networkcaptures` resources. The capture sidecar injection as an ephemeral container is implemented: `buildCaptureEphemeralContainer` (`gameserver_controller.go`) is the single source of truth for the container spec, injected eagerly by `GameServerReconciler.reconcileCapture` when `spec.capture.enabled` is set, with `NetworkCaptureReconciler.injectCaptureContainer` as an idempotent fallback for the case where its own cache is ahead of the GameServer reconciler's write. - **Split concerns:** diff --git a/test/e2e/buckets.sh b/test/e2e/buckets.sh index 56d5f50a7..0a72dc844 100755 --- a/test/e2e/buckets.sh +++ b/test/e2e/buckets.sh @@ -53,6 +53,7 @@ TestCRD_Validation_IdleRejectsBadValues TestCRD_Validation_TunnelServerAddrInvalid TestCRD_Validation_TunnelProxyNameInvalid TestCRD_Validation_TunnelServerAddrValid +TestCRD_Validation_LoadBalancerClassNameLength TestGameServer_OperatorMaterializesChildren TestGameServer_SuspendScalesToZeroAndBack TestGameServer_IdleNeverSleepsWithoutAPlayerCount @@ -69,6 +70,7 @@ TestGameServer_CorrectedImageRecoversFailedOrdinal TestGameServer_RestoredRolloutRehearsal TestGameServer_WipeReportsFailureOnPermissionDenied TestGameServer_CascadingDelete +TestGameServer_LoadBalancerClassReplacesTheService TestGameServer_TunnelCredentialRefusalSurfaced TestGameServer_IngressNetworkPolicyShapeAndCascade TestGameServer_NetworkCaptureStartStopDownload diff --git a/test/e2e/lbclass_e2e_test.go b/test/e2e/lbclass_e2e_test.go new file mode 100644 index 000000000..5cdefc74d --- /dev/null +++ b/test/e2e/lbclass_e2e_test.go @@ -0,0 +1,145 @@ +//go:build e2e + +package e2e + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" +) + +// TestGameServer_LoadBalancerClassReplacesTheService — a LoadBalancer server +// created without a class gets a new Service carrying the class once one is +// requested, and another new one when the class changes. Kubernetes rejects +// adding or changing a LoadBalancer Service's class in place, so each step +// must be a replacement (a new Service UID), never an update. +func TestGameServer_LoadBalancerClassReplacesTheService(t *testing.T) { + t.Parallel() + + ctx := context.Background() + ns := "gameplane-games" + tmplName := fmt.Sprintf("e2e-lbclass-%d", time.Now().UnixNano()) + gsName := fmt.Sprintf("e2e-gs-lbclass-%d", time.Now().UnixNano()) + applyBusyboxTemplate(t, tmplName) + + gs := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "gameplane.local/v1alpha1", + "kind": "GameServer", + "metadata": map[string]any{"name": gsName, "namespace": ns}, + "spec": map[string]any{ + "templateRef": map[string]any{"name": tmplName}, + "networking": map[string]any{"expose": "LoadBalancer"}, + }, + }} + if _, err := envInstance.Dyn.Resource(gameServerGVR).Namespace(ns). + Create(ctx, gs, metav1.CreateOptions{}); err != nil && !apierrors.IsAlreadyExists(err) { + t.Fatalf("create gameserver: %v", err) + } + t.Cleanup(func() { + _ = envInstance.Dyn.Resource(gameServerGVR).Namespace(ns). + Delete(context.Background(), gsName, metav1.DeleteOptions{}) + }) + + // waitForClass waits for a LoadBalancer Service with the given class (nil + // for none) whose UID differs from previous, and returns its UID. + waitForClass := func(class *string, previous types.UID) types.UID { + t.Helper() + var uid types.UID + envInstance.Eventually(t, 120*time.Second, func() (bool, string) { + svc, err := envInstance.K8s.CoreV1().Services(ns).Get(ctx, gsName, metav1.GetOptions{}) + if err != nil { + return false, "get service: " + err.Error() + } + if svc.Spec.Type != corev1.ServiceTypeLoadBalancer { + return false, fmt.Sprintf("service type = %s, want LoadBalancer", svc.Spec.Type) + } + if svc.UID == previous { + return false, "service not replaced yet" + } + got := svc.Spec.LoadBalancerClass + switch { + case class == nil && got != nil: + return false, fmt.Sprintf("service class = %q, want none", *got) + case class != nil && (got == nil || *got != *class): + return false, fmt.Sprintf("service class = %v, want %q", got, *class) + } + uid = svc.UID + return true, "" + }) + return uid + } + setClass := func(class string) { + t.Helper() + patch := fmt.Appendf(nil, `{"spec":{"networking":{"loadBalancerClass":%q}}}`, class) + if _, err := envInstance.Dyn.Resource(gameServerGVR).Namespace(ns). + Patch(ctx, gsName, types.MergePatchType, patch, metav1.PatchOptions{}); err != nil { + t.Fatalf("set loadBalancerClass %q: %v", class, err) + } + } + + unclassed := waitForClass(nil, "") + + first := "e2e.gameplane.local/first" + setClass(first) + classed := waitForClass(&first, unclassed) + + second := "e2e.gameplane.local/second" + setClass(second) + waitForClass(&second, classed) +} + +// TestCRD_Validation_LoadBalancerClassNameLength — the class's name part may +// be up to 63 characters, as Kubernetes allows for a Service's +// loadBalancerClass, and its prefix up to 253. Longer ones are rejected at +// admission, before they could replace a working Service with one Kubernetes +// refuses to create. +func TestCRD_Validation_LoadBalancerClassNameLength(t *testing.T) { + t.Parallel() + + manifest := func(name, class string) string { + return fmt.Sprintf(`apiVersion: gameplane.local/v1alpha1 +kind: GameServer +metadata: + name: %s + namespace: gameplane-games +spec: + templateRef: + name: e2e-template-test + networking: + expose: LoadBalancer + loadBalancerClass: %s +`, name, class) + } + + longest := "example.com/" + strings.Repeat("a", 63) + if out, err := envInstance.KubectlWithStdin(t.Context(), manifest("e2e-validation-lbclass-63", longest), + "apply", "--dry-run=server", "-f", "-"); err != nil { + t.Fatalf("CRD schema rejected a 63-character class name, which Kubernetes allows.\nkubectl output:\n%s", out) + } + + expectAdmissionRejection(t, manifest("e2e-validation-lbclass-64", "example.com/"+strings.Repeat("a", 64)), + []string{"loadBalancerClass"}) + + // A qualified name's prefix can be 253 characters, so the whole value + // can be 317. + prefix := func(n int) string { + label := strings.Repeat("a", 63) + p := strings.Join([]string{label, label, label}, ".") // 191 + return p + "." + strings.Repeat("b", n-len(p)-1) + } + if out, err := envInstance.KubectlWithStdin(t.Context(), + manifest("e2e-validation-lbclass-317", prefix(253)+"/"+strings.Repeat("a", 63)), + "apply", "--dry-run=server", "-f", "-"); err != nil { + t.Fatalf("CRD schema rejected a 317-character class, which Kubernetes allows.\nkubectl output:\n%s", out) + } + expectAdmissionRejection(t, manifest("e2e-validation-lbclass-prefix-254", prefix(254)+"/a"), + []string{"loadBalancerClass"}) +} diff --git a/web/specs.md b/web/specs.md index 6ea4c2851..b759b9cff 100644 --- a/web/specs.md +++ b/web/specs.md @@ -1016,7 +1016,7 @@ Save fetches the latest server and applies only the changes from the original ba 2. **Version** — Template version selector (triggers container restart) 2a. **Game configuration** — `GameConfigSection` (`web/src/routes/tabs/settings/GameConfig.tsx`), key `config`, shown only when `template.spec.configSchema` has entries (or the server still carries `spec.config` keys, so stray keys can be removed). Edits `draft.spec.config` through the tab's shared draft/Save footer; renders fields with the shared `ConfigFields` (`web/src/components/server/ConfigFields.tsx`, variant `settings`). An unset key means the template default (or the auto value); a value equal to the schema default removes the key, and an emptied map is written as `undefined` (never `{}`). Client validation (`validateConfig`, `web/src/lib/validation.ts`): required, enum, int (whole number, min/max), bool, string/password length; failures show inline and disable Save through `onValidityChange` (the operator stays authoritative; the API does not validate against the schema). Password fields are write-only: the API returns the marker `__gameplane_redacted__` for a stored password, the input is empty with the placeholder "Unchanged — type to replace" and a "Write-only" note, the marker is never rendered, stays in the draft until the user types (the PUT then keeps the stored value) and typing replaces it. A stored OPTIONAL password also shows a "Remove password" button (spec 021 OD-2): pressing it drops the key from the draft (the API deletes an optional password whose key is absent) and shows "Password will be removed" with an Undo button; the state is derived from `storedConfig` (the saved `gs.spec.config` marker) so it survives section switches, Undo restores the key in its saved position, required passwords and read-only sessions get no button, and emptying a typed value still returns to "unchanged". `target: file` fields carry a "Written to file" note. Keys present in `spec.config` but absent from the schema are listed with a "Remove" button ("No longer in the template") because the operator rejects unknown keys. The notice follows the edited fields in the effective schema. Startup-only edits apply at the next container start. Ordinary configuration edits can restart the server. Minecraft Java groups supported startup options and previews the independently resolved heap sizes for the itzg launcher. When `status.conditions[type=Ready].message` starts with `invalid config:` a danger alert shows it. Without `servers:write` (`access.canWrite`) the fields are disabled, the alert is hidden and the footer shows "You need permission to change this server's settings." instead of Discard/Save. 3. **Resources** — `ResourcesSection` (`web/src/routes/tabs/settings/Resources.tsx`): CPU and memory (`spec.resources`), storage size and StorageClass. The CPU and memory fields show the saved limit (falling back to the request, then the 2 cores / 4Gi dashboard default). By default each field writes the same value to the request and the limit (Guaranteed QoS). The "Reserve less than the limit" switch (Burstable QoS) is not stored: it is on when a saved request differs from its limit, or once the user turns it on. While it is on, the CPU and memory fields are the limits and "Reserved CPU" / "Reserved memory (GiB)" (`ResourceInput` with its `label` prop) are the requests, from 0 (reserve nothing) up to the saved limit (uncapped when there is no saved limit). Lowering a limit below a saved request lowers that request to the new limit, since Kubernetes rejects a request above its limit. Each control writes only its own value, so an absent limit or request stays absent: the displayed fallbacks are never written back. Switching off copies each saved limit onto its request; a resource without a saved limit keeps its request. -4. **Networking** — Service type (ClusterIP/NodePort/LoadBalancer), LoadBalancer hostname, address pool / explicit address request, port overrides. Tunnel validation (`tunnel.enabled`, provider-specific config, credentials) is computed during render and reported via `onValidityChange` callback in an effect; local field state for `addressPool` and `address` is held in `useState` — so consecutive edits within one render are cumulative rather than each recomputing against the same stale `net` snapshot — and is re-seeded from props by two complementary mechanisms: on identity change, via a parent `key` remount; and in-render, whenever the incoming values differ by value from the last synced pair (so a save round-trip or a reload that returns changed values for the *same* server is picked up). +4. **Networking** — Service type (ClusterIP/NodePort/LoadBalancer), LoadBalancer hostname, address pool / explicit address request, port overrides. `spec.networking.loadBalancerClass` is not editable in this form (it is set through the API or kubectl); a settings save keeps it as it is. Tunnel validation (`tunnel.enabled`, provider-specific config, credentials) is computed during render and reported via `onValidityChange` callback in an effect; local field state for `addressPool` and `address` is held in `useState` — so consecutive edits within one render are cumulative rather than each recomputing against the same stale `net` snapshot — and is re-seeded from props by two complementary mechanisms: on identity change, via a parent `key` remount; and in-render, whenever the incoming values differ by value from the last synced pair (so a save round-trip or a reload that returns changed values for the *same* server is picked up). 5. **Environment** — Custom env var key=value pairs 6. **Lifecycle** — Pre/post-start/stop scripts, quiesce grace period 7. **Scheduled backups** — `BackupsSection` (`web/src/routes/tabs/settings/Backups.tsx`): a single inline toggle (enable/disable) and form editing `spec.backupPolicy` on the server draft — cron-expression input (no daily/weekly picker), destination picker, retention fields, and a suspend switch; not a separate CRUD list diff --git a/web/src/routes/tabs/settings/Networking.test.tsx b/web/src/routes/tabs/settings/Networking.test.tsx index dd7f8eba7..4dd662500 100644 --- a/web/src/routes/tabs/settings/Networking.test.tsx +++ b/web/src/routes/tabs/settings/Networking.test.tsx @@ -136,6 +136,23 @@ describe("NetworkingSection", () => { expect(lastCall.spec.networking.sourceRanges).toEqual(["203.0.113.0/24"]); }); + it("preserves an existing loadBalancerClass when editing another field", () => { + const draft = { + ...baseDraft, + spec: { + ...baseDraft.spec, + networking: { expose: "LoadBalancer" as const, loadBalancerClass: "example.com/games" }, + }, + }; + const onChange = vi.fn(); + renderWithQuery(); + fireEvent.change(screen.getByPlaceholderText("mc.example.com"), { + target: { value: "mc.example.com" }, + }); + const lastCall = onChange.mock.calls.at(-1)![0]; + expect(lastCall.spec.networking.loadBalancerClass).toBe("example.com/games"); + }); + describe("AddressAssignment (T044, T047, T109)", () => { it("displays and edits address pool and address fields", () => { const onChange = vi.fn(); diff --git a/web/src/routes/tabs/settings/Networking.tsx b/web/src/routes/tabs/settings/Networking.tsx index 47f83b0d0..444dc4430 100644 --- a/web/src/routes/tabs/settings/Networking.tsx +++ b/web/src/routes/tabs/settings/Networking.tsx @@ -88,6 +88,9 @@ export function NetworkingSection({ draft, onChange, onValidityChange }: Section if (next.sourceRanges && next.sourceRanges.length) { cleaned.sourceRanges = next.sourceRanges; } + // Not editable here; set through the API or kubectl, and kept so a save + // from this form doesn't remove it. + if (next.loadBalancerClass) cleaned.loadBalancerClass = next.loadBalancerClass; if (next.addressPool) cleaned.addressPool = next.addressPool; if (next.address) cleaned.address = next.address; if (next.tunnel) cleaned.tunnel = next.tunnel; diff --git a/web/src/types.ts b/web/src/types.ts index bf7fa96bd..ed9d6a9a5 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -438,6 +438,8 @@ export interface GameServerNetworking { serviceAnnotations?: Record; portOverrides?: PortOverride[]; sourceRanges?: string[]; + // The Service's loadBalancerClass; honored only for expose: LoadBalancer. + loadBalancerClass?: string; // Load-balancer address pool to allocate from; honored only for // expose: LoadBalancer, and only when the cluster runs a supported // address manager (MetalLB or Cilium LB-IPAM).