"""Scheduling preflight regressions. Run on the Debian deployment host.""" import copy import importlib.util import unittest from pathlib import Path SPEC = importlib.util.spec_from_file_location( "scheduling_preflight", Path(__file__).resolve().parents[2] / "scripts/scheduling-preflight.py" ) MODULE = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(MODULE) def node(name="worker-01"): return { "metadata": {"name": name, "labels": {"kubernetes.io/hostname": name, "workload": "platform"}}, "spec": {}, "status": {"allocatable": {"cpu": "1", "memory": "8Gi", "pods": "110"}, "conditions": [{"type": "Ready", "status": "True"}]}, } def pod(name="existing", cpu="900m"): return {"kind": "Pod", "metadata": {"namespace": "monitoring", "name": name}, "spec": {"nodeName": "worker-01", "containers": [ {"name": "main", "resources": {"requests": {"cpu": cpu, "memory": "128Mi"}}} ]}, "status": {"phase": "Running"}} def deployment(unavailable=1): template = copy.deepcopy(pod("desired", "25m")) template["spec"].pop("nodeName") return {"kind": "Deployment", "metadata": {"namespace": "monitoring", "name": "agent"}, "spec": {"replicas": 1, "template": template, "strategy": {"type": "RollingUpdate", "rollingUpdate": { "maxSurge": 1 if unavailable == 0 else 0, "maxUnavailable": unavailable}}}} class SchedulingPreflightTests(unittest.TestCase): def test_encrypted_api_identity_is_refused_without_echoing_ciphertext(self): for field in ("apiVersion", "kind"): with self.subTest(field=field): document = {"apiVersion": "v1", "kind": "Secret", field: "ENC[AES256_GCM,example]"} with self.assertRaises(MODULE.CannotCheck) as raised: MODULE.require_decrypted_manifest(document, "Application gitea-runner") self.assertIn("Application gitea-runner", str(raised.exception)) self.assertIn("encrypted SOPS document", str(raised.exception)) self.assertNotIn("AES256_GCM", str(raised.exception)) def test_sops_secret_is_refused_even_with_plaintext_kind(self): document = {"apiVersion": "v1", "kind": "Secret", "sops": {"version": "3.9.0"}} with self.assertRaisesRegex(MODULE.CannotCheck, "encrypted SOPS document"): MODULE.require_decrypted_manifest(document, "Application example") def test_rendered_plaintext_resource_is_allowed(self): MODULE.require_decrypted_manifest({"apiVersion": "apps/v1", "kind": "Deployment"}, "Application example") def test_one_core_node_can_fit_small_request(self): estimate = MODULE.Estimate([node()], [pod(cpu="875m")], [], [], []) incoming = pod("agent", "125m") incoming["spec"].pop("nodeName") estimate.place(incoming) self.assertEqual(estimate.pods[-1]["spec"]["nodeName"], "worker-01") def test_requests_not_usage_block_a_full_node(self): estimate = MODULE.Estimate([node()], [pod(cpu="1")], [], [], []) with self.assertRaisesRegex(MODULE.CannotCheck, "needs 125.0m, free 0.0m"): estimate.place(pod("agent", "125m")) def test_init_sidecars_and_overhead_are_included(self): spec = {"containers": [{"resources": {"requests": {"cpu": "100m"}}}], "initContainers": [ {"restartPolicy": "Always", "resources": {"requests": {"cpu": "50m"}}}, {"resources": {"requests": {"cpu": "400m"}}}], "overhead": {"cpu": "10m"}} self.assertEqual(MODULE.pod_requests(spec)["cpu"], MODULE.quantity("460m")) def test_bound_local_pv_prevents_using_other_node_capacity(self): pvc = {"metadata": {"namespace": "monitoring", "name": "data"}, "spec": {"volumeName": "local"}} pv = {"metadata": {"name": "local"}, "spec": {"nodeAffinity": {"required": {"nodeSelectorTerms": [ {"matchExpressions": [{"key": "kubernetes.io/hostname", "operator": "In", "values": ["worker-01"]}]}]}}}} estimate = MODULE.Estimate([node(), node("worker-02")], [pod(cpu="1")], [], [pvc], [pv]) incoming = pod("grafana", "100m") incoming["spec"].pop("nodeName") incoming["spec"]["volumes"] = [{"name": "data", "persistentVolumeClaim": {"claimName": "data"}}] with self.assertRaisesRegex(MODULE.CannotCheck, "PVC data node affinity mismatch"): estimate.place(incoming) def test_selector_and_taints_are_enforced(self): candidate = node() candidate["spec"]["taints"] = [{"key": "dedicated", "value": "control", "effect": "NoSchedule"}] estimate = MODULE.Estimate([candidate], [], [], [], []) incoming = pod("agent", "25m") incoming["spec"]["nodeSelector"] = {"workload": "apps"} reasons = estimate.reasons(incoming, candidate) self.assertIn("nodeSelector mismatch", reasons) self.assertIn("untolerated taint dedicated", reasons) def test_zero_surge_can_rightsize_a_full_node(self): old = pod("old", "100m") old["metadata"]["ownerReferences"] = [{"kind": "ReplicaSet", "name": "agent-old", "controller": True}] replica_set = {"kind": "ReplicaSet", "metadata": {"namespace": "monitoring", "name": "agent-old", "ownerReferences": [{"kind": "Deployment", "name": "agent", "controller": True}]}} estimate = MODULE.Estimate([node()], [pod(cpu="900m"), old], [replica_set], [], []) estimate.workload(deployment()) self.assertEqual(sum(MODULE.pod_requests(p["spec"])["cpu"] for p in estimate.pods), MODULE.quantity("925m")) def test_surge_requires_capacity_before_removing_old_pod(self): old = pod("old", "100m") old["metadata"]["ownerReferences"] = [{"kind": "Deployment", "name": "agent", "controller": True}] estimate = MODULE.Estimate([node()], [pod(cpu="900m"), old], [], [], []) with self.assertRaisesRegex(MODULE.CannotCheck, "cannot fit"): estimate.workload(deployment(unavailable=0)) def test_empty_required_affinity_term_matches_nothing(self): self.assertFalse(MODULE.affinity_matches({"nodeSelectorTerms": [{}]}, node())) def test_known_false_nested_plan_values_are_not_unknown(self): self.assertFalse(MODULE.contains_unknown([False, {"resources": False}])) self.assertTrue(MODULE.contains_unknown([False, {"resources": True}])) def test_terminal_pods_do_not_reserve_capacity(self): old = pod(cpu="1") old["status"]["phase"] = "Failed" estimate = MODULE.Estimate([node()], [old], [], [], []) estimate.place(pod("new", "125m")) self.assertEqual(len(estimate.pods), 1) def test_required_anti_affinity_blocks_same_node(self): existing = pod() existing["metadata"]["labels"] = {"app": "agent"} incoming = pod("new", "25m") incoming["spec"]["affinity"] = {"podAntiAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": [ {"topologyKey": "kubernetes.io/hostname", "labelSelector": {"matchLabels": {"app": "agent"}}} ]}} estimate = MODULE.Estimate([node()], [existing], [], [], []) with self.assertRaisesRegex(MODULE.CannotCheck, "required pod anti-affinity"): estimate.place(incoming) def test_host_port_collision_is_not_free_capacity(self): existing = pod() existing["spec"]["containers"][0]["ports"] = [{"hostPort": 9100, "containerPort": 9100}] incoming = pod("new", "25m") incoming["spec"]["containers"][0]["ports"] = [{"hostPort": 9100, "containerPort": 9100}] estimate = MODULE.Estimate([node()], [existing], [], [], []) with self.assertRaisesRegex(MODULE.CannotCheck, "host port TCP/9100"): estimate.place(incoming) def test_memory_limits_supply_missing_requests(self): request = MODULE.container_requests({"resources": {"limits": {"memory": "1Gi"}}}) self.assertEqual(request["memory"], MODULE.quantity("1Gi")) def test_terminating_pod_does_not_release_cpu_early(self): old = pod(cpu="1") old["metadata"]["deletionTimestamp"] = "2026-10-30T10:00:00Z" estimate = MODULE.Estimate([node()], [old], [], [], []) with self.assertRaisesRegex(MODULE.CannotCheck, "cannot fit"): estimate.place(pod("new", "25m")) if __name__ == "__main__": unittest.main()