[Libguestfs] [PATCH] filesystems: fix size reporting for filesystems

Pino Toscano ptoscano at redhat.com
Wed Feb 26 16:15:06 UTC 2020


The current way to get the size of a filesystem is to query the size in
bytes of the device. However, this gives the whole size of the device
where a filesystem is stored, and it does not consider the actual size
for which the filesystem is configured (e.g. in case it was shrunk).
A simple reproducer for this is:
$ guestfish -N test.img=fs:ext4:2G resize2fs-size /dev/sda1 1073741824

As result, try to mount the filesystem, and get its actual statistics to
determine its full size. In case mounting fails, fall back to the
previous method, which is still a good value in the majority of the
cases.

Thanks to: Erik Skultety.
---
 cat/filesystems.c | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)

diff --git a/cat/filesystems.c b/cat/filesystems.c
index cec3c4e47..2b95d3112 100644
--- a/cat/filesystems.c
+++ b/cat/filesystems.c
@@ -508,7 +508,23 @@ do_output_filesystems (void)
       guestfs_pop_error_handler (g);
 
       if (!device || !subvolume) {
-        size = guestfs_blockdev_getsize64 (g, fses[i]);
+        /* Try mounting and stating the device.  This might reasonably
+         * fail, so don't show errors.
+         */
+        guestfs_push_error_handler (g, NULL, NULL);
+
+        if (guestfs_mount_ro (g, fses[i], "/") == 0) {
+          CLEANUP_FREE_STATVFS struct guestfs_statvfs *stat = NULL;
+
+          stat = guestfs_statvfs (g, "/");
+          size = stat->blocks * stat->bsize;
+          guestfs_umount_all (g);
+        } else {
+          size = guestfs_blockdev_getsize64 (g, fses[i]);
+        }
+
+        guestfs_pop_error_handler (g);
+
         if (size == -1)
           exit (EXIT_FAILURE);
       }
-- 
2.24.1




More information about the Libguestfs mailing list