mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-03 02:27:01 +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>
118 lines
4.3 KiB
Go
118 lines
4.3 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
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"strings"
|
|
|
|
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
|
"k8s.io/apimachinery/pkg/api/resource"
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
"k8s.io/apimachinery/pkg/types"
|
|
"k8s.io/apimachinery/pkg/util/validation"
|
|
"sigs.k8s.io/controller-runtime/pkg/client"
|
|
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
|
|
|
|
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"
|
|
)
|
|
|
|
// recordName is the claim's usage record. A claim name is itself up to
|
|
// 253 characters, so a name too long for the prefix is cut short and
|
|
// followed by a hash of the full name, which keeps it stable across passes.
|
|
// The hashed form has a prefix of its own, so no claim name, which a
|
|
// tenant chooses, can reproduce another claim's hashed record, and a
|
|
// 128-bit hash, so two long names sharing the cut cannot be made to meet.
|
|
func recordName(d *gpuv1alpha1.GPUClaim) string {
|
|
const prefix, hashedPrefix = "gpu-", "gpuh-"
|
|
if len(prefix)+len(d.Name) <= validation.DNS1123SubdomainMaxLength {
|
|
return prefix + d.Name
|
|
}
|
|
sum := sha256.Sum256([]byte(d.Name))
|
|
hash := hex.EncodeToString(sum[:16])
|
|
keep := validation.DNS1123SubdomainMaxLength - len(hashedPrefix) - len(hash) - 1
|
|
return hashedPrefix + strings.TrimRight(d.Name[:keep], "-.") + "-" + hash
|
|
}
|
|
|
|
func wantsRecord(d *gpuv1alpha1.GPUClaim) bool {
|
|
return model.InUsageRecords(d.Status.Phase) && !released(d)
|
|
}
|
|
|
|
// usageRecords keeps one Workload per claim that holds GPUs, owned by its
|
|
// GPUClaim and under no WorkloadMonitor, so no tenant label can add a record
|
|
// or drop one. The Workload controller leaves records owned by a GPUClaim
|
|
// alone, and garbage collection removes a record with its claim.
|
|
func (r *Reconciler) usageRecords(ctx context.Context, w *world) []error {
|
|
var errs []error
|
|
want := map[types.NamespacedName]bool{}
|
|
for _, d := range w.claims {
|
|
if wantsRecord(d) {
|
|
want[key(d.Namespace, recordName(d))] = true
|
|
errs = append(errs, r.ensureRecord(ctx, d))
|
|
}
|
|
}
|
|
records := &cozyv1alpha1.WorkloadList{}
|
|
if err := r.Client.List(ctx, records); err != nil {
|
|
return append(errs, err)
|
|
}
|
|
for i := range records.Items {
|
|
rec := &records.Items[i]
|
|
if model.OwnedByClaim(rec) && !want[key(rec.Namespace, rec.Name)] {
|
|
errs = append(errs, client.IgnoreNotFound(r.Client.Delete(ctx, rec)))
|
|
}
|
|
}
|
|
return errs
|
|
}
|
|
|
|
const claimKind = "GPUClaim"
|
|
|
|
func (r *Reconciler) ensureRecord(ctx context.Context, d *gpuv1alpha1.GPUClaim) error {
|
|
rec := &cozyv1alpha1.Workload{ObjectMeta: metav1.ObjectMeta{Name: recordName(d), Namespace: d.Namespace}}
|
|
_, err := controllerutil.CreateOrUpdate(ctx, r.Client, rec, func() error {
|
|
rec.OwnerReferences = []metav1.OwnerReference{{
|
|
APIVersion: gpuv1alpha1.GroupVersion.String(),
|
|
Kind: claimKind,
|
|
Name: d.Name,
|
|
UID: d.UID,
|
|
}}
|
|
rec.Status = cozyv1alpha1.WorkloadStatus{
|
|
Kind: gpu.WorkloadKind,
|
|
Type: d.Spec.ClassName,
|
|
Resources: map[string]resource.Quantity{string(model.ClassQuotaKey(d.Spec.ClassName)): *resource.NewQuantity(int64(d.Spec.Count), resource.DecimalSI)},
|
|
Operational: true,
|
|
}
|
|
return nil
|
|
})
|
|
if apierrors.IsAlreadyExists(err) {
|
|
// A stale cache read the record as missing; the next pass updates it.
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
// deleteRecord removes a released claim's record before its finalizer
|
|
// goes, so the record never outlives the hold.
|
|
func (r *Reconciler) deleteRecord(ctx context.Context, d *gpuv1alpha1.GPUClaim) error {
|
|
rec := &cozyv1alpha1.Workload{ObjectMeta: metav1.ObjectMeta{Name: recordName(d), Namespace: d.Namespace}}
|
|
return client.IgnoreNotFound(r.Client.Delete(ctx, rec))
|
|
}
|