mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 12:16:03 +09:00
The webhook fell back to the tenant class only when an application left spec.schedulingClass empty. A value naming a class that does not exist, or one the tenant does not allow, left the pod with no scheduler at all, so a typo, or a deliberate bogus name, in any application lifted the placement constraint the tenant administrator had set. Admission sees the application only once, so a class removed from the allowed list afterwards has to be caught here as well. Naming the tenant's own class needs no entry in the list, being the same as leaving the field empty. The application class is looked up once, so a class deleted between deciding and injecting cannot leave the pod with neither class. A lookup error fails the admission instead of counting as absence: otherwise a timeout or a 5xx from the apiserver would admit the Pod on the default scheduler, outside the tenant's constraint, until it was recreated. Under failurePolicy Fail its controller retries. Only an absent class, or an absent SchedulingClass CRD, means there is nothing to inject. Assisted-by: LLM Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
429 lines
15 KiB
Go
429 lines
15 KiB
Go
package lineagecontrollerwebhook
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/cozystack/cozystack/pkg/lineage"
|
|
admissionv1 "k8s.io/api/admission/v1"
|
|
corev1 "k8s.io/api/core/v1"
|
|
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
|
"k8s.io/apimachinery/pkg/api/meta"
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
|
"k8s.io/apimachinery/pkg/runtime"
|
|
"k8s.io/apimachinery/pkg/runtime/schema"
|
|
utiljson "k8s.io/apimachinery/pkg/util/json"
|
|
"k8s.io/apimachinery/pkg/util/validation"
|
|
"k8s.io/client-go/dynamic"
|
|
"k8s.io/client-go/rest"
|
|
ctrl "sigs.k8s.io/controller-runtime"
|
|
"sigs.k8s.io/controller-runtime/pkg/client"
|
|
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
|
|
"sigs.k8s.io/controller-runtime/pkg/log"
|
|
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
|
|
|
|
schedulerapi "github.com/cozystack/cozystack-scheduler/pkg/apis/v1alpha1"
|
|
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
|
|
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
|
|
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
|
|
)
|
|
|
|
var (
|
|
ErrNoAncestors = errors.New("no managed apps found in lineage")
|
|
ErrAncestryAmbiguous = errors.New("object ancestry is ambiguous")
|
|
)
|
|
|
|
const (
|
|
ManagedObjectKey = "internal.cozystack.io/managed-by-cozystack"
|
|
ManagerGroupKey = "apps.cozystack.io/application.group"
|
|
ManagerKindKey = "apps.cozystack.io/application.kind"
|
|
ManagerNameKey = "apps.cozystack.io/application.name"
|
|
)
|
|
|
|
// getResourceSelectors returns the appropriate ApplicationDefinitionResources for a given GroupKind
|
|
func (h *LineageControllerWebhook) getResourceSelectors(gk schema.GroupKind, crd *cozyv1alpha1.ApplicationDefinition) *cozyv1alpha1.ApplicationDefinitionResources {
|
|
switch {
|
|
case gk.Group == "" && gk.Kind == "Secret":
|
|
return &crd.Spec.Secrets
|
|
case gk.Group == "" && gk.Kind == "Service":
|
|
return &crd.Spec.Services
|
|
case gk.Group == "networking.k8s.io" && gk.Kind == "Ingress":
|
|
return &crd.Spec.Ingresses
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// SetupWithManager registers the handler with the webhook server.
|
|
func (h *LineageControllerWebhook) SetupWithManagerAsWebhook(mgr ctrl.Manager) error {
|
|
cfg := rest.CopyConfig(mgr.GetConfig())
|
|
|
|
var err error
|
|
h.dynClient, err = dynamic.NewForConfig(cfg)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
httpClient, err := rest.HTTPClientFor(cfg)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
h.mapper, err = apiutil.NewDynamicRESTMapper(cfg, httpClient)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
h.ownerCache = lineage.NewObjectCache(ownerCacheTTL)
|
|
|
|
h.initConfig()
|
|
// Register HTTP path -> handler.
|
|
mgr.GetWebhookServer().Register("/mutate-lineage", &admission.Webhook{Handler: h})
|
|
|
|
return nil
|
|
}
|
|
|
|
// InjectDecoder lets controller-runtime give us a decoder for AdmissionReview requests.
|
|
func (h *LineageControllerWebhook) InjectDecoder(d admission.Decoder) error {
|
|
h.decoder = d
|
|
return nil
|
|
}
|
|
|
|
// Handle is called for each AdmissionReview that matches the webhook config.
|
|
func (h *LineageControllerWebhook) Handle(ctx context.Context, req admission.Request) admission.Response {
|
|
logger := log.FromContext(ctx).WithValues(
|
|
"gvk", req.Kind.String(),
|
|
"namespace", req.Namespace,
|
|
"name", req.Name,
|
|
"operation", req.Operation,
|
|
)
|
|
warn := make(admission.Warnings, 0)
|
|
|
|
obj := &unstructured.Unstructured{}
|
|
if err := h.decodeUnstructured(req, obj); err != nil {
|
|
return admission.Errored(400, fmt.Errorf("decode object: %w", err))
|
|
}
|
|
|
|
// The objectSelector skips objects carrying the managed label, but on UPDATE
|
|
// it matches if either the old or the new object does. Pods go on, since
|
|
// every Pod admission also needs applySchedulingClass.
|
|
if obj.GetKind() != "Pod" && hasAllLineageLabels(obj) {
|
|
logger.V(1).Info("object already carries lineage labels, skipping owner walk")
|
|
return admission.Allowed("lineage labels already present")
|
|
}
|
|
|
|
owner, err := h.getOwner(ctx, obj)
|
|
switch {
|
|
case err != nil && errors.Is(err, ErrAncestryAmbiguous):
|
|
warn = append(warn, "object ancestry ambiguous, using first ancestor found")
|
|
case err != nil && errors.Is(err, ErrNoAncestors):
|
|
// not a problem, mark object as unmanaged
|
|
case err != nil:
|
|
logger.Error(err, "error computing lineage labels")
|
|
return admission.Errored(500, fmt.Errorf("error computing lineage labels: %w", err))
|
|
}
|
|
labels, err := h.computeLabels(ctx, obj, owner, req.Operation)
|
|
if err != nil {
|
|
logger.Error(err, "error computing lineage labels")
|
|
return admission.Errored(500, fmt.Errorf("error computing lineage labels: %w", err))
|
|
}
|
|
|
|
h.applyLabels(obj, labels)
|
|
|
|
if err := h.applySchedulingClass(ctx, obj, owner, req.Namespace); err != nil {
|
|
logger.Error(err, "error applying scheduling class")
|
|
return admission.Errored(500, fmt.Errorf("error applying scheduling class: %w", err))
|
|
}
|
|
|
|
mutated, err := json.Marshal(obj)
|
|
if err != nil {
|
|
return admission.Errored(500, fmt.Errorf("marshal mutated pod: %w", err))
|
|
}
|
|
logger.V(1).Info("mutated pod", "namespace", obj.GetNamespace(), "name", obj.GetName())
|
|
return admission.PatchResponseFromRaw(req.Object.Raw, mutated).WithWarnings(warn...)
|
|
}
|
|
|
|
func (h *LineageControllerWebhook) getOwner(ctx context.Context, o *unstructured.Unstructured) (*unstructured.Unstructured, error) {
|
|
owners := lineage.WalkOwnershipGraphWithCache(ctx, h.dynClient, h.mapper, h, h.ownerCache, o)
|
|
if len(owners) == 0 {
|
|
return nil, ErrNoAncestors
|
|
}
|
|
obj, err := owners[0].GetUnstructuredCached(ctx, h.dynClient, h.mapper, h.ownerCache)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(owners) > 1 {
|
|
err = ErrAncestryAmbiguous
|
|
}
|
|
return obj, err
|
|
}
|
|
|
|
func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstructured.Unstructured, owner *unstructured.Unstructured, op admissionv1.Operation) (map[string]string, error) {
|
|
if owner == nil {
|
|
return nil, nil
|
|
}
|
|
gv, err := schema.ParseGroupVersion(owner.GetAPIVersion())
|
|
if err != nil {
|
|
// should never happen, we got an APIVersion right from the API
|
|
return nil, fmt.Errorf("could not parse APIVersion %s to a group and version: %w", owner.GetAPIVersion(), err)
|
|
}
|
|
labels := map[string]string{
|
|
// truncate apigroup to first 63 chars
|
|
ManagedObjectKey: "true",
|
|
ManagerGroupKey: func(s string) string {
|
|
if len(s) < 63 {
|
|
return s
|
|
}
|
|
s = s[:63]
|
|
for b := s[62]; (b < 'a' || b > 'z') && (b < 'A' || b > 'Z') && (b < '0' || b > '9'); s = s[:len(s)-1] {
|
|
b = s[len(s)-1]
|
|
}
|
|
return s
|
|
}(gv.Group),
|
|
ManagerKindKey: owner.GetKind(),
|
|
ManagerNameKey: owner.GetName(),
|
|
}
|
|
templateLabels := map[string]string{
|
|
"kind": strings.ToLower(owner.GetKind()),
|
|
"name": owner.GetName(),
|
|
"namespace": obj.GetNamespace(),
|
|
}
|
|
cfg := h.config.Load().(*runtimeConfig)
|
|
crd := cfg.appCRDMap[appRef{gv.Group, owner.GetKind()}]
|
|
resourceSelectors := h.getResourceSelectors(obj.GroupVersionKind().GroupKind(), crd)
|
|
|
|
selected := matchResourceToExcludeInclude(ctx, obj.GetName(), templateLabels, obj.GetLabels(), resourceSelectors)
|
|
// On CREATE the object may narrow the verdict and never widen it: a
|
|
// rendered "false" is kept even where the definition selects the name, a
|
|
// rendered "true" is replaced. Only on CREATE: a re-admission (UPDATE with
|
|
// managed-by-cozystack dropped, as the cacert controller does on a selector
|
|
// change) carries the "false" this webhook wrote earlier, and keeping it
|
|
// would block a grant.
|
|
if op == admissionv1.Create && obj.GetLabels()[corev1alpha1.TenantResourceLabelKey] == "false" {
|
|
selected = false
|
|
}
|
|
labels[corev1alpha1.TenantResourceLabelKey] = "false"
|
|
if selected {
|
|
labels[corev1alpha1.TenantResourceLabelKey] = corev1alpha1.TenantResourceLabelValue
|
|
}
|
|
return labels, nil
|
|
}
|
|
|
|
func (h *LineageControllerWebhook) applyLabels(o *unstructured.Unstructured, labels map[string]string) {
|
|
existing := o.GetLabels()
|
|
if existing == nil {
|
|
existing = make(map[string]string)
|
|
}
|
|
maps.Copy(existing, labels)
|
|
o.SetLabels(existing)
|
|
}
|
|
|
|
// hasAllLineageLabels needs every key computeLabels writes, not just
|
|
// ManagedObjectKey: an UPDATE can carry a partial set written by another client,
|
|
// and the tenantsecret registry filters on TenantResourceLabelKey.
|
|
func hasAllLineageLabels(o *unstructured.Unstructured) bool {
|
|
labels := o.GetLabels()
|
|
if labels == nil {
|
|
return false
|
|
}
|
|
if labels[ManagedObjectKey] != "true" {
|
|
return false
|
|
}
|
|
for _, k := range []string{ManagerGroupKey, ManagerKindKey, ManagerNameKey, corev1alpha1.TenantResourceLabelKey} {
|
|
if _, ok := labels[k]; !ok {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// AllowedSchedulingClassesAnnotation lists, comma-separated, the
|
|
// SchedulingClasses an application in the namespace may select through
|
|
// spec.schedulingClass. The tenant chart writes it from the tenant's
|
|
// allowedSchedulingClasses; an absent or empty annotation allows none.
|
|
const AllowedSchedulingClassesAnnotation = "namespace.cozystack.io/allowed-scheduling-classes"
|
|
|
|
// applySchedulingClass injects schedulerName, scheduling-class annotation, and
|
|
// scheduling-class label into Pods whose application or namespace selects a
|
|
// SchedulingClass.
|
|
//
|
|
// The label (in addition to the annotation) lets SchedulingClass authors write
|
|
// podAffinity rules whose labelSelector matches pods across applications that
|
|
// share the same class.
|
|
//
|
|
// The tenant class comes from the namespace label and is set by whoever
|
|
// administers the tenant, so an application may replace it only with a class
|
|
// the namespace allows and that exists. Anything else falls back to the tenant
|
|
// class rather than dropping the injection, which would let a typo in an
|
|
// application lift the tenant's placement constraint. Admission of the
|
|
// application already refuses a class outside the allowed list; checking it
|
|
// again here covers a class removed from the list after the application was
|
|
// admitted.
|
|
//
|
|
// If the resolved SchedulingClass CR does not exist (e.g. the scheduler
|
|
// package is not installed), the injection is silently skipped so that pods
|
|
// are not left Pending.
|
|
func (h *LineageControllerWebhook) applySchedulingClass(ctx context.Context, obj, owner *unstructured.Unstructured, namespace string) error {
|
|
if obj.GetKind() != "Pod" {
|
|
return nil
|
|
}
|
|
logger := log.FromContext(ctx)
|
|
|
|
ns := &corev1.Namespace{}
|
|
if err := h.Get(ctx, client.ObjectKey{Name: namespace}, ns); err != nil {
|
|
return fmt.Errorf("getting namespace %s: %w", namespace, err)
|
|
}
|
|
tenantClass := ns.Labels[schedulerapi.SchedulingClassLabel]
|
|
|
|
schedulingClass, err := h.resolveApplicationClass(ctx, ownerSchedulingClass(owner), tenantClass, ns)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if schedulingClass == "" {
|
|
if tenantClass == "" {
|
|
return nil
|
|
}
|
|
exists, err := h.schedulingClassExists(ctx, tenantClass)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !exists {
|
|
logger.Info("SchedulingClass not found, skipping scheduler injection",
|
|
"schedulingClass", tenantClass, "namespace", namespace)
|
|
return nil
|
|
}
|
|
schedulingClass = tenantClass
|
|
}
|
|
|
|
if err := unstructured.SetNestedField(obj.Object, schedulerapi.SchedulerName, "spec", "schedulerName"); err != nil {
|
|
return fmt.Errorf("setting schedulerName: %w", err)
|
|
}
|
|
|
|
annotations := obj.GetAnnotations()
|
|
if annotations == nil {
|
|
annotations = make(map[string]string)
|
|
}
|
|
annotations[schedulerapi.SchedulingClassAnnotation] = schedulingClass
|
|
obj.SetAnnotations(annotations)
|
|
|
|
// Defence in depth: a SchedulingClass name is a DNS-1123 subdomain (up to
|
|
// 253 chars) while a label value is capped at 63. spec.schedulingClass is
|
|
// schema-capped at 63, but a pre-existing long-named class must degrade to
|
|
// annotation-only injection rather than have the apiserver reject the Pod.
|
|
if errs := validation.IsValidLabelValue(schedulingClass); len(errs) > 0 {
|
|
logger.Info("SchedulingClass name is not a valid label value, skipping co-affinity label",
|
|
"schedulingClass", schedulingClass, "namespace", namespace)
|
|
return nil
|
|
}
|
|
|
|
podLabels := obj.GetLabels()
|
|
if podLabels == nil {
|
|
podLabels = make(map[string]string)
|
|
}
|
|
podLabels[schedulerapi.SchedulingClassLabel] = schedulingClass
|
|
obj.SetLabels(podLabels)
|
|
|
|
return nil
|
|
}
|
|
|
|
// resolveApplicationClass returns the application's class when it may replace
|
|
// the tenant class: it differs from it, the namespace allows it and it exists.
|
|
// It returns "" otherwise, so that the caller falls back to the tenant class.
|
|
// The existence check runs once and its answer is final, since a second
|
|
// lookup that found the class gone would leave the pod with no class at all.
|
|
func (h *LineageControllerWebhook) resolveApplicationClass(ctx context.Context, appClass, tenantClass string, ns *corev1.Namespace) (string, error) {
|
|
if appClass == "" || appClass == tenantClass {
|
|
return "", nil
|
|
}
|
|
logger := log.FromContext(ctx)
|
|
if !slices.Contains(allowedSchedulingClasses(ns), appClass) {
|
|
logger.Info("application SchedulingClass is not allowed in this namespace, keeping the tenant class",
|
|
"schedulingClass", appClass, "tenantSchedulingClass", tenantClass, "namespace", ns.Name)
|
|
return "", nil
|
|
}
|
|
exists, err := h.schedulingClassExists(ctx, appClass)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if !exists {
|
|
logger.Info("application SchedulingClass not found, keeping the tenant class",
|
|
"schedulingClass", appClass, "tenantSchedulingClass", tenantClass, "namespace", ns.Name)
|
|
return "", nil
|
|
}
|
|
return appClass, nil
|
|
}
|
|
|
|
func ownerSchedulingClass(owner *unstructured.Unstructured) string {
|
|
if owner == nil {
|
|
return ""
|
|
}
|
|
var app appsv1alpha1.Application
|
|
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(owner.Object, &app); err != nil {
|
|
return ""
|
|
}
|
|
return app.SchedulingClass()
|
|
}
|
|
|
|
func allowedSchedulingClasses(ns *corev1.Namespace) []string {
|
|
var allowed []string
|
|
for _, name := range strings.Split(ns.Annotations[AllowedSchedulingClassesAnnotation], ",") {
|
|
if name = strings.TrimSpace(name); name != "" {
|
|
allowed = append(allowed, name)
|
|
}
|
|
}
|
|
return allowed
|
|
}
|
|
|
|
// schedulingClassExists reports a missing class, or a missing SchedulingClass
|
|
// CRD, as absence. Any other lookup error is returned: treating a timeout or a
|
|
// 5xx as absence would admit the Pod without the tenant's placement constraint,
|
|
// which it then keeps until it is recreated. Failing the admission lets the
|
|
// Pod's controller retry instead.
|
|
func (h *LineageControllerWebhook) schedulingClassExists(ctx context.Context, name string) (bool, error) {
|
|
_, err := h.dynClient.Resource(schedulingClassGVR).Get(ctx, name, metav1.GetOptions{})
|
|
switch {
|
|
case err == nil:
|
|
return true, nil
|
|
case apierrors.IsNotFound(err) || meta.IsNoMatchError(err):
|
|
return false, nil
|
|
default:
|
|
return false, fmt.Errorf("getting SchedulingClass %s: %w", name, err)
|
|
}
|
|
}
|
|
|
|
var schedulingClassGVR = schema.GroupVersionResource{
|
|
Group: schedulerapi.Group,
|
|
Version: schedulerapi.Version,
|
|
Resource: schedulerapi.Resource,
|
|
}
|
|
|
|
func (h *LineageControllerWebhook) decodeUnstructured(req admission.Request, out *unstructured.Unstructured) error {
|
|
if h.decoder != nil {
|
|
if err := h.decoder.Decode(req, out); err == nil {
|
|
return nil
|
|
}
|
|
if req.Kind.Group != "" || req.Kind.Kind != "" || req.Kind.Version != "" {
|
|
out.SetGroupVersionKind(schema.GroupVersionKind{
|
|
Group: req.Kind.Group,
|
|
Version: req.Kind.Version,
|
|
Kind: req.Kind.Kind,
|
|
})
|
|
if err := h.decoder.Decode(req, out); err == nil {
|
|
return nil
|
|
}
|
|
}
|
|
}
|
|
if len(req.Object.Raw) == 0 {
|
|
return errors.New("empty admission object")
|
|
}
|
|
// encoding/json would turn every number into float64, and an int64 above
|
|
// 2^53 would come back altered in the patch computed against req.Object.Raw.
|
|
return utiljson.Unmarshal(req.Object.Raw, &out.Object)
|
|
}
|