def cleanup_pods(labels):
    """Cleanup pods in current namespace that match the given labels"""
    kube = kubernetes.client.CoreV1Api()

    def get_pods():
        """Return list of pods matching given labels"""
        return [
            pod
            for pod in kube.list_namespaced_pod(namespace=K8S_NAMESPACE).items
            if all(
                pod.metadata.labels.get(key) == value for key, value in labels.items()
            )
        ]

    all_pods = pods = get_pods()
    for pod in pods:
        print(f"deleting pod {pod.metadata.name}")
        try:
            kube.delete_namespaced_pod(
                namespace=K8S_NAMESPACE,
                name=pod.metadata.name,
                body=kubernetes.client.V1DeleteOptions(grace_period_seconds=0),
            )
        except kubernetes.client.rest.ApiException as e:
            # ignore 404, 409: already gone
            if e.status not in (404, 409):
                raise

    while pods:
        print(f"Waiting for {len(pods)} pods to exit")
        time.sleep(1)
        pods = get_pods()
    if all_pods:
        pod_names = ",".join([pod.metadata.name for pod in all_pods])
        print(f"Deleted {len(all_pods)} pods: {pod_names}")
Cleanup pods in current namespace that match the given labels
binderhub/tests/conftest.py