Handle nullable scheduling fields and exporter startup
This commit is contained in:
parent
57b2e55ac0
commit
34389f7624
|
|
@ -19,6 +19,14 @@ if ! dpkg-query -W -f='${Status}' prometheus-node-exporter 2>/dev/null |
|
|||
sudo -n env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends prometheus-node-exporter
|
||||
fi
|
||||
sudo -n systemctl enable --now prometheus-node-exporter
|
||||
curl --max-time 10 -fsS http://127.0.0.1:9100/metrics |
|
||||
grep -F 'node_exporter_build_info' >/dev/null
|
||||
echo "Node exporter is responding on TCP/9100."
|
||||
for attempt in {1..15}; do
|
||||
if curl --max-time 5 -fsS http://127.0.0.1:9100/metrics 2>/dev/null |
|
||||
grep -F 'node_exporter_build_info' >/dev/null; then
|
||||
echo "Node exporter is responding on TCP/9100."
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "Node exporter did not respond on 127.0.0.1:9100 after 30 seconds." >&2
|
||||
sudo -n systemctl status prometheus-node-exporter --no-pager -n 8 >&2 || true
|
||||
exit 1
|
||||
|
|
|
|||
|
|
@ -119,18 +119,18 @@ 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", [])
|
||||
return all(labels.get(k) == v for k, v in (selector.get("matchLabels") or {}).items()) and all(
|
||||
expression_matches(e, labels) for e in selector.get("matchExpressions") or []
|
||||
)
|
||||
|
||||
|
||||
def affinity_matches(affinity, node):
|
||||
terms = affinity.get("nodeSelectorTerms", [])
|
||||
terms = affinity.get("nodeSelectorTerms") or []
|
||||
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", []))
|
||||
and all(expression_matches(e, node["metadata"].get("labels", {})) for e in term.get("matchExpressions") or [])
|
||||
and all(expression_matches(e, fields) for e in term.get("matchFields") or [])
|
||||
for term in terms
|
||||
)
|
||||
|
||||
|
|
@ -141,7 +141,7 @@ def tolerates(taint, tolerations):
|
|||
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
|
||||
for t in tolerations or []
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -194,7 +194,7 @@ class Estimate:
|
|||
def peer_matches(self, term, incoming, peer):
|
||||
namespace = incoming["metadata"].get("namespace", "default")
|
||||
peer_namespace = peer["metadata"].get("namespace", "default")
|
||||
namespaces = term.get("namespaces", [])
|
||||
namespaces = term.get("namespaces") or []
|
||||
selector = term.get("namespaceSelector")
|
||||
if not namespaces and selector is None:
|
||||
namespaces = [namespace]
|
||||
|
|
@ -204,10 +204,10 @@ class Estimate:
|
|||
source_labels = incoming["metadata"].get("labels", {})
|
||||
if not selector_matches(term.get("labelSelector"), labels):
|
||||
return False
|
||||
for key in term.get("matchLabelKeys", []):
|
||||
for key in term.get("matchLabelKeys") or []:
|
||||
if key in source_labels and labels.get(key) != source_labels[key]:
|
||||
return False
|
||||
for key in term.get("mismatchLabelKeys", []):
|
||||
for key in term.get("mismatchLabelKeys") or []:
|
||||
if key in source_labels and labels.get(key) == source_labels[key]:
|
||||
return False
|
||||
return True
|
||||
|
|
@ -215,7 +215,7 @@ class Estimate:
|
|||
def topology_reasons(self, pod, node):
|
||||
reasons = []
|
||||
labels = node["metadata"].get("labels", {})
|
||||
affinity = pod["spec"].get("affinity", {})
|
||||
affinity = pod["spec"].get("affinity") or {}
|
||||
for field in ("podAffinity", "podAntiAffinity"):
|
||||
for term in (affinity.get(field) or {}).get("requiredDuringSchedulingIgnoredDuringExecution") or []:
|
||||
key = term["topologyKey"]
|
||||
|
|
@ -246,14 +246,14 @@ class Estimate:
|
|||
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()):
|
||||
if any(candidate_labels.get(k) != v for k, v in (pod["spec"].get("nodeSelector") or {}).items()):
|
||||
continue
|
||||
required = affinity.get("nodeAffinity", {}).get("requiredDuringSchedulingIgnoredDuringExecution")
|
||||
required = (affinity.get("nodeAffinity") or {}).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", [])
|
||||
for t in candidate.get("spec", {}).get("taints") or []
|
||||
):
|
||||
continue
|
||||
domains.add(candidate_labels[key])
|
||||
|
|
@ -273,13 +273,13 @@ class Estimate:
|
|||
|
||||
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)
|
||||
ref = next((r for r in pod["metadata"].get("ownerReferences") or [] 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)
|
||||
parent = next((r for r in controller["metadata"].get("ownerReferences") or [] if r.get("controller")), None)
|
||||
if parent:
|
||||
key = parent["kind"], namespace, parent["name"]
|
||||
return key
|
||||
|
|
@ -295,25 +295,25 @@ class Estimate:
|
|||
reasons.append("nodeName mismatch")
|
||||
if node.get("spec", {}).get("unschedulable"):
|
||||
reasons.append("cordoned")
|
||||
node_ready = any(c["type"] == "Ready" and c["status"] == "True" for c in node.get("status", {}).get("conditions", []))
|
||||
node_ready = any(c["type"] == "Ready" and c["status"] == "True" for c in node.get("status", {}).get("conditions") or [])
|
||||
bootstrap = name == self.bootstrap_node
|
||||
if not node_ready and not bootstrap:
|
||||
reasons.append("NotReady")
|
||||
selector_mismatch = any(labels.get(k) != v for k, v in spec.get("nodeSelector", {}).items())
|
||||
selector_mismatch = any(labels.get(k) != v for k, v in (spec.get("nodeSelector") or {}).items())
|
||||
if selector_mismatch:
|
||||
reasons.append("nodeSelector mismatch")
|
||||
affinity = spec.get("affinity", {})
|
||||
required = affinity.get("nodeAffinity", {}).get("requiredDuringSchedulingIgnoredDuringExecution")
|
||||
affinity = spec.get("affinity") or {}
|
||||
required = (affinity.get("nodeAffinity") or {}).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", []):
|
||||
for taint in node.get("spec", {}).get("taints") or []:
|
||||
if (taint["effect"] in ("NoSchedule", "NoExecute")
|
||||
and not (bootstrap and taint.get("key") == "node.kubernetes.io/not-ready")
|
||||
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")
|
||||
claim = (volume.get("persistentVolumeClaim") or {}).get("claimName")
|
||||
if not claim:
|
||||
continue
|
||||
pvc = self.pvcs.get((namespace, claim))
|
||||
|
|
@ -341,11 +341,11 @@ class Estimate:
|
|||
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", [])
|
||||
modes = pvc.get("spec", {}).get("accessModes") or []
|
||||
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", []))
|
||||
uses_claim = any((v.get("persistentVolumeClaim") or {}).get("claimName") == claim for v in peer["spec"].get("volumes") or [])
|
||||
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":
|
||||
|
|
@ -424,7 +424,7 @@ class Estimate:
|
|||
targets = [None] * replicas
|
||||
if kind == "DaemonSet":
|
||||
# DaemonSet controller supplies these tolerations when creating pods.
|
||||
pod["spec"].setdefault("tolerations", []).extend([
|
||||
pod["spec"]["tolerations"] = (pod["spec"].get("tolerations") or []) + [
|
||||
{"key": key, "operator": "Exists", "effect": effect}
|
||||
for key, effect in [
|
||||
("node.kubernetes.io/not-ready", "NoExecute"),
|
||||
|
|
@ -434,7 +434,7 @@ class Estimate:
|
|||
("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):
|
||||
|
|
@ -443,17 +443,17 @@ class Estimate:
|
|||
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):
|
||||
update = spec.get("updateStrategy") or {}
|
||||
if update.get("type") == "OnDelete" or (update.get("rollingUpdate") or {}).get("partition", 0):
|
||||
raise CannotCheck(f"{namespace}/{name}: manual/partitioned StatefulSet rollout requires review")
|
||||
strategy = spec.get("strategy", {})
|
||||
rolling = strategy.get("rollingUpdate", {})
|
||||
strategy = spec.get("strategy") or {}
|
||||
rolling = strategy.get("rollingUpdate") or {}
|
||||
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", {})
|
||||
strategy = spec.get("updateStrategy") or {}
|
||||
if strategy.get("type") == "OnDelete":
|
||||
raise CannotCheck(f"{namespace}/{name}: manual DaemonSet rollout requires review")
|
||||
rolling = strategy.get("rollingUpdate", {})
|
||||
rolling = strategy.get("rollingUpdate") or {}
|
||||
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")
|
||||
|
|
@ -467,8 +467,8 @@ class Estimate:
|
|||
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", []):
|
||||
pod["spec"]["volumes"] = copy.deepcopy(template["spec"].get("volumes") or [])
|
||||
for claim in spec.get("volumeClaimTemplates") or []:
|
||||
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"]})
|
||||
|
|
@ -663,7 +663,7 @@ def operator_workload(document, controllers):
|
|||
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", []):
|
||||
for override in spec.get("containers") or []:
|
||||
existing = next((c for c in pod["containers"] if c["name"] == override["name"]), None)
|
||||
if existing is None:
|
||||
pod["containers"].append(copy.deepcopy(override))
|
||||
|
|
@ -761,6 +761,9 @@ def main():
|
|||
engine.pods = before
|
||||
failures[identity(item)] = str(exc)
|
||||
deferred.append(item)
|
||||
except (AttributeError, TypeError, KeyError) as exc:
|
||||
kind, namespace, name = identity(item)
|
||||
raise CannotCheck(f"{kind} {namespace}/{name}: could not evaluate scheduling fields ({exc})") from exc
|
||||
if not progress:
|
||||
break
|
||||
pending = deferred
|
||||
|
|
|
|||
Loading…
Reference in New Issue