From aa90f7991aef47ddf338e32698ddbcc5c0f15e21 Mon Sep 17 00:00:00 2001
From: Corey O'Brien <coreypobrien@gmail.com>
Date: Thu, 16 Mar 2017 12:31:23 -0400
Subject: [PATCH] Ignore missing path in unmount_dir

If the path is missing, unmount_dir currently exits with an error which
unintentionally aborts cleanup efforts early. This change makes
unmount_dir idempotent by exiting successfully if a directory doesn't
exist.

Change-Id: I1491b4344e8569ecb2833f44baee445a89a39d61
---
 diskimage_builder/lib/common-functions |  2 +-
 diskimage_builder/lib/img-functions    |  4 +---
 tests/run_dib_library_tests.sh         | 10 +++++++++-
 3 files changed, 11 insertions(+), 5 deletions(-)

diff --git a/diskimage_builder/lib/common-functions b/diskimage_builder/lib/common-functions
index b1f770588..89f0e41b3 100644
--- a/diskimage_builder/lib/common-functions
+++ b/diskimage_builder/lib/common-functions
@@ -341,7 +341,7 @@ function unmount_dir {
 
     if [ ! -d $dir ]; then
         echo "*** $dir is not a directory"
-        return 1
+        return 0
     fi
 
     # get rid of any symlink elements in the incoming path, because
diff --git a/diskimage_builder/lib/img-functions b/diskimage_builder/lib/img-functions
index 38f758a5e..f30e1f19f 100644
--- a/diskimage_builder/lib/img-functions
+++ b/diskimage_builder/lib/img-functions
@@ -113,9 +113,7 @@ function finalise_base () {
         fi
     fi
     # Cleanup /tmp in the guest, so there is less cruft left there
-    if [ -d "$TMP_MOUNT_PATH/tmp" ]; then
-        unmount_dir $TMP_MOUNT_PATH/tmp
-    fi
+    unmount_dir $TMP_MOUNT_PATH/tmp
     find $TMP_MOUNT_PATH/tmp -maxdepth 1 -mindepth 1 | xargs sudo rm -rf --one-file-system
     # Truncate /var/log files in preparation for first boot
     sudo find ${TMP_MOUNT_PATH}/var/log -type f -exec cp /dev/null '{}' \;
diff --git a/tests/run_dib_library_tests.sh b/tests/run_dib_library_tests.sh
index a44408c41..c8f0549a3 100755
--- a/tests/run_dib_library_tests.sh
+++ b/tests/run_dib_library_tests.sh
@@ -6,7 +6,7 @@
 # need a human in the loop.  Thus it's mostly useful for developers
 # during testing, but not so great for CI
 
-source ../lib/common-functions
+source ../diskimage_builder/lib/common-functions
 
 #
 # Directory mounting and unmounting
@@ -44,6 +44,14 @@ else
     echo "*** PASS all directories unmounted"
 fi
 
+# unmount missing dir
+if unmount_dir /this/path/does/not/exist/but/this/should/not/fail; then
+    echo "*** PASS unmount_dir ignored a missing path"
+else
+    echo "*** FAILED unmount_dir should ignore missing paths"
+    return 1
+fi
+
 # cleanup
 rm -rf $TMP_DIR