cros_sdk: Check for mounted chroot image

When --use-image is not passed, cros_sdk automatically enables use_image
if it finds a chroot.img alongside an empty chroot.  fstrim only gets
run when use_image is true, so this combination means that fstrim only
happens when chroot.img is initially mounted unless the user explicitly
passes --use-image.

In order to restore the previous behavior of running fstrim as needed
when entering the chroot, we want to enable use_image whenever the
chroot is mounted from an image.  We don't want to enable it every time
a chroot.img exists because the user may have created a plain chroot
without deleting their chroot.img.

If the chroot is populated and there's a chroot.img, add a new check
that something is mounted on the chroot before enabling use_image.  This
should catch the normal cases of entering a plain chroot or entering an
image-backed chroot.  If the user has an unused chroot.img and they've
mounted something else over their chroot, the new check will incorrectly
attempt to call fstrim.  This should be rare, so it doesn't seem helpful
to make the mountpoint check more robust.

BUG=chromium:1155628
TEST=cros_sdk --enter and verify that fstrim is called

Change-Id: Ied3631aef2c0614771cb6b29d2bb06466841c0e2
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/chromite/+/2580043
Reviewed-by: Mike Frysinger <vapier@chromium.org>
Tested-by: Benjamin Gordon <bmgordon@chromium.org>
Commit-Queue: Benjamin Gordon <bmgordon@chromium.org>
diff --git a/scripts/cros_sdk.py b/scripts/cros_sdk.py
index dc87c78..79c6b35 100644
--- a/scripts/cros_sdk.py
+++ b/scripts/cros_sdk.py
@@ -971,11 +971,19 @@
   # --use-image after a reboot to avoid losing access to their existing chroot.
   chroot_exists = cros_sdk_lib.IsChrootReady(options.chroot)
   img_path = _ImageFileForChroot(options.chroot)
-  if (not options.use_image and not chroot_exists and not options.delete and
-      not options.unmount and os.path.exists(img_path)):
-    logging.notice('Existing chroot image %s found.  Forcing --use-image on.',
-                   img_path)
-    options.use_image = True
+  if (not options.use_image and not options.delete and not options.unmount
+      and os.path.exists(img_path)):
+    if chroot_exists:
+      # If the chroot is already populated, make sure it has something
+      # mounted on it before we assume it came from an image.
+      cmd = ['mountpoint', '-q', options.chroot]
+      if cros_build_lib.dbg_run(cmd, check=False).returncode == 0:
+        options.use_image = True
+
+    else:
+      logging.notice('Existing chroot image %s found.  Forcing --use-image on.',
+                     img_path)
+      options.use_image = True
 
   if any_snapshot_operation and not options.use_image:
     if os.path.exists(img_path):