mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-02 18:16:53 +09:00
The binder is the only writer of a claim's placement, so budget and capacity checks that admission already ran cannot be raced past by two replicas. Every event collapses into one pass over all GPU objects, which serializes the decisions without per-object locks, and claims are read past the cache so a unit booked in the last pass is never booked again from a stale view. A VM starts through its launcher pod, which the pod webhook holds at a scheduling gate. The pass creates the VMI's template claims, gathers the whole set onto one node that every class of the set tolerates and has room on, then pins the pod there and removes the gate in one update, since the API server lets a pod's node affinity change only while the pod is gated. A set that cannot be placed keeps its pod gated with a condition on its claims and a Warning event on the VMI, once per change of reason, so the VM waits for capacity instead of being refused into KubeVirt's backoff. The set goes only to a node the pod's own node selector and required affinity accept and, when the VMI has a volume bound to a node's PersistentVolume, that volume reaches. Gated pods go before moves and new orders. A pin cannot be undone, so a pinned pod its node refuses for lack of resources is deleted and the node is skipped for that set for ten minutes, or until its allocatable, taints or readiness change. The template claims of the set go with its failed VMI, so the controller also keeps the rejection in memory for the VM's next VMI. Only a VMI whose pod is already pinned is deleted to free a claim whose node cannot keep it; a VMI whose pod is gated has its set gathered instead. The full pass also moves held sets off nodes that cannot keep them, rebinds Lost sets before new orders, and binds new orders onto the fullest node with room. Finalizers and usage records run with the feature disabled too, so turning GPU off never hangs a namespace or class deletion. Each usage record is owned by its claim and sits under no WorkloadMonitor, so no tenant label can add or drop one, and garbage collection removes it with the claim. Without a monitor label the Workload controller would take such a record for an orphan, so it now leaves a record owned by a GPUClaim to that owner. The claims one VM names move, go Lost and are rebound as a set. Every pass restores that invariant before it places anything, gathering a set left partly Lost, by a write that failed half way or by a VMI that ended next to held members, onto one node or sending all of it to Lost, so each later step only ever changes whole sets. A Lost claim already counts against its tenant's budgets, so the pod of its still running VMI is not counted again under a raw GPU key; for node capacity it is, since the claim itself holds no units. A pod is a VMI's launcher only when the VMI lists it in status.activePods, because whoever creates a pod sets its owner reference. The KubeVirt watches start once KubeVirt serves its kinds, whose CRDs a fresh install adds after this controller starts. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin <f@lex.la>
158 lines
6.2 KiB
Go
158 lines
6.2 KiB
Go
/*
|
|
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 runs the GPU binder, the class and claim lifecycle,
|
|
// usage records and metrics in cozystack-controller.
|
|
package controller
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
"time"
|
|
|
|
helmv2 "github.com/fluxcd/helm-controller/api/v2"
|
|
corev1 "k8s.io/api/core/v1"
|
|
"k8s.io/apimachinery/pkg/api/equality"
|
|
"k8s.io/apimachinery/pkg/api/meta"
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
|
"k8s.io/apimachinery/pkg/runtime/schema"
|
|
ctrl "sigs.k8s.io/controller-runtime"
|
|
"sigs.k8s.io/controller-runtime/pkg/builder"
|
|
"sigs.k8s.io/controller-runtime/pkg/client"
|
|
"sigs.k8s.io/controller-runtime/pkg/event"
|
|
"sigs.k8s.io/controller-runtime/pkg/handler"
|
|
"sigs.k8s.io/controller-runtime/pkg/log"
|
|
"sigs.k8s.io/controller-runtime/pkg/manager"
|
|
"sigs.k8s.io/controller-runtime/pkg/predicate"
|
|
"sigs.k8s.io/controller-runtime/pkg/reconcile"
|
|
"sigs.k8s.io/controller-runtime/pkg/source"
|
|
|
|
gpuv1alpha1 "github.com/cozystack/cozystack/api/gpu/v1alpha1"
|
|
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
|
|
"github.com/cozystack/cozystack/internal/gpu"
|
|
"github.com/cozystack/cozystack/internal/gpu/model"
|
|
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
|
|
)
|
|
|
|
// Setup adds the GPU reconciler to mgr. Finalizers and usage records are
|
|
// always reconciled, so a disabled feature never hangs a deletion; with
|
|
// cfg.Enabled it also places claims and watches KubeVirt objects, which
|
|
// exist only where the feature is enabled.
|
|
func Setup(mgr manager.Manager, cfg gpu.Config) error {
|
|
r := &Reconciler{Client: mgr.GetClient(), Reader: mgr.GetAPIReader(), Cache: mgr.GetCache(), Config: cfg,
|
|
Recorder: mgr.GetEventRecorder("gpu-binder")}
|
|
all := handler.EnqueueRequestsFromMapFunc(func(context.Context, client.Object) []reconcile.Request {
|
|
return []reconcile.Request{{NamespacedName: passKey}}
|
|
})
|
|
b := ctrl.NewControllerManagedBy(mgr).
|
|
Named("gpu-binder").
|
|
Watches(&gpuv1alpha1.GPUClass{}, all).
|
|
Watches(&gpuv1alpha1.GPUClaim{}, all).
|
|
Watches(&cozyv1alpha1.Workload{}, all, builder.WithPredicates(predicate.NewPredicateFuncs(func(o client.Object) bool { return model.OwnedByClaim(o) })))
|
|
if cfg.Enabled {
|
|
b = b.
|
|
Watches(&gpuv1alpha1.GPUNode{}, all).
|
|
Watches(&corev1.Node{}, all, builder.WithPredicates(nodePlacementChanged)).
|
|
Watches(&corev1.Namespace{}, all, builder.WithPredicates(predicate.LabelChangedPredicate{})).
|
|
Watches(&helmv2.HelmRelease{}, all, builder.WithPredicates(predicate.NewPredicateFuncs(func(o client.Object) bool {
|
|
return o.GetLabels()[appsv1alpha1.ApplicationKindLabel] == tenantKind
|
|
}))).
|
|
Watches(&corev1.Pod{}, all, builder.WithPredicates(predicate.NewPredicateFuncs(podMatters)))
|
|
}
|
|
c, err := b.Build(r)
|
|
if err != nil || !cfg.Enabled {
|
|
return err
|
|
}
|
|
srcs := make([]source.TypedSource[reconcile.Request], 0, 3)
|
|
for _, gvk := range []schema.GroupVersionKind{vmiGVK, vmGVK, kubeVirtGVK} {
|
|
obj := &unstructured.Unstructured{}
|
|
obj.SetGroupVersionKind(gvk)
|
|
srcs = append(srcs, source.Kind[client.Object](mgr.GetCache(), obj, all))
|
|
}
|
|
return mgr.Add(manager.RunnableFunc(func(ctx context.Context) error {
|
|
return watchWhenServed(ctx, mgr.GetRESTMapper(), kubeVirtPoll, c, srcs)
|
|
}))
|
|
}
|
|
|
|
// kubeVirtPoll is how often the binder looks again for the KubeVirt kinds.
|
|
const kubeVirtPoll = 5 * time.Second
|
|
|
|
// watchWhenServed adds the KubeVirt watches to the binder once KubeVirt
|
|
// serves their kinds: a watch on a kind no CRD serves fails the
|
|
// controller's start, and on a fresh install GPUs are enabled before
|
|
// KubeVirt's operator installs its CRDs. Until then a pass reads no
|
|
// KubeVirt object (listKubeVirt).
|
|
func watchWhenServed(ctx context.Context, mapper meta.RESTMapper, interval time.Duration,
|
|
c interface {
|
|
Watch(source.TypedSource[reconcile.Request]) error
|
|
}, srcs []source.TypedSource[reconcile.Request]) error {
|
|
err := WaitForKinds(ctx, mapper, interval, func(k schema.GroupVersionKind, err error) {
|
|
log.FromContext(ctx).Info("waiting for a KubeVirt kind the GPU binder watches", "kind", k.String(), "reason", err.Error())
|
|
}, vmiGVK, vmGVK, kubeVirtGVK)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
for _, src := range srcs {
|
|
if err := c.Watch(src); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// nodePlacementChanged drops node updates that cannot change placement,
|
|
// such as the kubelet's periodic status writes.
|
|
var nodePlacementChanged = predicate.Funcs{UpdateFunc: func(e event.UpdateEvent) bool {
|
|
o, ok1 := e.ObjectOld.(*corev1.Node)
|
|
n, ok2 := e.ObjectNew.(*corev1.Node)
|
|
if !ok1 || !ok2 {
|
|
return true
|
|
}
|
|
return o.Spec.Unschedulable != n.Spec.Unschedulable ||
|
|
!equality.Semantic.DeepEqual(o.Spec.Taints, n.Spec.Taints) ||
|
|
!equality.Semantic.DeepEqual(o.Labels, n.Labels) ||
|
|
!equality.Semantic.DeepEqual(o.Status.Allocatable, n.Status.Allocatable) ||
|
|
model.Ready(o) != model.Ready(n)
|
|
}}
|
|
|
|
// podMatters keeps the events of launcher pods with claim references, gated
|
|
// or pinned, and of pods that can change GPU usage.
|
|
func podMatters(o client.Object) bool {
|
|
return o.GetLabels()[gpu.LabelClaimReference] == gpu.LabelValueTrue || requestsExtendedResource(o)
|
|
}
|
|
|
|
// requestsExtendedResource keeps pod events that can change GPU usage
|
|
// without parsing the effective resource-name set on every pod event.
|
|
func requestsExtendedResource(o client.Object) bool {
|
|
p, ok := o.(*corev1.Pod)
|
|
if !ok {
|
|
return false
|
|
}
|
|
for _, cs := range [][]corev1.Container{p.Spec.Containers, p.Spec.InitContainers} {
|
|
for i := range cs {
|
|
for _, rl := range []corev1.ResourceList{cs[i].Resources.Limits, cs[i].Resources.Requests} {
|
|
for name := range rl {
|
|
// Every virt-launcher pod requests devices.kubevirt.io/kvm.
|
|
if strings.Contains(string(name), "/") && !strings.HasPrefix(string(name), "devices.kubevirt.io/") {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|