naviat
8/1/2018 - 4:48 PM

K8s client

K8s client

from kubernetes import client, config
from datetime import datetime


def extract_days(pod_timestamp):
    delta = datetime.now().replace(tzinfo=None) - pod_timestamp.replace(tzinfo=None)
    return delta.days



config.load_kube_config()


v1_apps = client.AppsV1beta1Api()
deployment = v1_apps.read_namespaced_deployment(name='acdclegacy-production', namespace='acdc-legacy')


print(deployment)
# print("Listing pods with their IPs:")

v1 = client.CoreV1Api()

ret = v1.list_namespaced_pod(namespace='acdc-legacy', label_selector="acdclegacy-production=true")

pods_need_replacement = 0
replace_list = []
for pod in ret.items:
    created = pod.metadata.creation_timestamp.replace(tzinfo=None)
    name = pod.metadata.name
    id = pod.metadata.uid

    days_old = extract_days(created)
    print("Pod {} is {} days old".format(name, days_old))

    if days_old > 0:
        pods_need_replacement += 1
        replace_list.append(pod)

# Scale first
if pods_need_replacement > 0:
    deployment.spec.replicas = deployment.spec.replicas + pods_need_replacement
    deployment = v1_apps.patch_namespaced_deployment_scale(name='acdclegacy-production', namespace='acdc-legacy', body=deployment)

    # Wait for running
    print(deployment)
    deployment.spec.replicas = deployment.spec.replicas - pods_need_replacement
    deployment = v1_apps.patch_namespaced_deployment_scale(name='acdclegacy-production', namespace='acdc-legacy', body=deployment)

# Delete old pods
for pod in replace_list:
    v1.delete_namespaced_pod(name=pod.metadata.name, namespace='acdc-legacy', body=pod)