Skip to content

Instantly share code, notes, and snippets.

@benoit74
Last active September 5, 2023 08:59
Show Gist options
  • Save benoit74/68d3fdb2bdc77e641cdb218575b417e8 to your computer and use it in GitHub Desktop.
Save benoit74/68d3fdb2bdc77e641cdb218575b417e8 to your computer and use it in GitHub Desktop.
k8s: Find daemonsets with pod to delete for update, and print the corresponding node names
import json
import subprocess
nodes_str = subprocess.check_output(
["kubectl", "get", "nodes", "-o", "json"]
)
nodes = json.loads(nodes_str)
node_data = {}
for node in nodes.get("items"):
node_data[node.get("metadata").get("name")] = {
"kiwix_role": node.get("metadata").get("labels").get("k8s.kiwix.org/role")
}
daemonsets_str = subprocess.check_output(
["kubectl", "get", "ds", "--all-namespaces", "-o", "json"]
)
daemonsets = json.loads(daemonsets_str)
def filter_ds(ds):
ds_status = ds.get("status")
if ds_status.get("currentNumberScheduled") == 0:
return False
return ds_status.get("currentNumberScheduled") != ds_status.get(
"updatedNumberScheduled"
)
daemonsets_with_old_pods = list(filter(filter_ds, daemonsets.get("items")))
if len(daemonsets_with_old_pods) == 0:
print("No daemonset with pod to update")
exit()
print()
print("Some pods have to be deleted for update.")
for daemonset in daemonsets_with_old_pods:
print()
daemonset_namespace = daemonset.get("metadata").get("namespace")
daemonset_name = daemonset.get("metadata").get("name")
print(f"Daemonset {daemonset_namespace}/{daemonset_name}:")
match_labels = daemonset.get("spec").get("selector").get("matchLabels")
command = [
"kubectl",
"get",
"pods",
"--all-namespaces",
"-o",
"json",
]
for key, value in match_labels.items():
command.append(f"-l={key}={value}")
expected_template_generation = daemonset.get("metadata").get("generation")
pods_str = subprocess.check_output(command)
pods = json.loads(pods_str)
for pod in pods.get("items"):
current_generation = (
pod.get("metadata").get("labels").get("pod-template-generation")
)
if int(current_generation) == int(expected_template_generation):
continue
nodeName = pod.get('spec').get('nodeName')
print(
f"- node {nodeName} ({node_data[nodeName]['kiwix_role']}): generation "
f"{current_generation} instead of generation {expected_template_generation}"
)
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment