Check workload scheduling and rollout capacity before Kubernetes applies
This commit is contained in:
parent
8938cb3511
commit
7b59ef0ce4
|
|
@ -56,6 +56,71 @@ ApplicationSet controller may be briefly unavailable during its update.
|
||||||
Apply with `LAB_CLUSTER_PROFILE=pimox ./jeannie platform argocd`; the readiness
|
Apply with `LAB_CLUSTER_PROFILE=pimox ./jeannie platform argocd`; the readiness
|
||||||
step waits for the Argo CD rollouts. This does not change worker CPU topology.
|
step waits for the Argo CD rollouts. This does not change worker CPU topology.
|
||||||
|
|
||||||
|
## Scheduling feasibility before deployment
|
||||||
|
|
||||||
|
Every platform and application OpenTofu apply now runs
|
||||||
|
`scripts/scheduling-preflight.py` first, including retry attempts. The pipeline
|
||||||
|
creates a private temporary plan, renders the selected Helm releases using their
|
||||||
|
planned values and chart versions, and reads the selected cluster's nodes,
|
||||||
|
active Pods, controllers, PVCs, PVs, StorageClasses, and namespace labels. It also
|
||||||
|
renders local Kustomize/plain-manifest Argo CD sources for application applies.
|
||||||
|
The temporary plan and chart values are removed when the check finishes.
|
||||||
|
|
||||||
|
The check uses **allocatable capacity minus requests**, not `kubectl top` usage
|
||||||
|
or an arbitrary minimum core count. Worker-01 can stay at one CPU. The former
|
||||||
|
`LAB_PIMOX_APP_DEPLOY_MIN_CPUS` setting no longer gates application deployment;
|
||||||
|
the early worker check verifies readiness, and the scheduling estimate checks
|
||||||
|
the actual requested workloads before apply.
|
||||||
|
|
||||||
|
The estimate accounts for CPU, memory, Pod slots, other requested resources,
|
||||||
|
init containers and restartable sidecars, explicit Pod overhead, selectors,
|
||||||
|
required node/Pod affinity, taints/tolerations, hard topology spread, host ports,
|
||||||
|
bound PV node affinity, and single-writer PVC placement. Rolling deployments
|
||||||
|
must have room for their surge unless their strategy permits replacing an old
|
||||||
|
Pod first. Existing Pods' reservations remain charged until the simulated
|
||||||
|
rollout allows removal; terminating Pods do not silently free capacity.
|
||||||
|
|
||||||
|
An unschedulable workload reports its per-node blockers and stops deployment.
|
||||||
|
Discovery, rendering, unknown planned chart values, and unsupported hard
|
||||||
|
constraints also stop the apply. This check does not change workloads, remove
|
||||||
|
Pods, resize VMs, alter requests, or attempt preemption. The existing state
|
||||||
|
adoption step still runs before the check to make the plan possible.
|
||||||
|
|
||||||
|
This is a conservative, sequential placement estimate, not kube-scheduler or an
|
||||||
|
admission dry run. It tries resource reductions first and can reject a layout
|
||||||
|
that a different rollout/placement order would admit. Preferred placement is
|
||||||
|
not a hard constraint. Admission-added sidecars/defaults, concurrent cluster
|
||||||
|
changes, provisioning capacity, CSI attachment limits, quotas, hook Jobs, and
|
||||||
|
future autoscaling are not proven by it. Local GitOps rendering assumes the
|
||||||
|
checkout matches the revision Argo CD will deploy. The check verifies that the
|
||||||
|
Application repository matches a local remote and its locally resolved revision
|
||||||
|
matches HEAD; it does not fetch the remote branch. Only image overrides are
|
||||||
|
supported. Unsupported Application renderers and unpinned chart identities
|
||||||
|
fail rather than silently assuming an empty workload.
|
||||||
|
|
||||||
|
Prometheus and Alertmanager upgrades reuse the live Operator-generated Pod
|
||||||
|
templates for sidecars and PVCs while overlaying planned resources/placement.
|
||||||
|
A missing Operator template blocks this estimate; first-time Operator workload
|
||||||
|
bootstrap needs a separately reviewed path. Other Operator-generated workloads
|
||||||
|
(for example Calico's Installation) are explicitly reported as outside the
|
||||||
|
rendered workload check. Dynamic PVC provisioning gets a notice, not a claim
|
||||||
|
that storage capacity exists. Live post-apply readiness checks remain required.
|
||||||
|
The actual apply replans after this check; its result is a snapshot, not a
|
||||||
|
reservation or a guarantee against races.
|
||||||
|
|
||||||
|
Run a focused deployment as usual on Debian:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
LAB_CLUSTER_PROFILE=pimox ./jeannie platform argocd
|
||||||
|
```
|
||||||
|
|
||||||
|
Regression cases are provided for execution on Debian; they are not run on the
|
||||||
|
development laptop:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m unittest discover -s tests/jeannie -p 'test_scheduling_preflight.py'
|
||||||
|
```
|
||||||
|
|
||||||
## Monitoring during reduced CPU capacity
|
## Monitoring during reduced CPU capacity
|
||||||
|
|
||||||
`platform monitoring` creates the `homelab-monitoring` PriorityClass before
|
`platform monitoring` creates the `homelab-monitoring` PriorityClass before
|
||||||
|
|
|
||||||
|
|
@ -819,6 +819,40 @@ delete_prometheus_stack_storage() {
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
kubernetes_scheduling_preflight() {
|
||||||
|
local stack="$1"
|
||||||
|
shift
|
||||||
|
local directory status arg
|
||||||
|
local -a plan_args=()
|
||||||
|
[[ "${stack}" == "bootstrap/platform" || "${stack}" == "bootstrap/apps" ]] || return 0
|
||||||
|
if [[ -z "${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-}" ]]; then
|
||||||
|
echo "Scheduling preflight requires the selected control-plane node name." >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
for arg in "$@"; do
|
||||||
|
[[ "${arg}" == "-auto-approve" ]] || plan_args+=("${arg}")
|
||||||
|
done
|
||||||
|
directory="$(mktemp -d "${TMPDIR:-/tmp}/jeannie-scheduling.XXXXXX")" || return 1
|
||||||
|
echo "Checking scheduling feasibility for ${stack} before deployment..."
|
||||||
|
if ! tofu -chdir="${REPO_ROOT}/${stack}" plan -input=false -out="${directory}/plan" \
|
||||||
|
"${plan_args[@]}" >"${directory}/plan.log" 2>&1; then
|
||||||
|
cat "${directory}/plan.log" >&2
|
||||||
|
rm -rf -- "${directory}"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
if ! tofu -chdir="${REPO_ROOT}/${stack}" show -json "${directory}/plan" >"${directory}/plan.json"; then
|
||||||
|
rm -rf -- "${directory}"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
status=0
|
||||||
|
python3 "${REPO_ROOT}/scripts/scheduling-preflight.py" \
|
||||||
|
--plan "${directory}/plan.json" --kubeconfig "${KUBECONFIG_PATH}" \
|
||||||
|
--repo-root "${REPO_ROOT}" --expected-node "${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME}" || status=$?
|
||||||
|
# The private directory can contain sensitive planned chart values.
|
||||||
|
rm -rf -- "${directory}"
|
||||||
|
return "${status}"
|
||||||
|
}
|
||||||
|
|
||||||
tofu_apply_with_kubernetes_retry() {
|
tofu_apply_with_kubernetes_retry() {
|
||||||
local stack="$1"
|
local stack="$1"
|
||||||
shift
|
shift
|
||||||
|
|
@ -832,6 +866,7 @@ tofu_apply_with_kubernetes_retry() {
|
||||||
local output_file
|
local output_file
|
||||||
|
|
||||||
while true; do
|
while true; do
|
||||||
|
kubernetes_scheduling_preflight "${stack}" "$@" || return 1
|
||||||
output_file="$(mktemp "${TMPDIR:-/tmp}/homelab-tofu-apply.XXXXXX")"
|
output_file="$(mktemp "${TMPDIR:-/tmp}/homelab-tofu-apply.XXXXXX")"
|
||||||
set +e
|
set +e
|
||||||
tofu -chdir="${REPO_ROOT}/${stack}" apply "$@" 2>&1 | tee "${output_file}"
|
tofu -chdir="${REPO_ROOT}/${stack}" apply "$@" 2>&1 | tee "${output_file}"
|
||||||
|
|
@ -865,6 +900,7 @@ tofu_apply_with_kubernetes_retry() {
|
||||||
elif [[ "${stack}" == "bootstrap/apps" ]]; then
|
elif [[ "${stack}" == "bootstrap/apps" ]]; then
|
||||||
adopt_apps_existing_resources
|
adopt_apps_existing_resources
|
||||||
fi
|
fi
|
||||||
|
kubernetes_scheduling_preflight "${stack}" "$@" || return 1
|
||||||
output_file="$(mktemp "${TMPDIR:-/tmp}/homelab-tofu-refresh-false-apply.XXXXXX")"
|
output_file="$(mktemp "${TMPDIR:-/tmp}/homelab-tofu-refresh-false-apply.XXXXXX")"
|
||||||
set +e
|
set +e
|
||||||
tofu -chdir="${REPO_ROOT}/${stack}" apply -refresh=false "$@" 2>&1 | tee "${output_file}"
|
tofu -chdir="${REPO_ROOT}/${stack}" apply -refresh=false "$@" 2>&1 | tee "${output_file}"
|
||||||
|
|
@ -7241,7 +7277,6 @@ require_pimox_app_worker_capacity() {
|
||||||
local scope="${1:-all}"
|
local scope="${1:-all}"
|
||||||
local enabled="${LAB_PIMOX_APP_DEPLOY_REQUIRE_CAPACITY:-true}"
|
local enabled="${LAB_PIMOX_APP_DEPLOY_REQUIRE_CAPACITY:-true}"
|
||||||
local spec_file="${REPO_ROOT}/.lab/pimox-workers.tsv"
|
local spec_file="${REPO_ROOT}/.lab/pimox-workers.tsv"
|
||||||
local minimum_cpus="${LAB_PIMOX_APP_DEPLOY_MIN_CPUS:-2}"
|
|
||||||
local worker_key
|
local worker_key
|
||||||
local worker_host
|
local worker_host
|
||||||
local worker_user
|
local worker_user
|
||||||
|
|
@ -7253,37 +7288,32 @@ require_pimox_app_worker_capacity() {
|
||||||
local eligible_workers=0
|
local eligible_workers=0
|
||||||
|
|
||||||
if disabled_value "${enabled}"; then
|
if disabled_value "${enabled}"; then
|
||||||
echo "Skipping Pimox worker CPU gate because LAB_PIMOX_APP_DEPLOY_REQUIRE_CAPACITY=${enabled}."
|
echo "Skipping Pimox worker readiness gate because LAB_PIMOX_APP_DEPLOY_REQUIRE_CAPACITY=${enabled}. Scheduling preflight still runs before apply."
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
if [[ ! -s "${spec_file}" ]]; then
|
if [[ ! -s "${spec_file}" ]]; then
|
||||||
echo "No generated Pimox worker inventory exists; skipping Pimox worker CPU gate."
|
echo "No generated Pimox worker inventory exists; scheduling preflight will inspect live nodes before apply."
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
if ! [[ "${minimum_cpus}" =~ ^[1-9][0-9]*$ ]]; then
|
|
||||||
echo "LAB_PIMOX_APP_DEPLOY_MIN_CPUS must be a positive integer." >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
while IFS=$'\t' read -r worker_key worker_host worker_user worker_node worker_key_path; do
|
while IFS=$'\t' read -r worker_key worker_host worker_user worker_node worker_key_path; do
|
||||||
[[ -n "${worker_node}" ]] || continue
|
[[ -n "${worker_node}" ]] || continue
|
||||||
capacity="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" get node "${worker_node}" -o jsonpath='{.status.capacity.cpu}' 2>/dev/null || true)"
|
capacity="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" get node "${worker_node}" -o jsonpath='{.status.capacity.cpu}' 2>/dev/null || true)"
|
||||||
ready="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" get node "${worker_node}" -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' 2>/dev/null || true)"
|
ready="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" get node "${worker_node}" -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' 2>/dev/null || true)"
|
||||||
if [[ "${ready}" == "True" ]] && [[ "${capacity}" =~ ^[0-9]+$ ]] && ((capacity >= minimum_cpus)); then
|
if [[ "${ready}" == "True" ]] && [[ "${capacity}" =~ ^[0-9]+$ ]] && ((capacity >= 1)); then
|
||||||
eligible_workers=$((eligible_workers + 1))
|
eligible_workers=$((eligible_workers + 1))
|
||||||
elif [[ "${scope}" == "all" ]]; then
|
elif [[ "${scope}" == "all" ]]; then
|
||||||
echo "Pimox worker ${worker_node} must be Ready with at least ${minimum_cpus} Kubernetes CPU(s); Ready=${ready:-missing}, capacity=${capacity:-missing}." >&2
|
echo "Pimox worker ${worker_node} must be Ready with positive CPU capacity; Ready=${ready:-missing}, capacity=${capacity:-missing}." >&2
|
||||||
failures=$((failures + 1))
|
failures=$((failures + 1))
|
||||||
fi
|
fi
|
||||||
done <"${spec_file}"
|
done <"${spec_file}"
|
||||||
|
|
||||||
if [[ "${scope}" == "all" ]] && ((failures > 0)); then
|
if [[ "${scope}" == "all" ]] && ((failures > 0)); then
|
||||||
echo "Refusing to deploy applications until Pimox workers expose the required Kubernetes CPU capacity." >&2
|
echo "Refusing to deploy applications until Pimox workers are Ready; scheduling feasibility is checked separately." >&2
|
||||||
kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o custom-columns='NAME:.metadata.name,CPUS:.status.capacity.cpu,READY:.status.conditions[?(@.type=="Ready")].status' >&2 || true
|
kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o custom-columns='NAME:.metadata.name,CPUS:.status.capacity.cpu,READY:.status.conditions[?(@.type=="Ready")].status' >&2 || true
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
if [[ "${scope}" != "all" ]] && ((eligible_workers == 0)); then
|
if [[ "${scope}" != "all" ]] && ((eligible_workers == 0)); then
|
||||||
echo "Refusing to deploy ${scope}: no Ready Pimox worker exposes at least ${minimum_cpus} Kubernetes CPU(s)." >&2
|
echo "Refusing to deploy ${scope}: no Ready Pimox worker exposes positive CPU capacity." >&2
|
||||||
kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o custom-columns='NAME:.metadata.name,CPUS:.status.capacity.cpu,READY:.status.conditions[?(@.type=="Ready")].status' >&2 || true
|
kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o custom-columns='NAME:.metadata.name,CPUS:.status.capacity.cpu,READY:.status.conditions[?(@.type=="Ready")].status' >&2 || true
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,681 @@
|
||||||
|
#!/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", {})
|
||||||
|
limits = resources.get("limits", {})
|
||||||
|
requests = dict(resources.get("requests", {}))
|
||||||
|
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", []):
|
||||||
|
app.update(container_requests(container))
|
||||||
|
for container in spec.get("initContainers", []):
|
||||||
|
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", {}).items()})
|
||||||
|
app["pods"] = 1
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
def expression_matches(expression, labels):
|
||||||
|
key, operator = expression["key"], expression["operator"]
|
||||||
|
values = expression.get("values", [])
|
||||||
|
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):
|
||||||
|
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, {}).get("requiredDuringSchedulingIgnoredDuringExecution", []):
|
||||||
|
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", {}).get("podAntiAffinity", {}).get("requiredDuringSchedulingIgnoredDuringExecution", []):
|
||||||
|
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", []):
|
||||||
|
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", []):
|
||||||
|
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", []) + spec.get("initContainers", [])
|
||||||
|
for p in c.get("ports", [])
|
||||||
|
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:
|
||||||
|
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["spec"]["source"]
|
||||||
|
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", {})) - {"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:
|
||||||
|
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)
|
||||||
|
|
@ -0,0 +1,146 @@
|
||||||
|
"""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_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()
|
||||||
Loading…
Reference in New Issue