Joe Jasinski
Joe Jasinski

Reputation: 10791

kubernetes python client: block and wait for child pods to dissappear when deleting deployment

I'm looking to use the Kubernetes python client to delete a deployment, but then block and wait until all of the associated pods are deleted as well. A lot of the examples I'm finding recommend using the watch function something like follows.

try:
    # try to delete if exists
    AppsV1Api(api_client).delete_namespaced_deployment(namespace="default", name="mypod")
except Exception:
    # handle exception

# wait for all pods associated with deployment to be deleted. 
for e in w.stream(
    v1.list_namespaced_pod, namespace="default",
    label_selector='mylabel=my-value",
    timeout_seconds=300):

    pod_name = e['object'].metadata.name
    print("pod_name", pod_name)
    if e['type'] == 'DELETED':
        w.stop()
        break

However, I see two problems with this.

  1. If the pod is already gone (or if some other process deletes all pods before execution reaches the watch stream), then the watch will find no events and the for loop will get stuck until the timeout expires. Watch does not seem to generate activity if there are no events.
  2. Upon seeing events in the event stream for the pod activity, how do know all the pods got deleted? Seems fragile to count them.

I'm basically looking to replace the kubectl delete --wait functionality with a python script.

Thanks for any insights into this.

Upvotes: 3

Views: 2221

Answers (2)

Chetan Jain
Chetan Jain

Reputation: 241

import json

def delete_pod(pod_name):
    return v1.delete_namespaced_pod(name=pod_name, namespace="default")


def delete_pod_if_exists(pod_name):
    def run():
        delete_pod(pod_name)

    while True:
        try:
            run()
        except ApiException as e:
            has_deleted = json.loads(e.body)['code'] == 404
            if has_deleted:
                return

Upvotes: 2

G1Rao
G1Rao

Reputation: 480

May be you can try this way and handle exceptions based your requirement

    def delete_deployment():
        """ Delete deployment """
        while True:
            try:
                deployment = api_client.delete_namespaced_deployment(
                    name="deployment_name",
                    namespace="deployment_namespace",
                  body=client.V1DeleteOptions(propagation_policy="Foreground", grace_period_seconds=5),
                    )
            except ApiException:
                break
        print("Deployment 'deployment_name' has been deleted.")

Upvotes: 1

Related Questions