From 4109cdec5303fea082db2b3435cfd37b391bb7e1 Mon Sep 17 00:00:00 2001 From: William Wernert Date: Wed, 30 Jun 2021 15:35:01 -0400 Subject: [PATCH] Refactor so-docker-prune to prevent exceptions when removing images * Prune containers at beginning of script so stopped containers using old images are removed * Add force=True arg to remove() call to ensure an image is still deleted on the off chance a container is still using that image * Add exception handling to continue removing containers instead of exiting if the script fails to remove a container --- salt/common/tools/sbin/so-docker-prune | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/salt/common/tools/sbin/so-docker-prune b/salt/common/tools/sbin/so-docker-prune index b1c359b58..3ec2a31a9 100755 --- a/salt/common/tools/sbin/so-docker-prune +++ b/salt/common/tools/sbin/so-docker-prune @@ -47,6 +47,10 @@ def get_image_version(string) -> str: def main(quiet): client = docker.from_env() + # Prune old/stopped containers + if not quiet: print('Pruning old containers') + client.container.prune() + image_list = client.images.list(filters={ 'dangling': False }) # Map list of image objects to flattened list of tags (format: "name:version") @@ -74,7 +78,10 @@ def main(quiet): for group in grouped_t_list[2:]: for tag in group: if not quiet: print(f'Removing image {tag}') - client.images.remove(tag) + try: + client.images.remove(tag, force=True) + except docker.errors.ClientError as e: + print(f'Could not remove image {tag}, continuing...') except (docker.errors.APIError, InvalidVersion) as e: print(f'so-{get_so_image_basename(t_list[0])}: {e}', file=sys.stderr) exit(1)