Files
cozystack/internal/lineagecontrollerwebhook/webhook_test.go
T
Mattia Eleuteri e67a514903 fix(lineage-webhook): keep the tenant class when an application's is refused
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>
2026-11-23 08:05:08 +01:00

742 lines
28 KiB
Go

package lineagecontrollerwebhook
import (
"context"
"encoding/json"
"errors"
"sort"
"strings"
"testing"
schedulerapi "github.com/cozystack/cozystack-scheduler/pkg/apis/v1alpha1"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
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"
"k8s.io/apimachinery/pkg/runtime"
"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"
)
const podWithNumericFields = `{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "harbor-demo-core-0",
"namespace": "tenant-demo",
"labels": {"helm.toolkit.fluxcd.io/name": "harbor-demo"},
"annotations": {"existing": "kept"}
},
"spec": {
"terminationGracePeriodSeconds": 30,
"activeDeadlineSeconds": 9007199254740993,
"containers": [{
"name": "core",
"image": "goharbor/harbor-core:v2.11.0",
"ports": [{"containerPort": 8080, "protocol": "TCP"}],
"resources": {
"limits": {"cpu": "500m", "memory": "512Mi"},
"requests": {"cpu": "0.1", "memory": "128Mi"}
}
}]
}
}`
func newHandleTestWebhook(t *testing.T) *LineageControllerWebhook {
t.Helper()
scheme := newWebhookScheme(t)
if err := clientgoscheme.AddToScheme(scheme); err != nil {
t.Fatalf("add client-go scheme: %v", err)
}
ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{
Name: "tenant-demo",
Labels: map[string]string{schedulerapi.SchedulingClassLabel: "gpu"},
}}
hrGVK := schema.GroupVersionKind{Group: "helm.toolkit.fluxcd.io", Version: "v2", Kind: "HelmRelease"}
appGVK := schema.GroupVersionKind{Group: "apps.cozystack.io", Version: "v1alpha1", Kind: "Harbor"}
scGVK := schema.GroupVersionKind{Group: schedulerapi.Group, Version: schedulerapi.Version, Kind: "SchedulingClass"}
mapper := meta.NewDefaultRESTMapper(nil)
mapper.Add(hrGVK, meta.RESTScopeNamespace)
mapper.Add(appGVK, meta.RESTScopeNamespace)
obj := func(gvk schema.GroupVersionKind, namespace, name string, labels map[string]string) *unstructured.Unstructured {
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(gvk)
u.SetNamespace(namespace)
u.SetName(name)
u.SetLabels(labels)
return u
}
dyn := dynamicfake.NewSimpleDynamicClient(runtime.NewScheme(),
obj(hrGVK, "tenant-demo", "harbor-demo", map[string]string{
ManagerKindKey: "Harbor",
ManagerGroupKey: "apps.cozystack.io",
ManagerNameKey: "demo",
}),
obj(appGVK, "tenant-demo", "demo", nil),
obj(scGVK, "", "gpu", nil),
)
w := &LineageControllerWebhook{
Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(ns).Build(),
Scheme: scheme,
dynClient: dyn,
mapper: mapper,
}
w.initConfig()
return w
}
// TestHandle_PatchTouchesOnlyLineageAndScheduling pins that the JSON
// patch computed from the re-marshalled Pod contains the lineage labels
// and scheduler fields and nothing else: numbers the webhook never
// touched, including an int64 beyond float64 precision, must not show
// up as replace operations.
func TestHandle_PatchTouchesOnlyLineageAndScheduling(t *testing.T) {
w := newHandleTestWebhook(t)
resp := w.Handle(context.Background(), admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{
Kind: metav1.GroupVersionKind{Version: "v1", Kind: "Pod"},
Namespace: "tenant-demo",
Name: "harbor-demo-core-0",
Operation: admissionv1.Create,
Object: runtime.RawExtension{Raw: []byte(podWithNumericFields)},
}})
if !resp.Allowed {
t.Fatalf("expected allowed response, got %+v", resp.Result)
}
want := map[string]any{
"add /metadata/labels/internal.cozystack.io~1managed-by-cozystack": "true",
"add /metadata/labels/apps.cozystack.io~1application.group": "apps.cozystack.io",
"add /metadata/labels/apps.cozystack.io~1application.kind": "Harbor",
"add /metadata/labels/apps.cozystack.io~1application.name": "demo",
"add /metadata/labels/internal.cozystack.io~1tenantresource": "false",
"add /metadata/annotations/scheduler.cozystack.io~1scheduling-class": "gpu",
"add /metadata/labels/scheduler.cozystack.io~1scheduling-class": "gpu",
"add /spec/schedulerName": schedulerapi.SchedulerName,
}
got := map[string]any{}
var keys []string
for _, p := range resp.Patches {
k := p.Operation + " " + p.Path
got[k] = p.Value
keys = append(keys, k)
}
sort.Strings(keys)
if len(resp.Patches) != len(want) {
t.Errorf("expected %d patch operations, got %d: %v", len(want), len(resp.Patches), keys)
}
for k, v := range want {
if got[k] != v {
t.Errorf("patch %q = %#v, want %#v", k, got[k], v)
}
}
for _, p := range resp.Patches {
if _, ok := want[p.Operation+" "+p.Path]; !ok {
t.Errorf("unexpected patch operation %s %s = %#v", p.Operation, p.Path, p.Value)
}
}
}
// TestHandle_ReadmissionShortCircuit pins which UPDATEs skip the owner walk.
// Every object points at the harbor-demo HelmRelease but names a stale
// application, so an object that goes through the walk gets its labels
// rewritten, and one that skips it gets no patch at all.
func TestHandle_ReadmissionShortCircuit(t *testing.T) {
fullLabels := func() map[string]string {
return map[string]string{
"helm.toolkit.fluxcd.io/name": "harbor-demo",
ManagedObjectKey: "true",
ManagerGroupKey: "apps.cozystack.io",
ManagerKindKey: "Harbor",
ManagerNameKey: "stale",
corev1alpha1.TenantResourceLabelKey: "false",
}
}
escape := func(k string) string {
return "/metadata/labels/" + strings.ReplaceAll(k, "/", "~1")
}
tests := []struct {
name string
kind string
labels func() map[string]string
// wantPatches lists "op path" entries that must appear; nil means the
// response must carry no patch at all.
wantPatches []string
}{
{
name: "secret with every lineage label skips the walk",
kind: "Secret",
labels: fullLabels,
},
{
name: "pod with every lineage label still gets the scheduling fields",
kind: "Pod",
labels: fullLabels,
wantPatches: []string{"add /spec/schedulerName", "replace " + escape(ManagerNameKey)},
},
{
name: "secret marked unmanaged goes through the walk",
kind: "Secret",
labels: func() map[string]string {
l := fullLabels()
l[ManagedObjectKey] = "false"
return l
},
wantPatches: []string{"replace " + escape(ManagedObjectKey), "replace " + escape(ManagerNameKey)},
},
{
name: "secret missing the application kind goes through the walk",
kind: "Secret",
labels: func() map[string]string {
l := fullLabels()
delete(l, ManagerKindKey)
return l
},
wantPatches: []string{"add " + escape(ManagerKindKey), "replace " + escape(ManagerNameKey)},
},
{
name: "secret missing the tenantresource label goes through the walk",
kind: "Secret",
labels: func() map[string]string {
l := fullLabels()
delete(l, corev1alpha1.TenantResourceLabelKey)
return l
},
wantPatches: []string{"add " + escape(corev1alpha1.TenantResourceLabelKey), "replace " + escape(ManagerNameKey)},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := newHandleTestWebhook(t)
w.config.Store(&runtimeConfig{appCRDMap: map[appRef]*cozyv1alpha1.ApplicationDefinition{
{"apps.cozystack.io", "Harbor"}: {Spec: cozyv1alpha1.ApplicationDefinitionSpec{
Application: cozyv1alpha1.ApplicationDefinitionApplication{Kind: "Harbor"},
}},
}})
obj := &unstructured.Unstructured{}
obj.SetAPIVersion("v1")
obj.SetKind(tt.kind)
obj.SetNamespace("tenant-demo")
obj.SetName("harbor-demo-core")
obj.SetLabels(tt.labels())
if tt.kind == "Pod" {
obj.Object["spec"] = map[string]any{"containers": []any{map[string]any{"name": "core", "image": "core"}}}
}
raw, err := json.Marshal(obj)
if err != nil {
t.Fatalf("marshal object: %v", err)
}
resp := w.Handle(context.Background(), admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{
Kind: metav1.GroupVersionKind{Version: "v1", Kind: tt.kind},
Namespace: "tenant-demo",
Name: "harbor-demo-core",
Operation: admissionv1.Update,
Object: runtime.RawExtension{Raw: raw},
OldObject: runtime.RawExtension{Raw: raw},
}})
if !resp.Allowed {
t.Fatalf("expected allowed response, got %+v", resp.Result)
}
got := map[string]bool{}
var keys []string
for _, p := range resp.Patches {
k := p.Operation + " " + p.Path
got[k] = true
keys = append(keys, k)
}
sort.Strings(keys)
if tt.wantPatches == nil {
if len(resp.Patches) != 0 {
t.Errorf("expected no patch, got %v", keys)
}
return
}
for _, k := range tt.wantPatches {
if !got[k] {
t.Errorf("missing patch %q, got %v", k, keys)
}
}
})
}
}
const testSchedulingClass = "co-region-test"
// newSchedulingClassCR builds an unstructured SchedulingClass CR the fake
// dynamic client can serve.
func newSchedulingClassCR(name string) *unstructured.Unstructured {
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(schema.GroupVersionKind{
Group: schedulerapi.Group,
Version: schedulerapi.Version,
Kind: "SchedulingClass",
})
u.SetName(name)
return u
}
// newWebhookTestEnv builds a LineageControllerWebhook wired with fakes,
// pre-populated with a Namespace carrying the scheduling-class label and a
// SchedulingClass CR by that name.
func newWebhookTestEnv(t *testing.T, namespace string, classOnNamespace string, classExists bool) *LineageControllerWebhook {
t.Helper()
testScheme := runtime.NewScheme()
_ = clientgoscheme.AddToScheme(testScheme)
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
},
}
if classOnNamespace != "" {
ns.Labels = map[string]string{
schedulerapi.SchedulingClassLabel: classOnNamespace,
}
}
c := fake.NewClientBuilder().
WithScheme(testScheme).
WithObjects(ns).
Build()
gvr := schema.GroupVersionResource{
Group: schedulerapi.Group,
Version: schedulerapi.Version,
Resource: schedulerapi.Resource,
}
dynObjs := []runtime.Object{}
if classExists {
dynObjs = append(dynObjs, newSchedulingClassCR(classOnNamespace))
}
dyn := dynamicfake.NewSimpleDynamicClientWithCustomListKinds(
testScheme,
map[schema.GroupVersionResource]string{gvr: "SchedulingClassList"},
dynObjs...,
)
return &LineageControllerWebhook{
Client: c,
Scheme: testScheme,
dynClient: dyn,
}
}
// newPod returns a minimal unstructured Pod for mutation tests.
func newPod(namespace, name string) *unstructured.Unstructured {
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(schema.GroupVersionKind{Version: "v1", Kind: "Pod"})
u.SetNamespace(namespace)
u.SetName(name)
return u
}
func TestApplySchedulingClass_SetsLabelAnnotationAndSchedulerName(t *testing.T) {
ctx := context.Background()
h := newWebhookTestEnv(t, "tenant-acme", testSchedulingClass, true)
pod := newPod("tenant-acme", "db-0")
if err := h.applySchedulingClass(ctx, pod, nil, "tenant-acme"); err != nil {
t.Fatalf("applySchedulingClass returned error: %v", err)
}
gotLabel := pod.GetLabels()[schedulerapi.SchedulingClassLabel]
if gotLabel != testSchedulingClass {
t.Errorf("expected pod label %s=%s, got %q", schedulerapi.SchedulingClassLabel, testSchedulingClass, gotLabel)
}
gotAnnotation := pod.GetAnnotations()[schedulerapi.SchedulingClassAnnotation]
if gotAnnotation != testSchedulingClass {
t.Errorf("expected pod annotation %s=%s, got %q", schedulerapi.SchedulingClassAnnotation, testSchedulingClass, gotAnnotation)
}
gotSched, _, _ := unstructured.NestedString(pod.Object, "spec", "schedulerName")
if gotSched != schedulerapi.SchedulerName {
t.Errorf("expected pod spec.schedulerName=%s, got %q", schedulerapi.SchedulerName, gotSched)
}
}
func TestApplySchedulingClass_PreservesExistingLabels(t *testing.T) {
ctx := context.Background()
h := newWebhookTestEnv(t, "tenant-acme", testSchedulingClass, true)
pod := newPod("tenant-acme", "db-0")
pod.SetLabels(map[string]string{
"app.kubernetes.io/name": "postgres",
"role": "primary",
})
if err := h.applySchedulingClass(ctx, pod, nil, "tenant-acme"); err != nil {
t.Fatalf("applySchedulingClass returned error: %v", err)
}
labels := pod.GetLabels()
if labels[schedulerapi.SchedulingClassLabel] != testSchedulingClass {
t.Errorf("scheduling-class label not set")
}
if labels["app.kubernetes.io/name"] != "postgres" {
t.Errorf("existing label app.kubernetes.io/name was clobbered: %q", labels["app.kubernetes.io/name"])
}
if labels["role"] != "primary" {
t.Errorf("existing label role was clobbered: %q", labels["role"])
}
}
func TestApplySchedulingClass_NonPodIsNoOp(t *testing.T) {
ctx := context.Background()
h := newWebhookTestEnv(t, "tenant-acme", testSchedulingClass, true)
svc := &unstructured.Unstructured{}
svc.SetGroupVersionKind(schema.GroupVersionKind{Version: "v1", Kind: "Service"})
svc.SetNamespace("tenant-acme")
svc.SetName("svc-0")
if err := h.applySchedulingClass(ctx, svc, nil, "tenant-acme"); err != nil {
t.Fatalf("applySchedulingClass returned error: %v", err)
}
if _, ok := svc.GetLabels()[schedulerapi.SchedulingClassLabel]; ok {
t.Errorf("non-Pod object should not be mutated")
}
if _, ok := svc.GetAnnotations()[schedulerapi.SchedulingClassAnnotation]; ok {
t.Errorf("non-Pod object should not be mutated")
}
}
func TestApplySchedulingClass_NoClassOnNamespaceIsNoOp(t *testing.T) {
ctx := context.Background()
h := newWebhookTestEnv(t, "tenant-acme", "", false)
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 _, ok := pod.GetLabels()[schedulerapi.SchedulingClassLabel]; ok {
t.Errorf("pod label should not be set when namespace has no scheduling-class label")
}
if _, ok := pod.GetAnnotations()[schedulerapi.SchedulingClassAnnotation]; ok {
t.Errorf("pod annotation should not be set when namespace has no scheduling-class label")
}
if sched, _, _ := unstructured.NestedString(pod.Object, "spec", "schedulerName"); sched != "" {
t.Errorf("pod spec.schedulerName should not be set when namespace has no scheduling-class label, got %q", sched)
}
}
func TestApplySchedulingClass_MissingClassCRSkipsInjection(t *testing.T) {
ctx := context.Background()
// Namespace carries the label, but the SchedulingClass CR is NOT created.
h := newWebhookTestEnv(t, "tenant-acme", testSchedulingClass, false)
pod := newPod("tenant-acme", "db-0")
if err := h.applySchedulingClass(ctx, pod, nil, "tenant-acme"); err != nil {
t.Fatalf("applySchedulingClass returned error: %v", err)
}
// Defensive behavior: pod must not be left referencing a non-existent
// scheduler, otherwise it would stay Pending forever.
if _, ok := pod.GetLabels()[schedulerapi.SchedulingClassLabel]; ok {
t.Errorf("pod label should not be set when SchedulingClass CR is missing")
}
if _, ok := pod.GetAnnotations()[schedulerapi.SchedulingClassAnnotation]; ok {
t.Errorf("pod annotation should not be set when SchedulingClass CR is missing")
}
if sched, _, _ := unstructured.NestedString(pod.Object, "spec", "schedulerName"); sched != "" {
t.Errorf("pod spec.schedulerName should not be set when SchedulingClass CR is missing, got %q", sched)
}
}
// newOwnerApplication returns the unstructured Application a Pod's lineage
// walk resolves to, with the given top-level spec.
func newOwnerApplication(namespace, name string, spec map[string]interface{}) *unstructured.Unstructured {
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(schema.GroupVersionKind{Group: "apps.cozystack.io", Version: "v1alpha1", Kind: "Postgres"})
u.SetNamespace(namespace)
u.SetName(name)
if spec != nil {
u.Object["spec"] = spec
}
return u
}
func addSchedulingClassCR(t *testing.T, h *LineageControllerWebhook, name string) {
t.Helper()
if _, err := h.dynClient.Resource(schedulingClassGVR).Create(context.Background(), newSchedulingClassCR(name), metav1.CreateOptions{}); err != nil {
t.Fatalf("creating SchedulingClass %s: %v", name, err)
}
}
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",
})
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 != "app-class" {
t.Errorf("expected pod label %s=app-class, got %q", schedulerapi.SchedulingClassLabel, got)
}
if got := pod.GetAnnotations()[schedulerapi.SchedulingClassAnnotation]; got != "app-class" {
t.Errorf("expected pod annotation %s=app-class, got %q", schedulerapi.SchedulingClassAnnotation, got)
}
}
func TestApplySchedulingClass_OwnerApplicationWithoutClassFallsBackToNamespace(t *testing.T) {
for _, tc := range []struct {
name string
spec map[string]interface{}
}{
{name: "field absent", spec: map[string]interface{}{"replicas": int64(2)}},
{name: "field empty", spec: map[string]interface{}{"schedulingClass": ""}},
{name: "no spec", spec: nil},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
h := newWebhookTestEnv(t, "tenant-acme", testSchedulingClass, true)
pod := newPod("tenant-acme", "db-0")
if err := h.applySchedulingClass(ctx, pod, newOwnerApplication("tenant-acme", "db", tc.spec), "tenant-acme"); err != nil {
t.Fatalf("applySchedulingClass returned error: %v", err)
}
if got := pod.GetLabels()[schedulerapi.SchedulingClassLabel]; got != testSchedulingClass {
t.Errorf("expected the namespace class %q, got %q", testSchedulingClass, got)
}
})
}
}
// A SchedulingClass name may be up to 253 characters, a label value only 63.
// A Pod carrying the longer value would be rejected by the apiserver, so the
// class must still apply through the annotation, without the label.
func TestApplySchedulingClass_ClassNameTooLongForLabelSkipsOnlyLabel(t *testing.T) {
ctx := context.Background()
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")
if err := h.applySchedulingClass(ctx, pod, owner, "tenant-acme"); err != nil {
t.Fatalf("applySchedulingClass returned error: %v", err)
}
if _, ok := pod.GetLabels()[schedulerapi.SchedulingClassLabel]; ok {
t.Errorf("pod label should not be set for a class name longer than 63 characters")
}
if got := pod.GetAnnotations()[schedulerapi.SchedulingClassAnnotation]; got != longClass {
t.Errorf("expected pod annotation %s=%s, got %q", schedulerapi.SchedulingClassAnnotation, longClass, got)
}
if sched, _, _ := unstructured.NestedString(pod.Object, "spec", "schedulerName"); sched != schedulerapi.SchedulerName {
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)
}
}