def delete_pvc(self, namespace, name, service_api: CoreV1Api = None): try: service_api.delete_namespaced_persistent_volume_claim( name, namespace) except Exception as e: logger.error(e) return -1 return 2
def delete_pvcs(api: CoreV1Api): for pvc in list_pvcs(api): api.delete_namespaced_persistent_volume_claim( pvc.metadata.name, pvc.metadata.namespace, body=V1DeleteOptions( grace_period_seconds=0, propagation_policy="Background", preconditions=V1Preconditions( resource_version=pvc.metadata.resource_version, uid=pvc.metadata.uid, ), ), )
def destroy_statefulset(api: client.AppsV1Api, core_api: client.CoreV1Api, namespace, name): for pvc in core_api.list_namespaced_persistent_volume_claim( namespace=namespace, label_selector=f'app={name}').items: core_api.delete_namespaced_persistent_volume_claim( name=pvc.metadata.name, namespace=namespace) if len( api.list_namespaced_stateful_set( namespace=namespace, field_selector=f'metadata.name={name}').items) == 1: logger.info(f'destroying StatefulSet: {namespace}/{name}') api.delete_namespaced_stateful_set(name=name, namespace=namespace) else: logger.info(f'cannot find StatefulSet to destroy: {namespace}/{name}')
def delete_detached_pvcs(api: CoreV1Api, namespace: str, claim_prefix: str): """ Delete persistent volume claims that are not attached to any pods. If a persistent volume claim is deleted while attached to a pod, then the underlying persistent volume will remain bound until the delete is finalized, and the delete will not be finalized until the pod is also deleted. If a stateful set immediately recreates a pod (e.g. via `kubectl rollout restart`) that was attached to a persistent volume claim that was deleted, then the stateful set may still try to reuse the persistent volume claim after the delete is finalized. Delete the pod again to cause the stateful set to recreate the persistent volume claim when it next recreates the pod. """ attached_pvcs = { volume.persistent_volume_claim.claim_name for pod in api.list_namespaced_pod(namespace).items if not _unschedulable_due_to_pvc(pod) and pod.spec and pod.spec.volumes for volume in pod.spec.volumes if volume.persistent_volume_claim } for pvc in api.list_namespaced_persistent_volume_claim(namespace).items: if (pvc.metadata.name.startswith(claim_prefix) and pvc.metadata.name not in attached_pvcs and not pvc.metadata.deletion_timestamp): logger.info(f"deleting detached pvc: {pvc.metadata.name}") try: api.delete_namespaced_persistent_volume_claim( name=pvc.metadata.name, namespace=namespace, body=V1DeleteOptions( grace_period_seconds=0, propagation_policy="Background", preconditions=V1Preconditions( resource_version=pvc.metadata.resource_version, uid=pvc.metadata.uid, ), ), ) except ApiException as e: if e.reason not in (CONFLICT, NOT_FOUND): raise logger.info( f"pvc already deleted or updated: {pvc.metadata.name}")