diff --git a/Makefile b/Makefile index 6c877b571..bc9a36a51 100644 --- a/Makefile +++ b/Makefile @@ -184,7 +184,7 @@ $(SETUP_ENVTEST): test-controllers-envtest: $(SETUP_ENVTEST) KUBEBUILDER_ASSETS="$$($(SETUP_ENVTEST) use $(ENVTEST_K8S_VERSION) --installed-only --bin-dir $(ENVTEST_DIR) --print path 2>/dev/null || $(SETUP_ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(ENVTEST_DIR) --print path)" \ HELMRELEASE_CRD_DIR=$(CURDIR)/internal/fluxinstall/manifests \ - go test -tags envtest -run '^TestEnvtest' ./internal/controller/fluxplunger/... -count=1 + go test -tags envtest -run '^TestEnvtest' ./internal/controller/fluxplunger/... ./internal/gpu/controller/... -count=1 # Black-box golden test for cmd/check-readiness. Builds the binary and runs it # against a mock kubectl (fixtures under test/check-readiness/testdata), diff --git a/cmd/cozystack-controller/main.go b/cmd/cozystack-controller/main.go index 20611eb1c..d49f7c37b 100644 --- a/cmd/cozystack-controller/main.go +++ b/cmd/cozystack-controller/main.go @@ -51,6 +51,7 @@ import ( "github.com/cozystack/cozystack/internal/controller/tenantlogrouting" "github.com/cozystack/cozystack/internal/controller/tenantquota" "github.com/cozystack/cozystack/internal/controller/wildcardsecret" + gpucontroller "github.com/cozystack/cozystack/internal/gpu/controller" "github.com/cozystack/cozystack/internal/telemetry" cmv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" @@ -96,6 +97,7 @@ func main() { var seaweedfsMetricsEndpoint string var cozyProxyContractImplemented bool var endpointAttachmentNodePorts bool + var enableGPU bool var tlsOpts []func(*tls.Config) flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") @@ -124,6 +126,8 @@ func main() { "Without it such attachments render no Service and report DatapathContractUnavailable: a load balancer would still attract the address while every proxy skipped the Service.") flag.BoolVar(&endpointAttachmentNodePorts, "endpoint-attachment-allocate-node-ports", false, "Allocate node ports on the LoadBalancer Services EndpointAttachments render. Off by default, matching the platform convention; needed only by load balancers that forward through node ports (Hetzner RobotLB).") + flag.BoolVar(&enableGPU, "enable-gpu", false, + "Compute GPUClass status and copy vGPU licenses into entitled namespaces. Without it, existing license copies are deleted.") opts := zap.Options{ Development: false, } @@ -330,11 +334,11 @@ func main() { o.Scheme = scheme }) if err != nil { - setupLog.Error(err, "unable to build the CA source metadata cache") + setupLog.Error(err, "unable to build the Secret metadata cache") os.Exit(1) } if err = mgr.Add(caSecretCluster); err != nil { - setupLog.Error(err, "unable to add the CA source metadata cache to the manager") + setupLog.Error(err, "unable to add the Secret metadata cache to the manager") os.Exit(1) } @@ -379,6 +383,13 @@ func main() { os.Exit(1) } + // The GPU license copier watches license Secrets on the same metadata-only + // cache, for the same reason. + if err = gpucontroller.Setup(mgr, enableGPU, caSecretCluster.GetCache()); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "GPU") + os.Exit(1) + } + // +kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { diff --git a/hack/cozystack-controller-secret-rbac.bats b/hack/cozystack-controller-secret-rbac.bats index 9d7ccf913..901a9d70e 100644 --- a/hack/cozystack-controller-secret-rbac.bats +++ b/hack/cozystack-controller-secret-rbac.bats @@ -10,13 +10,15 @@ # here for some other subject would fold into the union too, which errs toward # refusing a grant rather than missing one. # -# Two reconcilers share one Secret write grant: WildcardSecretReconciler -# replicates the operator wildcard TLS Secret into each tenant namespace, and +# Several reconcilers share one Secret write grant: WildcardSecretReconciler +# replicates the operator wildcard TLS Secret into each tenant namespace, # CACertReconciler writes -- and withdraws -- the key-free ".tenant-ca" -# projection. The controller is cluster-scoped, so any verb it holds on Secrets -# it holds on every Secret in every tenant namespace. That is why the set is -# pinned rather than merely bounded from above: a widening reaches all tenants, -# and a narrowing breaks both reconcilers. +# projection, and the GPU license copier writes and deletes license copies in +# namespaces entitled to vGPU. The controller is cluster-scoped, so any verb +# it holds on Secrets it holds on every Secret in every tenant namespace. +# That is why the set is pinned rather than merely bounded from above: a +# widening reaches all tenants, and a narrowing breaks the reconcilers that +# write Secrets. # # The check reads effective permission off the rendered manifests, not manifest # text. A rule reaches core Secrets when its apiGroups admit "" and its @@ -70,8 +72,8 @@ load test_helper # What "*" in a rule's verbs means for a namespaced resource such as Secret. VERB_UNIVERSE='["create","delete","deletecollection","get","list","patch","update","watch"]' -# The grant the chart declares, as a sorted set: read for both reconcilers plus -# the writes the two of them need. Sorted because the comparison below is on +# The grant the chart declares, as a sorted set: read plus the writes the +# Secret-writing reconcilers need. Sorted because the comparison below is on # `unique`d jq output, which is sorted. DECLARED_SECRET_VERBS="create,delete,get,list,patch,update,watch" diff --git a/internal/gpu/controller/setup.go b/internal/gpu/controller/setup.go new file mode 100644 index 000000000..104c0ba5e --- /dev/null +++ b/internal/gpu/controller/setup.go @@ -0,0 +1,71 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package controller computes GPUClass status and delivers vGPU license +// copies in cozystack-controller. +package controller + +import ( + "context" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/manager" + "sigs.k8s.io/controller-runtime/pkg/predicate" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + crsource "sigs.k8s.io/controller-runtime/pkg/source" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" +) + +// Setup adds the GPU reconcilers to mgr. secretMeta is a cache of Secret +// metadata across the cluster: the manager's own Secret cache is scoped +// by label to other reconcilers' Secrets, and a metadata watch on it would +// inherit that scope and never see a license Secret. +// +// The license copier runs even when enabled is false, to delete the +// copies; the status controller runs only when it is true, since it +// caches every Node. +func Setup(mgr manager.Manager, enabled bool, secretMeta cache.Cache) error { + lic := &LicenseReconciler{Client: mgr.GetClient(), Reader: mgr.GetAPIReader(), Secrets: secretMeta, Enabled: enabled} + secret := &metav1.PartialObjectMetadata{} + secret.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("Secret")) + err := ctrl.NewControllerManagedBy(mgr). + Named("gpuclass-license"). + For(&cozyv1alpha1.GPUClass{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + Watches(&corev1.Namespace{}, handler.EnqueueRequestsFromMapFunc(lic.allClasses), + builder.WithPredicates(predicate.LabelChangedPredicate{})). + WatchesRawSource(crsource.Kind(secretMeta, secret, handler.TypedEnqueueRequestsFromMapFunc(lic.secretToClasses))). + Complete(lic) + if err != nil || !enabled { + return err + } + + pass := handler.EnqueueRequestsFromMapFunc(func(context.Context, client.Object) []reconcile.Request { + return []reconcile.Request{{}} + }) + return ctrl.NewControllerManagedBy(mgr). + Named("gpuclass-status"). + Watches(&cozyv1alpha1.GPUClass{}, pass, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + Watches(&corev1.Node{}, pass, builder.WithPredicates(nodeCapacityChanged)). + Watches(&corev1.Pod{}, pass, builder.WithPredicates(predicate.NewPredicateFuncs(requestsExtendedResource))). + Complete(&StatusReconciler{Client: mgr.GetClient(), Reader: mgr.GetAPIReader()}) +} diff --git a/internal/gpu/controller/setup_envtest_test.go b/internal/gpu/controller/setup_envtest_test.go new file mode 100644 index 000000000..a14a043a8 --- /dev/null +++ b/internal/gpu/controller/setup_envtest_test.go @@ -0,0 +1,224 @@ +//go:build envtest + +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package controller + +import ( + "context" + "fmt" + "os" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/utils/ptr" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/cluster" + "sigs.k8s.io/controller-runtime/pkg/config" + "sigs.k8s.io/controller-runtime/pkg/envtest" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + "github.com/cozystack/cozystack/internal/controller/wildcardsecret" + "github.com/cozystack/cozystack/internal/gpu" +) + +// TestEnvtest_Setup drives both reconcilers through the watches Setup +// registers, so a missing or mis-scoped watch shows up as a copy or a +// status that never converges. +func TestEnvtest_Setup(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("set KUBEBUILDER_ASSETS, as make test-controllers-envtest does") + } + env := &envtest.Environment{ + CRDDirectoryPaths: []string{"../../../packages/system/cozystack-controller/definitions"}, + ErrorIfCRDPathMissing: true, + ControlPlaneStartTimeout: 2 * time.Minute, + } + cfg, err := env.Start() + if err != nil { + t.Fatalf("start envtest: %v", err) + } + t.Cleanup(func() { _ = env.Stop() }) + + s := testScheme(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + // start runs the GPU controllers as cozystack-controller does and + // returns a stop that waits for the manager to exit. + start := func(enabled bool) (stop func()) { + // The Secret cache is scoped as in cozystack-controller, so a copier + // reading Secrets through the manager's cache would miss them here. + mgr, err := ctrl.NewManager(cfg, ctrl.Options{Scheme: s, Metrics: metricsserver.Options{BindAddress: "0"}, + Controller: config.Controller{SkipNameValidation: ptr.To(true)}, + Cache: cache.Options{ByObject: map[client.Object]cache.ByObject{&corev1.Secret{}: wildcardsecret.SecretCacheByObject()}}}) + if err != nil { + t.Fatal(err) + } + secretMeta, err := cluster.New(cfg, func(o *cluster.Options) { o.Scheme = s }) + if err != nil { + t.Fatal(err) + } + if err := mgr.Add(secretMeta); err != nil { + t.Fatal(err) + } + if err := Setup(mgr, enabled, secretMeta.GetCache()); err != nil { + t.Fatal(err) + } + mctx, mcancel := context.WithCancel(ctx) + done := make(chan struct{}) + go func() { _ = mgr.Start(mctx); close(done) }() + return func() { mcancel(); <-done } + } + + cl, err := client.New(cfg, client.Options{Scheme: s}) + if err != nil { + t.Fatal(err) + } + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + eventually := func(what string, cond func() error) { + t.Helper() + var last error + if err := wait.PollUntilContextTimeout(ctx, 100*time.Millisecond, 30*time.Second, true, func(context.Context) (bool, error) { + last = cond() + return last == nil, nil + }); err != nil { + t.Fatalf("%s: %v", what, last) + } + } + copyData := func(ns string) (map[string]string, error) { + sec := &corev1.Secret{} + if err := cl.Get(ctx, client.ObjectKey{Namespace: ns, Name: copyName}, sec); err != nil { + return nil, err + } + return dataOf(sec), nil + } + wantToken := func(ns, token string) func() error { + return func() error { + d, err := copyData(ns) + if err != nil { + return err + } + if d[gpu.LicenseTokenKey] != token { + return fmt.Errorf("token %q, want %q", d[gpu.LicenseTokenKey], token) + } + return nil + } + } + gone := func(ns string) func() error { + return func() error { + if _, err := copyData(ns); err == nil { + return fmt.Errorf("copy in %s still exists", ns) + } + return nil + } + } + condition := func(typ string, status metav1.ConditionStatus) func() error { + return func() error { + c := &cozyv1alpha1.GPUClass{} + if err := cl.Get(ctx, client.ObjectKey{Name: "l40s"}, c); err != nil { + return err + } + if got := meta.FindStatusCondition(c.Status.Conditions, typ); got == nil || got.Status != status { + return fmt.Errorf("%s = %+v, want %s", typ, got, status) + } + return nil + } + } + + must(cl.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: gpu.LicenseSecretNamespace}})) + tenant := namespace("tenant-a", "true") + must(cl.Create(ctx, tenant)) + class := gpuClass("l40s", rnL40S, 0, licensed(tokenSecret, 4)) + class.CreationTimestamp = metav1.Time{} + must(cl.Create(ctx, class)) + must(cl.Create(ctx, licenseCopy("tenant-a", "l40s", map[string]string{gpu.LicenseTokenKey: "token-0"}))) + + stop := start(false) + eventually("copy deleted while GPU features are off", gone("tenant-a")) + // A node event after the copier has settled would start a pass of a + // status controller run by mistake, which writes free; the copier + // skips status updates and would not clear it again. + must(cl.Create(ctx, gpuNode("cpu-0", nil))) + for deadline := time.Now().Add(3 * time.Second); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) { + if c := (&cozyv1alpha1.GPUClass{}); cl.Get(ctx, client.ObjectKey{Name: "l40s"}, c) != nil || c.Status.Free != nil { + t.Fatalf("status computed while GPU features are off: %+v", c.Status) + } + } + stop() + + t.Cleanup(start(true)) + eventually("LicenseSecretMissing while the hoster Secret is absent", condition(cozyv1alpha1.GPUClassLicenseSecretMissing, metav1.ConditionTrue)) + eventually("ResourceNameConflict written next to it", condition(cozyv1alpha1.GPUClassResourceNameConflict, metav1.ConditionFalse)) + + src := hosterSecret(map[string]string{gpu.LicenseTokenKey: "token-1"}) + must(cl.Create(ctx, src)) + eventually("copy after the hoster Secret appears", wantToken("tenant-a", "token-1")) + eventually("LicenseSecretMissing cleared", condition(cozyv1alpha1.GPUClassLicenseSecretMissing, metav1.ConditionFalse)) + + src.Data[gpu.LicenseTokenKey] = []byte("token-2") + must(cl.Update(ctx, src)) + eventually("copy refreshed after rotation", wantToken("tenant-a", "token-2")) + + must(cl.Delete(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "tenant-a", Name: copyName}})) + eventually("deleted copy written again", wantToken("tenant-a", "token-2")) + + tenant.Labels[gpu.LabelNamespaceVGPU] = "false" + must(cl.Update(ctx, tenant)) + eventually("copy deleted with the entitlement", gone("tenant-a")) + tenant.Labels[gpu.LabelNamespaceVGPU] = "true" + must(cl.Update(ctx, tenant)) + eventually("copy back with the entitlement", wantToken("tenant-a", "token-2")) + + node := gpuNode("gpu-1", nil) + allocatable := gpuNode("gpu-1", map[string]int64{rnL40S: 3}).Status + must(cl.Create(ctx, node)) + node.Status = allocatable + must(cl.Status().Update(ctx, node)) + free := func(want int32) func() error { + return func() error { + c := &cozyv1alpha1.GPUClass{} + if err := cl.Get(ctx, client.ObjectKey{Name: "l40s"}, c); err != nil { + return err + } + if c.Status.Free == nil || *c.Status.Free != want { + return fmt.Errorf("free = %v, want %d", c.Status.Free, want) + } + return nil + } + } + eventually("free after the node advertises units", free(3)) + must(cl.Create(ctx, gpuPod("vm-1", "gpu-1", rnL40S, 1, func(p *corev1.Pod) { + p.Namespace = "tenant-a" + p.Spec.Containers[0].Image = "virt-launcher" + }))) + eventually("free after a pod takes a unit", free(2)) + + must(cl.Delete(ctx, class)) + eventually("copy deleted with the class", gone("tenant-a")) +} diff --git a/internal/gpu/doc.go b/internal/gpu/doc.go index 6fccb5a92..43f8f8084 100644 --- a/internal/gpu/doc.go +++ b/internal/gpu/doc.go @@ -85,7 +85,7 @@ limitations under the License. // license goes. While the hoster's Secret is missing or lacks // LicenseTokenKey, it keeps the copies it has, writes no new ones and sets // LicenseSecretMissing on the class. It touches no Secret without -// LabelGPUClass. +// LabelGPUClass. With GPU features off, it deletes every copy. // // The VMI webhook adds a secret volume for the copy of the VMI's licensed // vGPU class, with LicenseVolumeLabel, and a disk for it after the VMI's diff --git a/packages/system/cozystack-controller/templates/deployment.yaml b/packages/system/cozystack-controller/templates/deployment.yaml index aac25d9fb..342d0ce12 100644 --- a/packages/system/cozystack-controller/templates/deployment.yaml +++ b/packages/system/cozystack-controller/templates/deployment.yaml @@ -37,6 +37,9 @@ spec: {{- if .Values.cozystackController.endpointAttachments.allocateLoadBalancerNodePorts }} - --endpoint-attachment-allocate-node-ports {{- end }} + {{- if .Values.cozystackController.gpu.enabled }} + - --enable-gpu + {{- end }} {{- with .Values.cozystackController.resources }} resources: {{- toYaml . | nindent 10 }} diff --git a/packages/system/cozystack-controller/templates/rbac.yaml b/packages/system/cozystack-controller/templates/rbac.yaml index a9f7b646d..6625b69eb 100644 --- a/packages/system/cozystack-controller/templates/rbac.yaml +++ b/packages/system/cozystack-controller/templates/rbac.yaml @@ -84,13 +84,15 @@ rules: - apiGroups: [""] resources: ["events"] verbs: ["create", "patch"] -# Two reconcilers share this one Secret write grant on the platform controller's -# own ServiceAccount; it widens no tenant's RBAC. WildcardSecretReconciler -# replicates the operator wildcard TLS Secret into each tenant namespace; -# CACertReconciler writes — and withdraws — the key-free ".tenant-ca" -# projection, deleting only a projection it owns by owner reference, never a -# foreign Secret. Read was already covered by the catch-all rule below; -# create/update/patch/delete are the new grants. +# Several reconcilers share this one Secret write grant on the platform +# controller's own ServiceAccount; it widens no tenant's RBAC. +# WildcardSecretReconciler replicates the operator wildcard TLS Secret into each +# tenant namespace; CACertReconciler writes — and withdraws — the key-free +# ".tenant-ca" projection, deleting only a projection it owns by owner +# reference, never a foreign Secret; the GPU license copier writes and deletes +# the gpuclass--license copies labelled cozystack.io/gpuclass in +# namespaces entitled to vGPU. Read was already covered by the catch-all rule +# below; create/update/patch/delete are the new grants. - apiGroups: [""] resources: ["secrets"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] diff --git a/packages/system/cozystack-controller/tests/gpu_test.yaml b/packages/system/cozystack-controller/tests/gpu_test.yaml new file mode 100644 index 000000000..2f8f69a93 --- /dev/null +++ b/packages/system/cozystack-controller/tests/gpu_test.yaml @@ -0,0 +1,22 @@ +suite: cozystack-controller GPU flag +templates: + - templates/deployment.yaml + +release: + name: cozystack-controller + namespace: cozy-system + +tests: + - it: leaves GPU features off by default + asserts: + - notContains: + path: spec.template.spec.containers[0].args + content: --enable-gpu + + - it: passes --enable-gpu when gpu.enabled is set + set: + cozystackController.gpu.enabled: true + asserts: + - contains: + path: spec.template.spec.containers[0].args + content: --enable-gpu diff --git a/packages/system/cozystack-controller/tests/rbac_test.yaml b/packages/system/cozystack-controller/tests/rbac_test.yaml index 891e28870..a79bbcd40 100644 --- a/packages/system/cozystack-controller/tests/rbac_test.yaml +++ b/packages/system/cozystack-controller/tests/rbac_test.yaml @@ -6,9 +6,10 @@ release: name: cozystack-controller namespace: cozy-system -# One Secret write grant serves two reconcilers (WildcardSecret replication and -# CACert projection, including "delete"); it scopes the platform controller's own -# ServiceAccount and widens no tenant's RBAC. This rule gates both features, so pin it. +# One Secret write grant serves every reconciler that writes Secrets (WildcardSecret +# replication, CACert projection and GPU license copies, each including "delete"); +# it scopes the platform controller's own ServiceAccount and widens no tenant's +# RBAC. This rule gates all of them, so pin it. # # This suite pins the rule as written and nothing more. helm-unittest compares # every field it is handed by value equality -- `any: true` changes which fields @@ -22,7 +23,7 @@ release: # may do to a Secret. tests: - - it: grants the ClusterRole every verb both reconcilers need, including delete + - it: grants the ClusterRole every verb the Secret writers need, including delete documentSelector: path: kind value: ClusterRole diff --git a/packages/system/cozystack-controller/values.yaml b/packages/system/cozystack-controller/values.yaml index 7ce6d5d6b..b7d671753 100644 --- a/packages/system/cozystack-controller/values.yaml +++ b/packages/system/cozystack-controller/values.yaml @@ -28,3 +28,7 @@ cozystackController: # load balancer forwards through node ports (Hetzner RobotLB), matching # the cozy-lib convention the charts follow. allocateLoadBalancerNodePorts: false + # GPUClass status and vGPU license copies in tenant namespaces. While it is + # off, the controller deletes every license copy. + gpu: + enabled: false