#!/usr/bin/env python3 """Read-only, conservative scheduling/rollout estimate for a selected Tofu plan. This is not kube-scheduler: admission mutation, preemption, storage provisioning, and operator reconciliation require live readiness checks after deployment. """ import argparse import copy import json import math import re import subprocess import sys import tempfile from collections import Counter from decimal import Decimal from pathlib import Path from urllib.parse import urlparse try: import yaml except ImportError: print("Scheduling preflight requires python3-yaml on the deployment host.", file=sys.stderr) sys.exit(1) class CannotCheck(RuntimeError): pass def run(command, timeout=60): result = subprocess.run(command, capture_output=True, text=True, timeout=timeout, check=False) if result.returncode: # Helm errors can contain rendered secrets. Do not echo command output. raise CannotCheck(f"{command[0]} {command[1]} failed (exit {result.returncode}); no deployment performed") return result.stdout def quantity(value): match = re.fullmatch(r"([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)([a-zA-Z]*)", str(value)) if not match: raise CannotCheck(f"Unsupported resource quantity: {value}") factors = {"": 1, "n": Decimal("1e-9"), "u": Decimal("1e-6"), "m": Decimal("1e-3")} factors.update({s: 1000**i for i, s in enumerate("kMGTPE", 1)}) factors["K"] = 1000 factors.update({s + "i": 1024**i for i, s in enumerate("KMGTPE", 1)}) if match[2] not in factors: raise CannotCheck(f"Unsupported quantity suffix: {match[2]}") return Decimal(match[1]) * factors[match[2]] def container_requests(container): resources = container.get("resources") or {} limits = resources.get("limits") or {} requests = dict(resources.get("requests") or {}) for name, value in limits.items(): requests.setdefault(name, value) return Counter({name: quantity(value) for name, value in requests.items()}) def pod_requests(spec): app = Counter() sidecars = Counter() peak = Counter() for container in spec.get("containers") or []: app.update(container_requests(container)) for container in spec.get("initContainers") or []: request = container_requests(container) if container.get("restartPolicy") == "Always": sidecars.update(request) request = sidecars.copy() else: request.update(sidecars) for resource in request: peak[resource] = max(peak[resource], request[resource]) app.update(sidecars) for resource in peak: app[resource] = max(app[resource], peak[resource]) for resource, value in container_requests(spec).items(): app[resource] = max(app[resource], value) app.update({name: quantity(value) for name, value in (spec.get("overhead") or {}).items()}) app["pods"] = 1 return app def expression_matches(expression, labels): key, operator = expression["key"], expression["operator"] values = expression.get("values") or [] present = key in labels value = labels.get(key) if operator == "In": return present and value in values if operator == "NotIn": return not present or value not in values if operator == "Exists": return present if operator == "DoesNotExist": return not present if operator in ("Gt", "Lt"): try: return present and (int(value) > int(values[0]) if operator == "Gt" else int(value) < int(values[0])) except (ValueError, IndexError): return False raise CannotCheck(f"Unsupported selector operator: {operator}") def selector_matches(selector, labels): selector = selector or {} if selector is None: return False return all(labels.get(k) == v for k, v in selector.get("matchLabels", {}).items()) and all( expression_matches(e, labels) for e in selector.get("matchExpressions", []) ) def affinity_matches(affinity, node): terms = affinity.get("nodeSelectorTerms", []) fields = {"metadata.name": node["metadata"]["name"]} return any( bool(term.get("matchExpressions") or term.get("matchFields")) and all(expression_matches(e, node["metadata"].get("labels", {})) for e in term.get("matchExpressions", [])) and all(expression_matches(e, fields) for e in term.get("matchFields", [])) for term in terms ) def tolerates(taint, tolerations): return any( (not t.get("effect") or t["effect"] == taint["effect"]) and ((t.get("operator") == "Exists" and (not t.get("key") or t["key"] == taint["key"])) or (t.get("operator", "Equal") == "Equal" and t.get("key") == taint["key"] and t.get("value", "") == taint.get("value", ""))) for t in tolerations ) def limit(value, replicas, round_up=False): if isinstance(value, str) and value.endswith("%"): raw = replicas * int(value[:-1]) / 100 return math.ceil(raw) if round_up else math.floor(raw) return int(value) def identity(item): return item["kind"], item["metadata"].get("namespace", "default"), item["metadata"]["name"] def contains_unknown(value): if isinstance(value, dict): return any(contains_unknown(v) for v in value.values()) if isinstance(value, list): return any(contains_unknown(v) for v in value) return value is True def repository_identity(url): if "://" in url: parsed = urlparse(url) return (parsed.hostname or "").lower(), parsed.path.strip("/").removesuffix(".git") match = re.fullmatch(r"(?:[^@/]+@)?([^:/]+):(.+)", url) if match: return match[1].lower(), match[2].strip("/").removesuffix(".git") return "", str(Path(url).resolve()) class Estimate: def __init__(self, nodes, pods, controllers, pvcs, pvs, storage_classes=(), namespaces=()): self.nodes = {n["metadata"]["name"]: n for n in nodes} self.pods = [p for p in pods if p.get("status", {}).get("phase") not in ("Succeeded", "Failed")] self.controllers = {identity(c): c for c in controllers} self.pvcs = {(p["metadata"]["namespace"], p["metadata"]["name"]): p for p in pvcs} self.pvs = {p["metadata"]["name"]: p for p in pvs} self.storage_classes = {s["metadata"]["name"]: s for s in storage_classes} self.namespaces = {n["metadata"]["name"]: n["metadata"].get("labels", {}) for n in namespaces} self.notices = set() def notice(self, message): if message not in self.notices: print(f" NOTICE {message}") self.notices.add(message) def peer_matches(self, term, incoming, peer): namespace = incoming["metadata"].get("namespace", "default") peer_namespace = peer["metadata"].get("namespace", "default") namespaces = term.get("namespaces", []) selector = term.get("namespaceSelector") if not namespaces and selector is None: namespaces = [namespace] if peer_namespace not in namespaces and (selector is None or not selector_matches(selector, self.namespaces.get(peer_namespace, {}))): return False labels = peer["metadata"].get("labels", {}) source_labels = incoming["metadata"].get("labels", {}) if not selector_matches(term.get("labelSelector"), labels): return False for key in term.get("matchLabelKeys", []): if key in source_labels and labels.get(key) != source_labels[key]: return False for key in term.get("mismatchLabelKeys", []): if key in source_labels and labels.get(key) == source_labels[key]: return False return True def topology_reasons(self, pod, node): reasons = [] labels = node["metadata"].get("labels", {}) affinity = pod["spec"].get("affinity", {}) for field in ("podAffinity", "podAntiAffinity"): for term in (affinity.get(field) or {}).get("requiredDuringSchedulingIgnoredDuringExecution") or []: key = term["topologyKey"] peers = [p for p in self.pods if p["spec"].get("nodeName") in self.nodes and self.peer_matches(term, pod, p)] same_domain = any(self.nodes[p["spec"]["nodeName"]]["metadata"].get("labels", {}).get(key) == labels.get(key) for p in peers) if key not in labels: reasons.append(f"missing topology key {key}") elif field == "podAntiAffinity" and same_domain: reasons.append(f"required pod anti-affinity on {key}") elif field == "podAffinity" and not same_domain and (peers or not self.peer_matches(term, pod, pod)): reasons.append(f"required pod affinity on {key}") # Existing Pods' required anti-affinity also constrains incoming Pods. for peer in self.pods: peer_node = self.nodes.get(peer["spec"].get("nodeName")) if not peer_node: continue for term in (((peer["spec"].get("affinity") or {}).get("podAntiAffinity") or {}).get("requiredDuringSchedulingIgnoredDuringExecution") or []): key = term["topologyKey"] if key in labels and peer_node["metadata"].get("labels", {}).get(key) == labels[key] and self.peer_matches(term, peer, pod): reasons.append(f"existing pod required anti-affinity on {key}") for constraint in pod["spec"].get("topologySpreadConstraints") or []: if constraint.get("whenUnsatisfiable") != "DoNotSchedule": continue key = constraint["topologyKey"] domains = set() for candidate in self.nodes.values(): candidate_labels = candidate["metadata"].get("labels", {}) if key not in candidate_labels: continue if constraint.get("nodeAffinityPolicy", "Honor") == "Honor": if any(candidate_labels.get(k) != v for k, v in pod["spec"].get("nodeSelector", {}).items()): continue required = affinity.get("nodeAffinity", {}).get("requiredDuringSchedulingIgnoredDuringExecution") if required is not None and not affinity_matches(required, candidate): continue if constraint.get("nodeTaintsPolicy", "Ignore") == "Honor" and any( t["effect"] in ("NoSchedule", "NoExecute") and not tolerates(t, pod["spec"].get("tolerations", [])) for t in candidate.get("spec", {}).get("taints", []) ): continue domains.add(candidate_labels[key]) counts = Counter({domain: 0 for domain in domains}) term = {"labelSelector": constraint.get("labelSelector", {}), "matchLabelKeys": constraint.get("matchLabelKeys", [])} for peer in self.pods: peer_node = self.nodes.get(peer["spec"].get("nodeName")) if peer_node and self.peer_matches(term, pod, peer): domain = peer_node["metadata"].get("labels", {}).get(key) if domain in domains: counts[domain] += 1 minimum = min(counts.values(), default=0) if len(domains) >= constraint.get("minDomains", 1) else 0 increment = int(self.peer_matches(term, pod, pod)) if key not in labels or counts[labels.get(key)] + increment - minimum > constraint["maxSkew"]: reasons.append(f"hard topology spread on {key}") return reasons def owner(self, pod): namespace = pod["metadata"].get("namespace", "default") ref = next((r for r in pod["metadata"].get("ownerReferences", []) if r.get("controller")), None) if not ref: return identity(pod) key = ref["kind"], namespace, ref["name"] controller = self.controllers.get(key) if ref["kind"] == "ReplicaSet" and controller: parent = next((r for r in controller["metadata"].get("ownerReferences", []) if r.get("controller")), None) if parent: key = parent["kind"], namespace, parent["name"] return key def reasons(self, pod, node, required_node=None): spec = pod["spec"] name = node["metadata"]["name"] labels = node["metadata"].get("labels", {}) reasons = [] if required_node and required_node != name: return ["DaemonSet targets another node"] if spec.get("nodeName") and spec["nodeName"] != name: reasons.append("nodeName mismatch") if node.get("spec", {}).get("unschedulable"): reasons.append("cordoned") if not any(c["type"] == "Ready" and c["status"] == "True" for c in node.get("status", {}).get("conditions", [])): reasons.append("NotReady") if any(labels.get(k) != v for k, v in spec.get("nodeSelector", {}).items()): reasons.append("nodeSelector mismatch") affinity = spec.get("affinity", {}) required = affinity.get("nodeAffinity", {}).get("requiredDuringSchedulingIgnoredDuringExecution") if required is not None and not affinity_matches(required, node): reasons.append("required node affinity mismatch") for taint in node.get("spec", {}).get("taints", []): if taint["effect"] in ("NoSchedule", "NoExecute") and not tolerates(taint, spec.get("tolerations", [])): reasons.append(f"untolerated taint {taint['key']}") namespace = pod["metadata"].get("namespace", "default") for volume in spec.get("volumes") or []: claim = volume.get("persistentVolumeClaim", {}).get("claimName") if not claim: continue pvc = self.pvcs.get((namespace, claim)) if pvc is None: raise CannotCheck(f"{namespace}/{claim}: PVC absent and no claim template was rendered") if not pvc.get("spec", {}).get("volumeName"): class_name = pvc.get("spec", {}).get("storageClassName") storage_class = self.storage_classes.get(class_name) if class_name is None: defaults = [s for s in self.storage_classes.values() if s["metadata"].get("annotations", {}).get("storageclass.kubernetes.io/is-default-class") == "true"] storage_class = defaults[0] if len(defaults) == 1 else None if not storage_class or storage_class.get("provisioner") == "kubernetes.io/no-provisioner": raise CannotCheck(f"{namespace}/{claim}: unbound claim has no known dynamic provisioner") selected_node = pvc["metadata"].get("annotations", {}).get("volume.kubernetes.io/selected-node") if selected_node and selected_node != name: reasons.append(f"PVC {claim} selected another node") terms = storage_class.get("allowedTopologies", []) if terms and not any(all(expression_matches(dict(e, operator="In"), labels) for e in term.get("matchLabelExpressions", [])) for term in terms): reasons.append(f"PVC {claim} storage topology mismatch") self.notice(f"{namespace}/{claim}: dynamic provisioning/storage capacity is not proven by this estimate") continue pv = self.pvs.get(pvc["spec"]["volumeName"]) if pv is None: raise CannotCheck(f"{namespace}/{claim}: bound PV could not be read") required = pv.get("spec", {}).get("nodeAffinity", {}).get("required") if required is not None and not affinity_matches(required, node): reasons.append(f"PVC {claim} node affinity mismatch") modes = pvc.get("spec", {}).get("accessModes", []) for peer in self.pods: if peer["metadata"].get("namespace", "default") != namespace or not peer["spec"].get("nodeName"): continue uses_claim = any(v.get("persistentVolumeClaim", {}).get("claimName") == claim for v in peer["spec"].get("volumes", [])) if uses_claim and ("ReadWriteOncePod" in modes or ("ReadWriteOnce" in modes and peer["spec"]["nodeName"] != name)): reasons.append(f"PVC {claim} is still in use by {peer['metadata']['name']}") if spec.get("schedulingGates") or spec.get("resourceClaims") or spec.get("schedulerName", "default-scheduler") != "default-scheduler": raise CannotCheck("Scheduling gates, dynamic claims, or custom schedulers require separate evaluation") return reasons @staticmethod def host_ports(spec): return [ (p.get("hostIP", "0.0.0.0"), p.get("protocol", "TCP"), p.get("hostPort") or p.get("containerPort")) for c in (spec.get("containers") or []) + (spec.get("initContainers") or []) for p in c.get("ports") or [] if p.get("hostPort") or spec.get("hostNetwork") ] def place(self, pod, required_node=None): request = pod_requests(pod["spec"]) used = {name: Counter() for name in self.nodes} for current in self.pods: name = current["spec"].get("nodeName") if name in used: used[name].update(pod_requests(current["spec"])) errors = [] for name, node in self.nodes.items(): reasons = self.reasons(pod, node, required_node) reasons.extend(self.topology_reasons(pod, node)) for peer in self.pods: if peer["spec"].get("nodeName") != name: continue for address, protocol, port in self.host_ports(pod["spec"]): if any(proto == protocol and number == port and ( address == host or address in ("0.0.0.0", "::") or host in ("0.0.0.0", "::") ) for host, proto, number in self.host_ports(peer["spec"])): reasons.append(f"host port {protocol}/{port} is reserved") allocatable = node.get("status", {}).get("allocatable", {}) for resource, amount in request.items(): free = quantity(allocatable.get(resource, 0)) - used[name][resource] if free < amount: unit = 1000 if resource == "cpu" else 1 / (1024 * 1024) if resource == "memory" else 1 suffix = "m" if resource == "cpu" else "Mi" if resource == "memory" else "" reasons.append(f"{resource}: needs {float(amount) * unit:.1f}{suffix}, free {float(free) * unit:.1f}{suffix}") if not reasons: placed = copy.deepcopy(pod) placed["spec"]["nodeName"] = name self.pods.append(placed) return errors.append(f" {name}: {'; '.join(reasons)}") raise CannotCheck(f"{pod['metadata']['namespace']}/{pod['metadata']['name']} cannot fit:\n" + "\n".join(errors)) def workload(self, item): kind, namespace, name = identity(item) spec = item["spec"] template = item if kind == "Pod" else spec["template"] pod = {"kind": "Pod", "metadata": dict(template.get("metadata", {}), namespace=namespace), "spec": copy.deepcopy(template["spec"])} # Live admission defaults/sidecars cannot be inferred from chart YAML. if pod["spec"].get("runtimeClassName") and "overhead" not in pod["spec"]: raise CannotCheck(f"{namespace}/{name}: RuntimeClass overhead is not present in rendered template") old = [p for p in self.pods if self.owner(p) == (kind, namespace, name)] live = self.controllers.get((kind, namespace, name), {}) desired = spec.get("replicas", 1) status = live.get("status", {}) stable = status.get("observedGeneration", 0) >= live.get("metadata", {}).get("generation", 1) stable = stable and status.get("readyReplicas", 0) >= desired and status.get("updatedReplicas", 0) >= desired if kind == "StatefulSet": stable = stable and status.get("currentRevision") == status.get("updateRevision") if item.get("_preflight_noop") and kind != "DaemonSet" and stable and len(old) == desired: print(f" UNCHANGED {kind} {namespace}/{name}: existing replicas ready") return replicas = spec.get("replicas", 1) targets = [None] * replicas if kind == "DaemonSet": # DaemonSet controller supplies these tolerations when creating pods. pod["spec"].setdefault("tolerations", []).extend([ {"key": key, "operator": "Exists", "effect": effect} for key, effect in [ ("node.kubernetes.io/not-ready", "NoExecute"), ("node.kubernetes.io/unreachable", "NoExecute"), ("node.kubernetes.io/disk-pressure", "NoSchedule"), ("node.kubernetes.io/memory-pressure", "NoSchedule"), ("node.kubernetes.io/pid-pressure", "NoSchedule"), ("node.kubernetes.io/unschedulable", "NoSchedule"), ] ]) targets = [] for node_name, node in self.nodes.items(): if not self.reasons(pod, node): targets.append(node_name) if not targets: raise CannotCheck(f"{namespace}/{name}: DaemonSet has no eligible Ready nodes") replicas = len(targets) if kind == "StatefulSet": update = spec.get("updateStrategy", {}) if update.get("type") == "OnDelete" or update.get("rollingUpdate", {}).get("partition", 0): raise CannotCheck(f"{namespace}/{name}: manual/partitioned StatefulSet rollout requires review") strategy = spec.get("strategy", {}) rolling = strategy.get("rollingUpdate", {}) delete_first = kind in ("StatefulSet", "DaemonSet") or strategy.get("type") == "Recreate" or limit(rolling.get("maxUnavailable", "25%"), replicas) > 0 if kind == "DaemonSet": strategy = spec.get("updateStrategy", {}) if strategy.get("type") == "OnDelete": raise CannotCheck(f"{namespace}/{name}: manual DaemonSet rollout requires review") rolling = strategy.get("rollingUpdate", {}) delete_first = limit(rolling.get("maxUnavailable", 1), replicas, True) > 0 if not delete_first and not limit(rolling.get("maxSurge", 0), replicas, True): raise CannotCheck(f"{namespace}/{name}: DaemonSet rollout permits neither surge nor unavailability") if strategy.get("type") == "Recreate": for previous in old: if previous["metadata"].get("deletionTimestamp"): raise CannotCheck(f"{namespace}/{name}: old pod is still terminating") self.pods.remove(previous) old = [] if kind == "Deployment" and not delete_first and not limit(rolling.get("maxSurge", "25%"), replicas, True): raise CannotCheck(f"{namespace}/{name}: rollout permits neither surge nor unavailability") for ordinal, target in enumerate(targets): pod["metadata"]["name"] = f"{name}-{ordinal}" if kind == "StatefulSet" else f"{name}-preflight-{ordinal}" pod["spec"]["volumes"] = copy.deepcopy(template["spec"].get("volumes", [])) for claim in spec.get("volumeClaimTemplates", []): claim_name = claim["metadata"]["name"] full_name = f"{claim_name}-{name}-{ordinal}" self.pvcs.setdefault((namespace, full_name), {"metadata": {"namespace": namespace, "name": full_name}, "spec": claim["spec"]}) pod["spec"]["volumes"] = [v for v in pod["spec"]["volumes"] if v["name"] != claim_name] pod["spec"]["volumes"].append({"name": claim_name, "persistentVolumeClaim": {"claimName": full_name}}) previous = next((p for p in old if (kind != "StatefulSet" or p["metadata"]["name"] == f"{name}-{ordinal}") and (target is None or p["spec"].get("nodeName") == target)), None) if previous and previous["metadata"].get("deletionTimestamp"): raise CannotCheck(f"{namespace}/{name}: old pod is still terminating; retry after its reservations clear") if previous and delete_first: self.pods.remove(previous) self.place(pod, target) if previous: if not delete_first: self.pods.remove(previous) old.remove(previous) for previous in old: self.pods.remove(previous) print(f" FIT {kind} {namespace}/{name}: {replicas} replica(s), {'replacement' if delete_first else 'surge'} budget") def manifests_from_plan(args, plan, kubectl): documents = [] version = json.loads(run(kubectl + ["version", "-o", "json"]))["serverVersion"]["gitVersion"] api_versions = run(kubectl + ["api-versions"]).splitlines() for resource in plan.get("resource_changes", []): change = resource["change"] if change.get("after") is None or change.get("actions") == ["delete"]: continue value = change["after"] resource_type = resource["type"] if resource.get("mode", "managed") != "managed": continue if resource_type == "helm_release": if value.get("set") or value.get("set_sensitive") or value.get("set_list") or value.get("reuse_values"): raise CannotCheck(f"{resource['address']}: Helm set/reuse overrides are not supported by the preflight") if not all(value.get(key) for key in ("name", "chart", "version", "namespace", "repository")): raise CannotCheck(f"{resource['address']}: chart identity/version is unknown; pin the chart before deployment") print(f" Rendering Helm release {value['namespace']}/{value['name']} at {value['version']}...", flush=True) unknown = change.get("after_unknown", {}) if any(contains_unknown(unknown.get(key)) for key in ("values", "set", "set_sensitive", "set_list")): raise CannotCheck(f"{resource['address']}: planned Helm overrides are unknown") with tempfile.TemporaryDirectory(prefix="jeannie-scheduling-") as directory: command = ["helm", "template", value["name"], value["chart"], "--repo", value["repository"], "--version", value["version"], "--namespace", value["namespace"], "--kube-version", version, "--skip-tests"] if change.get("before"): command.append("--is-upgrade") for api in api_versions: command.extend(["--api-versions", api]) for index, content in enumerate(value.get("values") or []): if content is None: raise CannotCheck(f"{resource['address']}: planned Helm values are unknown") path = Path(directory) / f"values-{index}.yaml" path.write_text(content) path.chmod(0o600) command.extend(["--values", str(path)]) rendered = list(yaml.safe_load_all(run(command, timeout=180))) for item in rendered or []: if item: metadata = item.setdefault("metadata", {}) metadata["namespace"] = metadata.get("namespace") or value["namespace"] item["_preflight_noop"] = change.get("actions") == ["no-op"] documents.append(item) elif resource_type == "kubernetes_manifest": item = value.get("manifest") if not item: raise CannotCheck(f"{resource['address']}: planned manifest is unknown") if item.get("kind") == "Application": source = item.get("spec", {}).get("source") or {} if not source.get("path") or any(source.get(key) for key in ("helm", "plugin", "directory")): raise CannotCheck(f"{item['metadata']['name']}: only local Kustomize/plain-manifest Application sources are supported") if set(source.get("kustomize") or {}) - {"images"}: raise CannotCheck(f"{item['metadata']['name']}: Argo-specific Kustomize placement overrides require separate rendering") path = (Path(args.repo_root) / source["path"]).resolve() if not path.is_relative_to(Path(args.repo_root).resolve()): raise CannotCheck("Application path escapes repository") if not path.is_dir(): raise CannotCheck(f"{item['metadata']['name']}: Application source directory is absent") live_text = run(kubectl + ["-n", item["metadata"].get("namespace", "argocd"), "get", "application", item["metadata"]["name"], "--ignore-not-found", "-o", "json"]) live_application = json.loads(live_text) if live_text.strip() else {} sync = live_application.get("status", {}).get("sync", {}) checkout_revision = run(["git", "-C", args.repo_root, "rev-parse", "HEAD"]).strip() remotes = run(["git", "-C", args.repo_root, "remote", "-v"]).splitlines() remote_ids = {repository_identity(line.split()[1]) for line in remotes if len(line.split()) >= 2} if repository_identity(source["repoURL"]) not in remote_ids: raise CannotCheck(f"{item['metadata']['name']}: Application repository does not match a local Git remote") target = run(["git", "-C", args.repo_root, "rev-parse", "--verify", "--end-of-options", source.get("targetRevision", "HEAD") + "^{commit}"]).strip() if target != checkout_revision: raise CannotCheck(f"{item['metadata']['name']}: checkout does not match the configured Application revision") dirty = run(["git", "-C", args.repo_root, "status", "--porcelain", "--", source["path"]]).strip() if dirty: raise CannotCheck(f"{item['metadata']['name']}: commit Application source changes before checking the GitOps deployment revision") # A no-op Application CR does not mean its Git workloads are # unchanged. Only trust it when Argo has synced this checkout. already_synced = change.get("actions") == ["no-op"] and not dirty and sync.get("status") == "Synced" and sync.get("revision") == checkout_revision if any((path / name).exists() for name in ("kustomization.yaml", "kustomization.yml", "Kustomization")): rendered = list(yaml.safe_load_all(run(kubectl + ["kustomize", str(path)]))) else: rendered = [] for manifest in sorted(path.iterdir()): if manifest.is_file() and manifest.suffix in (".yaml", ".yml", ".json"): rendered.extend(yaml.safe_load_all(manifest.read_text())) for app_item in rendered or []: if app_item: metadata = app_item.setdefault("metadata", {}) metadata["namespace"] = metadata.get("namespace") or item["spec"]["destination"]["namespace"] app_item["_preflight_noop"] = already_synced documents.append(app_item) else: documents.append(item) return documents def operator_workload(document, controllers): """Preserve the Operator's existing sidecars and volume claims on upgrades. First installs cannot be predicted without the operator's Pod defaults. Refuse those rather than claiming that an unrendered Pod fits. """ kind, namespace, name = identity(document) stateful_name = ("prometheus-" if kind == "Prometheus" else "alertmanager-") + name live = controllers.get(("StatefulSet", namespace, stateful_name)) if not live: raise CannotCheck(f"{kind} {namespace}/{name}: operator Pod template is not available yet; bootstrap the operator workload separately before checking its scheduling") result = copy.deepcopy(live) spec = document["spec"] result["spec"]["replicas"] = spec.get("replicas", 1) result["_preflight_noop"] = document.get("_preflight_noop", False) pod = result["spec"]["template"]["spec"] for field in ("nodeSelector", "affinity", "tolerations", "topologySpreadConstraints", "priorityClassName"): if field in spec: pod[field] = copy.deepcopy(spec[field]) primary = "prometheus" if kind == "Prometheus" else "alertmanager" for container in pod["containers"]: if container["name"] == primary and "resources" in spec: container["resources"] = copy.deepcopy(spec["resources"]) for override in spec.get("containers", []): existing = next((c for c in pod["containers"] if c["name"] == override["name"]), None) if existing is None: pod["containers"].append(copy.deepcopy(override)) elif "resources" in override: existing["resources"] = copy.deepcopy(override["resources"]) print(f" NOTICE {kind}/{name}: estimating with the live Operator sidecars and PVCs") return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--plan", required=True, help="OpenTofu show -json output (may contain secrets)") parser.add_argument("--kubeconfig", required=True) parser.add_argument("--repo-root", required=True) parser.add_argument("--expected-node", required=True) args = parser.parse_args() kubectl = ["kubectl", "--kubeconfig", args.kubeconfig, "--request-timeout=15s"] nodes = json.loads(run(kubectl + ["get", "nodes", "-o", "json"]))["items"] if args.expected_node not in {n["metadata"]["name"] for n in nodes}: raise CannotCheck(f"Expected control plane {args.expected_node} is absent; refusing to check a different cluster") objects = json.loads(run(kubectl + ["get", "pods,deployments,replicasets,statefulsets,daemonsets,persistentvolumeclaims", "-A", "-o", "json"]))["items"] pvs = json.loads(run(kubectl + ["get", "pv", "-o", "json"]))["items"] storage_classes = json.loads(run(kubectl + ["get", "storageclasses", "-o", "json"]))["items"] namespaces = json.loads(run(kubectl + ["get", "namespaces", "-o", "json"]))["items"] with open(args.plan, encoding="utf-8") as handle: documents = manifests_from_plan(args, json.load(handle), kubectl) engine = Estimate(nodes, [p for p in objects if p["kind"] == "Pod"], objects, [p for p in objects if p["kind"] == "PersistentVolumeClaim"], pvs, storage_classes, namespaces) for item in documents: if item["kind"] == "PersistentVolumeClaim": key = item["metadata"]["namespace"], item["metadata"]["name"] engine.pvcs.setdefault(key, item) elif item["kind"] == "StorageClass": engine.storage_classes[item["metadata"]["name"]] = item workloads = {identity(d): d for d in documents if d["kind"] in ("Deployment", "StatefulSet", "DaemonSet", "Pod")} for document in documents: if document["kind"] in ("Prometheus", "Alertmanager"): item = operator_workload(document, engine.controllers) workloads[identity(item)] = item elif document["kind"] == "Installation": print(f" NOTICE {document['kind']}/{document['metadata']['name']}: operator-generated pods require post-apply readiness checks") # Reductions first makes headroom available before increases. This is a # feasible sequence estimate, not a promise about controller execution order. def delta(item): template = item if item["kind"] == "Pod" else item["spec"]["template"] # Use an upper bound for DaemonSets here; workload() resolves their # actual eligible nodes. Counting only one Pod misorders additions. replicas = len(engine.nodes) if item["kind"] == "DaemonSet" else item["spec"].get("replicas", 1) desired = pod_requests(template["spec"])["cpu"] * replicas current = sum(pod_requests(p["spec"])["cpu"] for p in engine.pods if engine.owner(p) == identity(item)) return desired - current print(f"Scheduling preflight: {len(workloads)} rendered workload(s); using allocatable resources and reservations, not CPU usage") for name, node in engine.nodes.items(): reserved = Counter() for pod in engine.pods: if pod["spec"].get("nodeName") == name: reserved.update(pod_requests(pod["spec"])) allocatable = node["status"]["allocatable"] cpu = quantity(allocatable.get("cpu", 0)) memory = quantity(allocatable.get("memory", 0)) print(f" {name}: CPU reserved={reserved['cpu'] * 1000:.0f}m/{cpu * 1000:.0f}m; " f"memory reserved={reserved['memory'] / (1024 * 1024):.0f}Mi/{memory / (1024 * 1024):.0f}Mi") failures = {} pending = sorted(workloads.values(), key=delta) while pending: deferred = [] progress = False for item in pending: before = copy.deepcopy(engine.pods) try: engine.workload(item) failures.pop(identity(item), None) progress = True except CannotCheck as exc: engine.pods = before failures[identity(item)] = str(exc) deferred.append(item) if not progress: break pending = deferred if failures: raise CannotCheck("\n".join(failures.values())) print("Scheduling estimate passed for rendered workloads; admission, operators and live readiness remain authoritative.") if __name__ == "__main__": try: main() except yaml.YAMLError: print("Scheduling preflight blocked deployment: invalid YAML in a chart or manifest (contents withheld).", file=sys.stderr) sys.exit(1) except subprocess.TimeoutExpired as error: print(f"Scheduling preflight blocked deployment: {error.cmd[0]} {error.cmd[1]} timed out.", file=sys.stderr) sys.exit(1) except (CannotCheck, OSError, ValueError, KeyError, TypeError) as error: print(f"Scheduling preflight blocked deployment: {error}", file=sys.stderr) sys.exit(1)