From a99ca6d11b52738f2ce6b49f7417a45cf0f4496f Mon Sep 17 00:00:00 2001 From: Christian Breunig Date: Tue, 29 Jul 2025 22:15:09 +0200 Subject: op-mode: T7403: add option for forcefully remove a container image If you have multiple images (tags) loaded for a container which point to the exact same hash - you can only forcefully delete them. vyos@vyos:~$ delete container image 70dc5806 Error: unable to delete image "70dc5806" by ID with more than one tag ([registry.io/foo/bar:v1.0 registry.io/foo/bar:v1.0.1]): please force removal In additon an image that is still beeing used can not be removed from the system as this would cause infinite container restarts. vyos@vyos:~$ delete container image all force Cannot delete image "d205499ae8bb" because it is currently being used by container "3b290f90e83d"! --- src/op_mode/container.py | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/op_mode/container.py b/src/op_mode/container.py index fe81636d2..feb9f41cc 100755 --- a/src/op_mode/container.py +++ b/src/op_mode/container.py @@ -14,6 +14,7 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +import typing import json import sys import subprocess @@ -63,7 +64,7 @@ def add_image(name: str): if do_logout: rc_cmd('podman logout --all') -def delete_image(name: str): +def delete_image(name: str, force: typing.Optional[bool] = False): from vyos.utils.process import rc_cmd if name == 'all': @@ -73,9 +74,30 @@ def delete_image(name: str): if not name: return # replace newline with whitespace name = name.replace('\n', ' ') - rc, output = rc_cmd(f'podman image rm {name}') - if rc != 0: - raise vyos.opmode.InternalError(output) + # convert to list + name = name.split() + + for image in name: + # convert the truncated image ID to a full image ID + rc, ancestor = rc_cmd(f'podman inspect {image} --format "{{{{.Id}}}}"') + if rc != 0: + raise vyos.opmode.InternalError(ancestor) + # check if the image ID is an ancestor of any running container + rc, in_use = rc_cmd(f'podman ps --filter ancestor={ancestor} -q') + if rc != 0: + raise vyos.opmode.InternalError(in_use) + + if bool(in_use): + error = f'Cannot delete image "{image}" because it is currently '\ + f'being used by container "{in_use}"!' + raise vyos.opmode.InternalError(error) + + tmp = f'podman image rm {image}' + if force: tmp += ' --force' + + rc, output = rc_cmd(tmp) + if rc != 0: + raise vyos.opmode.InternalError(output) def show_container(raw: bool): command = 'podman ps --all' -- cgit v1.2.3