diff --git a/internal/lineagecontrollerwebhook/webhook.go b/internal/lineagecontrollerwebhook/webhook.go index 52602c7de..57aaf2898 100644 --- a/internal/lineagecontrollerwebhook/webhook.go +++ b/internal/lineagecontrollerwebhook/webhook.go @@ -6,11 +6,14 @@ import ( "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" @@ -240,52 +243,62 @@ func hasAllLineageLabels(o *unstructured.Unstructured) bool { 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 namespace carries the -// scheduler.cozystack.io/scheduling-class label. +// 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. // -// If the referenced SchedulingClass CR does not exist (e.g. the scheduler +// 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) - // Determine scheduling class: owner Application field takes priority, - // then fall back to namespace label. - var schedulingClass string - if owner != nil { - var app appsv1alpha1.Application - if err := runtime.DefaultUnstructuredConverter.FromUnstructured(owner.Object, &app); err == nil { - schedulingClass = app.SchedulingClass() - } - } - if schedulingClass == "" { - ns := &corev1.Namespace{} - if err := h.Get(ctx, client.ObjectKey{Name: namespace}, ns); err != nil { - return fmt.Errorf("getting namespace %s: %w", namespace, err) - } - schedulingClass = ns.Labels[schedulerapi.SchedulingClassLabel] + 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] - if schedulingClass == "" { - return nil - } - - // Verify that the referenced SchedulingClass CR exists. - // If the CRD is not installed or the CR is missing, skip injection - // so that pods are not stuck Pending on a non-existent scheduler. - _, err := h.dynClient.Resource(schedulingClassGVR).Get(ctx, schedulingClass, metav1.GetOptions{}) + schedulingClass, err := h.resolveApplicationClass(ctx, ownerSchedulingClass(owner), tenantClass, ns) if err != nil { - logger := log.FromContext(ctx) - logger.Info("SchedulingClass not found, skipping scheduler injection", - "schedulingClass", schedulingClass, "namespace", namespace) - return 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 { @@ -304,7 +317,7 @@ func (h *LineageControllerWebhook) applySchedulingClass(ctx context.Context, obj // 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 { - log.FromContext(ctx).Info("SchedulingClass name is not a valid label value, skipping co-affinity label", + logger.Info("SchedulingClass name is not a valid label value, skipping co-affinity label", "schedulingClass", schedulingClass, "namespace", namespace) return nil } @@ -319,6 +332,71 @@ func (h *LineageControllerWebhook) applySchedulingClass(ctx context.Context, obj 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, diff --git a/internal/lineagecontrollerwebhook/webhook_test.go b/internal/lineagecontrollerwebhook/webhook_test.go index 5170d70e1..6323d9616 100644 --- a/internal/lineagecontrollerwebhook/webhook_test.go +++ b/internal/lineagecontrollerwebhook/webhook_test.go @@ -3,6 +3,7 @@ package lineagecontrollerwebhook import ( "context" "encoding/json" + "errors" "sort" "strings" "testing" @@ -12,6 +13,7 @@ import ( corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" 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" @@ -19,6 +21,8 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" dynamicfake "k8s.io/client-go/dynamic/fake" clientgoscheme "k8s.io/client-go/kubernetes/scheme" + k8stesting "k8s.io/client-go/testing" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" ) @@ -481,10 +485,23 @@ func addSchedulingClassCR(t *testing.T, h *LineageControllerWebhook, name string } } +func allowSchedulingClasses(t *testing.T, h *LineageControllerWebhook, namespace, allowed string) { + t.Helper() + ns := &corev1.Namespace{} + if err := h.Get(context.Background(), client.ObjectKey{Name: namespace}, ns); err != nil { + t.Fatalf("getting namespace %s: %v", namespace, err) + } + ns.Annotations = map[string]string{AllowedSchedulingClassesAnnotation: allowed} + if err := h.Update(context.Background(), ns); err != nil { + t.Fatalf("updating namespace %s: %v", namespace, err) + } +} + func TestApplySchedulingClass_OwnerApplicationClassOverridesNamespace(t *testing.T) { ctx := context.Background() h := newWebhookTestEnv(t, "tenant-acme", testSchedulingClass, true) addSchedulingClassCR(t, h, "app-class") + allowSchedulingClasses(t, h, "tenant-acme", "other-class, app-class") owner := newOwnerApplication("tenant-acme", "db", map[string]interface{}{ "replicas": int64(2), "schedulingClass": "app-class", @@ -536,6 +553,7 @@ func TestApplySchedulingClass_ClassNameTooLongForLabelSkipsOnlyLabel(t *testing. longClass := strings.Repeat("a", 64) h := newWebhookTestEnv(t, "tenant-acme", "", false) addSchedulingClassCR(t, h, longClass) + allowSchedulingClasses(t, h, "tenant-acme", longClass) owner := newOwnerApplication("tenant-acme", "db", map[string]interface{}{"schedulingClass": longClass}) pod := newPod("tenant-acme", "db-0") @@ -553,3 +571,171 @@ func TestApplySchedulingClass_ClassNameTooLongForLabelSkipsOnlyLabel(t *testing. t.Errorf("expected pod spec.schedulerName=%s, got %q", schedulerapi.SchedulerName, sched) } } + +// The tenant class is the administrator's placement constraint. An application +// class that the namespace does not allow, or that does not exist, must leave +// it in force instead of dropping the injection altogether. +func TestApplySchedulingClass_RejectedOwnerApplicationClassKeepsTenantClass(t *testing.T) { + for _, tc := range []struct { + name string + appClass string + allowed string + existing []string + }{ + {name: "class does not exist", appClass: "does-not-exist", allowed: "does-not-exist"}, + {name: "class not in the allowed list", appClass: "app-class", allowed: "other-class", existing: []string{"app-class"}}, + {name: "no allowed list", appClass: "app-class", existing: []string{"app-class"}}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + h := newWebhookTestEnv(t, "tenant-acme", testSchedulingClass, true) + for _, name := range tc.existing { + addSchedulingClassCR(t, h, name) + } + if tc.allowed != "" { + allowSchedulingClasses(t, h, "tenant-acme", tc.allowed) + } + owner := newOwnerApplication("tenant-acme", "db", map[string]interface{}{"schedulingClass": tc.appClass}) + pod := newPod("tenant-acme", "db-0") + + if err := h.applySchedulingClass(ctx, pod, owner, "tenant-acme"); err != nil { + t.Fatalf("applySchedulingClass returned error: %v", err) + } + + if got := pod.GetLabels()[schedulerapi.SchedulingClassLabel]; got != testSchedulingClass { + t.Errorf("expected pod label %s=%s, got %q", schedulerapi.SchedulingClassLabel, testSchedulingClass, got) + } + if got := pod.GetAnnotations()[schedulerapi.SchedulingClassAnnotation]; got != testSchedulingClass { + t.Errorf("expected pod annotation %s=%s, got %q", schedulerapi.SchedulingClassAnnotation, testSchedulingClass, got) + } + if sched, _, _ := unstructured.NestedString(pod.Object, "spec", "schedulerName"); sched != schedulerapi.SchedulerName { + t.Errorf("expected pod spec.schedulerName=%s, got %q", schedulerapi.SchedulerName, sched) + } + }) + } +} + +// Naming the tenant's own class is the same as leaving the field empty, so it +// needs no entry in the allowed list. +func TestApplySchedulingClass_OwnerApplicationNamingTenantClassNeedsNoAllowedList(t *testing.T) { + ctx := context.Background() + h := newWebhookTestEnv(t, "tenant-acme", testSchedulingClass, true) + owner := newOwnerApplication("tenant-acme", "db", map[string]interface{}{"schedulingClass": testSchedulingClass}) + pod := newPod("tenant-acme", "db-0") + + if err := h.applySchedulingClass(ctx, pod, owner, "tenant-acme"); err != nil { + t.Fatalf("applySchedulingClass returned error: %v", err) + } + + if got := pod.GetLabels()[schedulerapi.SchedulingClassLabel]; got != testSchedulingClass { + t.Errorf("expected pod label %s=%s, got %q", schedulerapi.SchedulingClassLabel, testSchedulingClass, got) + } +} + +// Without a tenant class there is nothing to fall back to: a rejected +// application class leaves the pod on the default scheduler. +func TestApplySchedulingClass_RejectedOwnerApplicationClassWithoutTenantClassIsNoOp(t *testing.T) { + ctx := context.Background() + h := newWebhookTestEnv(t, "tenant-acme", "", false) + addSchedulingClassCR(t, h, "app-class") + owner := newOwnerApplication("tenant-acme", "db", map[string]interface{}{"schedulingClass": "app-class"}) + pod := newPod("tenant-acme", "db-0") + + if err := h.applySchedulingClass(ctx, pod, owner, "tenant-acme"); err != nil { + t.Fatalf("applySchedulingClass returned error: %v", err) + } + + if _, ok := pod.GetAnnotations()[schedulerapi.SchedulingClassAnnotation]; ok { + t.Errorf("pod annotation should not be set for a class the namespace does not allow") + } + if sched, _, _ := unstructured.NestedString(pod.Object, "spec", "schedulerName"); sched != "" { + t.Errorf("pod spec.schedulerName should not be set, got %q", sched) + } +} + +// failSchedulingClassGet makes every SchedulingClass lookup return err. +func failSchedulingClassGet(h *LineageControllerWebhook, err error) { + h.dynClient.(*dynamicfake.FakeDynamicClient).PrependReactor("get", schedulerapi.Resource, + func(k8stesting.Action) (bool, runtime.Object, error) { return true, nil, err }) +} + +// A lookup that fails for any reason other than absence must fail the +// admission, so the Pod's controller retries it. Admitting the Pod without +// the tenant class would leave it on the default scheduler until recreated. +func TestApplySchedulingClass_TransientLookupErrorFailsAdmission(t *testing.T) { + transient := apierrors.NewInternalError(errors.New("etcdserver: request timed out")) + for _, tc := range []struct { + name string + owner *unstructured.Unstructured + }{ + {name: "tenant class", owner: nil}, + {name: "application class", owner: newOwnerApplication("tenant-acme", "db", map[string]interface{}{"schedulingClass": "app-class"})}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + h := newWebhookTestEnv(t, "tenant-acme", testSchedulingClass, true) + allowSchedulingClasses(t, h, "tenant-acme", "app-class") + failSchedulingClassGet(h, transient) + pod := newPod("tenant-acme", "db-0") + + err := h.applySchedulingClass(ctx, pod, tc.owner, "tenant-acme") + if !apierrors.IsInternalError(err) { + t.Fatalf("expected the lookup error to be returned, got %v", err) + } + if _, ok := pod.GetAnnotations()[schedulerapi.SchedulingClassAnnotation]; ok { + t.Errorf("pod must not be mutated when the lookup fails") + } + }) + } +} + +// Without the SchedulingClass CRD there is no scheduler to send the Pod to, so +// a NoMatch error is absence, like NotFound, and the injection is skipped. +func TestApplySchedulingClass_MissingCRDSkipsInjection(t *testing.T) { + ctx := context.Background() + h := newWebhookTestEnv(t, "tenant-acme", testSchedulingClass, true) + failSchedulingClassGet(h, &meta.NoKindMatchError{GroupKind: schema.GroupKind{Group: schedulerapi.Group, Kind: "SchedulingClass"}}) + pod := newPod("tenant-acme", "db-0") + + if err := h.applySchedulingClass(ctx, pod, nil, "tenant-acme"); err != nil { + t.Fatalf("applySchedulingClass returned error: %v", err) + } + if sched, _, _ := unstructured.NestedString(pod.Object, "spec", "schedulerName"); sched != "" { + t.Errorf("pod spec.schedulerName should not be set without the CRD, got %q", sched) + } +} + +// The application class is looked up once. If it were looked up again before +// injecting, a class deleted between the two lookups would leave the pod with +// neither the application class nor the tenant class. +func TestApplySchedulingClass_ApplicationClassDeletedDuringAdmissionKeepsAClass(t *testing.T) { + ctx := context.Background() + h := newWebhookTestEnv(t, "tenant-acme", testSchedulingClass, true) + addSchedulingClassCR(t, h, "app-class") + allowSchedulingClasses(t, h, "tenant-acme", "app-class") + lookups := 0 + h.dynClient.(*dynamicfake.FakeDynamicClient).PrependReactor("get", schedulerapi.Resource, + func(action k8stesting.Action) (bool, runtime.Object, error) { + if action.(k8stesting.GetAction).GetName() != "app-class" { + return false, nil, nil + } + lookups++ + if lookups == 1 { + return false, nil, nil + } + return true, nil, apierrors.NewNotFound(schema.GroupResource{Group: schedulerapi.Group, Resource: schedulerapi.Resource}, "app-class") + }) + owner := newOwnerApplication("tenant-acme", "db", map[string]interface{}{"schedulingClass": "app-class"}) + pod := newPod("tenant-acme", "db-0") + + if err := h.applySchedulingClass(ctx, pod, owner, "tenant-acme"); err != nil { + t.Fatalf("applySchedulingClass returned error: %v", err) + } + + if sched, _, _ := unstructured.NestedString(pod.Object, "spec", "schedulerName"); sched != schedulerapi.SchedulerName { + t.Errorf("expected pod spec.schedulerName=%s, got %q", schedulerapi.SchedulerName, sched) + } + if got := pod.GetAnnotations()[schedulerapi.SchedulingClassAnnotation]; got != "app-class" { + t.Errorf("expected pod annotation %s=app-class, got %q", schedulerapi.SchedulingClassAnnotation, got) + } +} diff --git a/pkg/apis/apps/v1alpha1/types.go b/pkg/apis/apps/v1alpha1/types.go index 5a18a8601..deb34e40d 100644 --- a/pkg/apis/apps/v1alpha1/types.go +++ b/pkg/apis/apps/v1alpha1/types.go @@ -77,9 +77,9 @@ type ApplicationStatus struct { } // SchedulingClass returns the scheduling class requested by this Application, -// parsed from its Spec JSON under the top-level `schedulingClass` key. When set, -// the named SchedulingClass takes precedence over any tenant-level class for -// the workloads of this Application. +// parsed from its Spec JSON under the top-level `schedulingClass` key. It is a +// request: the lineage webhook applies it in place of the tenant-level class +// only when the namespace allows it and the SchedulingClass exists. // // A missing or empty field returns "" — the caller then falls back to the // namespace-level scheduling class.