From 85e20d9852b34b307fad0cd4fae722f8f9161930 Mon Sep 17 00:00:00 2001 From: Ian Wienand Date: Tue, 9 Nov 2021 16:52:47 +1100 Subject: [PATCH] containerfile: handle errors better Refactor things to use explicit names, and put in a trap to cleanup after any errors. Currently, if the build/run/export steps fail, it leaves behind images which eventually clog things to the point podman won't run any more (see also https://github.com/containers/podman/pull/12233 about errors seen due to this) Change-Id: Ib328a07ad67e3f71f379fbf34ae7ef74e212ef1c --- .../containerfile/root.d/08-containerfile | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/diskimage_builder/elements/containerfile/root.d/08-containerfile b/diskimage_builder/elements/containerfile/root.d/08-containerfile index c3452580..48fd8c5b 100755 --- a/diskimage_builder/elements/containerfile/root.d/08-containerfile +++ b/diskimage_builder/elements/containerfile/root.d/08-containerfile @@ -58,12 +58,22 @@ else _sudo="" fi -${_sudo} podman build -t dib-work-image -f $DIB_CONTAINERFILE_DOCKERFILE $DIB_CONTAINER_CONTEXT -container=$(${_sudo} podman run -d dib-work-image /bin/sh) +_podman_build_image="dib-tmp-work-image-$RANDOM" +_podman_export_container="dib-tmp-export-$RANDOM" + +function podman_cleanup() { + echo "Cleaning up container ${_podman_export_container}" + ${_sudo} podman rm ${_podman_export_container} || true + echo "Cleaning up build image ${_podman_build_image}" + ${_sudo} podman rmi ${_podman_build_image} || true +} + +trap "podman_cleanup" EXIT + +${_sudo} podman build -t ${_podman_build_image} -f $DIB_CONTAINERFILE_DOCKERFILE $DIB_CONTAINER_CONTEXT +${_sudo} podman run --name ${_podman_export_container} -d ${_podman_build_image} /bin/sh # NOTE(ianw) 2021-11-10 the tar must always be sudo to write out the chroot files # as other uids -${_sudo} podman export $container | sudo tar -C $TARGET_ROOT --numeric-owner -xf - -${_sudo} podman rm $container -${_sudo} podman rmi dib-work-image +${_sudo} podman export ${_podman_export_container} | sudo tar -C $TARGET_ROOT --numeric-owner -xf - sudo rm -f ${TARGET_ROOT}/.extra_settings