Skip to contentSkip to conversation

Provide classes for building disk images with FS partitions

PATCH Superseded Simon Glass 2 participants 11 messages Mar 6

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v3 cover Provide classes for building disk images with FS partitions

Create a class around mk_fs() to handle the common tasks of image creation, such as managing scratch directories and cleaning up. Add a helper class for creating disk images with partition tables.

Start with a few small cleanups to mk_fs(), then convert a test over to use the new classes.

Changes in v3:
- Rewrite the commit message as suggested by Tom Rini
- Make the class a thin wrapper that delegates to mk_fs()
- Remove cur_dir parameter from DiskHelper as suggested by Tom Rini
- Remove editorialising from commit message

Changes in v2:
- Split the quiet flag into a separate commit
- Fix fs_img to accept only a leaf name, always under persistent_data_dir
- Add new patch to split the quiet flag out of the previous patch
- Split the pylint fix into a separate commit
- Explain why setup_image() is left to later

Simon Glass (7):
test: fs_helper: Allow passing the image filename
test: fs_helper: Add a quiet flag to mk_fs()
test: Update comment for fs_helper.setup_image()
test: fs_helper: Drop the size_gran argument
test: Convert fs_helper to use a class
test: Add a helper class to create disk images
test: Convert test_efi_bootmgr to use FsHelper

 test/py/tests/fs_helper.py        | 205 ++++++++++++++++++++++++++++--
 test/py/tests/test_efi_bootmgr.py |  38 ++----
 2 files changed, 211 insertions(+), 32 deletions(-)
Signature · 4 lines
2.43.0

base-commit: c0ca147ac6228949a6d6497531c9f2f4a0dc6c67
branch: testfs3
#1 lore raw

PATCH v3 1/7 test: fs_helper: Allow passing the image filename

From: Simon Glass <[email protected]>

The mk_fs() function always generates its own image filename from the prefix and fs_type. Some callers need to specify a custom leaf name while still keeping the image under the persistent-data directory.

Add an fs_img parameter that accepts a leaf filename. When provided, it is joined with persistent_data_dir instead of the default name.

---

(no changes since v2)

Changes in v2:
- Split the quiet flag into a separate commit
- Fix fs_img to accept only a leaf name, always under persistent_data_dir

 test/py/tests/fs_helper.py | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
test/py/tests/fs_helper.py +7 -2
index b8a22b22806..bd9169b2a4d 100644
@@ -9,7 +9,8 @@ import re
 import os
 from subprocess import call, check_call, check_output, CalledProcessError
 
-def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000):
+def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
+          fs_img=None):
     """Create a file system volume
 
     Args:
@@ -19,11 +20,15 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000):
         prefix (str): Prefix string of volume's file name
         src_dir (str): Root directory to use, or None for none
         size_gran (int): Size granularity of file system image in bytes
+        fs_img (str or None): Leaf filename for image, or None to use a
+            default name. The image is always placed under
+            persistent_data_dir.
 
     Raises:
         CalledProcessError: if any error occurs when creating the filesystem
     """
-    fs_img = f'{prefix}.{fs_type}.img'
+    if not fs_img:
+        fs_img = f'{prefix}.{fs_type}.img'
     fs_img = os.path.join(config.persistent_data_dir, fs_img)
 
     if fs_type == 'fat12':
Signature · 1 line
2.43.0
Reviewed-by on v3 1/7
#2 lore raw

Re: [PATCH v3 1/7] test: fs_helper: Allow passing the image filename

Quoted 11 lines · Simon Glass

From: Simon Glass <[email protected]>

The mk_fs() function always generates its own image filename from the prefix and fs_type. Some callers need to specify a custom leaf name while still keeping the image under the persistent-data directory.

Add an fs_img parameter that accepts a leaf filename. When provided, it is joined with persistent_data_dir instead of the default name.

Signature · 1 line
Tom
#3 lore raw

PATCH v3 2/7 test: fs_helper: Add a quiet flag to mk_fs()

In reply to Simon Glass

From: Simon Glass <[email protected]>

In many cases callers only want to see warnings and errors from the filesystem-creation tools, not their normal output.

Add a quiet parameter to mk_fs() that suppresses the output of mkfs and switches mcopy from verbose to quiet mode.

---

(no changes since v2)

Changes in v2:
- Add new patch to split the quiet flag out of the previous patch

 test/py/tests/fs_helper.py | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
test/py/tests/fs_helper.py +8 -3
index bd9169b2a4d..4b123ab0afd 100644
@@ -8,9 +8,10 @@
 import re
 import os
 from subprocess import call, check_call, check_output, CalledProcessError
+from subprocess import DEVNULL
 
 def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
-          fs_img=None):
+          fs_img=None, quiet=False):
     """Create a file system volume
 
     Args:
@@ -23,6 +24,7 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
         fs_img (str or None): Leaf filename for image, or None to use a
             default name. The image is always placed under
             persistent_data_dir.
+        quiet (bool): Suppress non-error output
 
     Raises:
         CalledProcessError: if any error occurs when creating the filesystem
@@ -63,14 +65,17 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
         check_call(f'rm -f {fs_img}', shell=True)
         check_call(f'truncate -s $(( {size_gran} * {count} )) {fs_img}',
                    shell=True)
-        check_call(f'mkfs.{fs_lnxtype} {mkfs_opt} {fs_img}', shell=True)
+        check_call(f'mkfs.{fs_lnxtype} {mkfs_opt} {fs_img}', shell=True,
+                   stdout=DEVNULL if quiet else None)
         if fs_type == 'ext4':
             sb_content = check_output(f'tune2fs -l {fs_img}',
                                       shell=True).decode()
             if 'metadata_csum' in sb_content:
                 check_call(f'tune2fs -O ^metadata_csum {fs_img}', shell=True)
         elif fs_lnxtype == 'vfat' and src_dir:
-            check_call(f'mcopy -i {fs_img} -vsmpQ {src_dir}/* ::/', shell=True)
+            flags = f"-smpQ{'' if quiet else 'v'}"
+            check_call(f'mcopy -i {fs_img} {flags} {src_dir}/* ::/',
+                       shell=True)
         elif fs_lnxtype == 'exfat' and src_dir:
             check_call(f'fattools cp {src_dir}/* {fs_img}', shell=True)
         return fs_img
Signature · 1 line
2.43.0
#4 lore raw

PATCH v3 3/7 test: Update comment for fs_helper.setup_image()

In reply to Simon Glass

From: Simon Glass <[email protected]>

This function actually allows creating two partitions now, so update its comment to match that.

---

(no changes since v1)

 test/py/tests/fs_helper.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
test/py/tests/fs_helper.py +1 -1
index 4b123ab0afd..47340295fbb 100644
@@ -85,7 +85,7 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
 
 def setup_image(ubman, devnum, part_type, img_size=20, second_part=False,
                 basename='mmc'):
-    """Create a disk image with a single partition
+    """Create a disk image with one or two partitions
 
     Args:
         ubman (ConsoleBase): Console to use
Signature · 1 line
2.43.0
#5 lore raw

PATCH v3 4/7 test: fs_helper: Drop the size_gran argument

In reply to Simon Glass

From: Simon Glass <[email protected]>

Nothing uses this argument, so make it a constant for now.

---

(no changes since v2)

Changes in v2:
- Split the pylint fix into a separate commit

 test/py/tests/fs_helper.py | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)
test/py/tests/fs_helper.py +7 -5
index 47340295fbb..72e18588288 100644
@@ -10,8 +10,11 @@ import os
 from subprocess import call, check_call, check_output, CalledProcessError
 from subprocess import DEVNULL
 
-def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
-          fs_img=None, quiet=False):
+# size_gran (int): Size granularity of file system image in bytes
+SIZE_GRAN = 1 << 20
+
+
+def mk_fs(config, fs_type, size, prefix, src_dir=None, fs_img=None, quiet=False):
     """Create a file system volume
 
     Args:
@@ -20,7 +23,6 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
         size (int): Size of file system in bytes
         prefix (str): Prefix string of volume's file name
         src_dir (str): Root directory to use, or None for none
-        size_gran (int): Size granularity of file system image in bytes
         fs_img (str or None): Leaf filename for image, or None to use a
             default name. The image is always placed under
             persistent_data_dir.
@@ -55,7 +57,7 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
         elif fs_lnxtype != 'vfat' and fs_lnxtype != 'exfat':
             raise ValueError(f'src_dir not implemented for fs {fs_lnxtype}')
 
-    count = (size + size_gran - 1) // size_gran
+    count = (size + SIZE_GRAN - 1) // SIZE_GRAN
 
     # Some distributions do not add /sbin to the default PATH, where mkfs lives
     if '/sbin' not in os.environ["PATH"].split(os.pathsep):
@@ -63,7 +65,7 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
 
     try:
         check_call(f'rm -f {fs_img}', shell=True)
-        check_call(f'truncate -s $(( {size_gran} * {count} )) {fs_img}',
+        check_call(f'truncate -s $(( {SIZE_GRAN} * {count} )) {fs_img}',
                    shell=True)
         check_call(f'mkfs.{fs_lnxtype} {mkfs_opt} {fs_img}', shell=True,
                    stdout=DEVNULL if quiet else None)
Signature · 1 line
2.43.0
#6 lore raw

PATCH v3 5/7 test: Convert fs_helper to use a class

In reply to Simon Glass

From: Simon Glass <[email protected]>

Create a class around mk_fs() (and later setup_image()) to handle the common tasks of image creation. Many callers of fs_helper.mk_fs() create their own scratch directories while users of fs_helper.setup_image() rely on one being returned. Unify this by adding 'srcdir' as a field while converting to a class.

The class delegates to the existing mk_fs() function for the actual filesystem creation, adding lifecycle management for scratch directories and the image file.

---

Changes in v3:
- Rewrite the commit message as suggested by Tom Rini
- Make the class a thin wrapper that delegates to mk_fs()

 test/py/tests/fs_helper.py | 82 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 82 insertions(+)
test/py/tests/fs_helper.py +82 -0
index 72e18588288..07c011fa430 100644
@@ -7,13 +7,95 @@
 
 import re
 import os
+import shutil
 from subprocess import call, check_call, check_output, CalledProcessError
 from subprocess import DEVNULL
+import tempfile
 
 # size_gran (int): Size granularity of file system image in bytes
 SIZE_GRAN = 1 << 20
 
 
+class FsHelper:
+    """Creating a filesystem containing test files
+
+    Usage:
+        with FsHelper(ubman.config, 'ext4', 10, 'mmc1') as fsh:
+            # create files in the self.srcdir directory
+            fsh.mk_fs()
+            # Now use the filesystem
+
+        # The filesystem and srcdir are erased after the 'with' statement.
+
+        It is also possible to use an existing srcdir:
+
+            with FsHelper(ubman.config, 'fat32', 10, 'usb2') as fsh:
+                fsh.srcdir = src_dir
+                fsh.mk_fs()
+                ...
+
+    Properties:
+        fs_img (str): Filename for the filesystem image
+    """
+    def __init__(self, config, fs_type, size_mb, prefix):
+        """Set up a new object
+
+        Args:
+            config (u_boot_config): U-Boot configuration
+            fs_type (str): File system type: one of ext2, ext3, ext4, vfat,
+                fat12, fat16, fat32, exfat, fs_generic (which means vfat)
+            size_mb (int): Size of file system in MB
+            prefix (str): Prefix string of volume's file name
+        """
+        if ('fat' not in fs_type and 'ext' not in fs_type and
+             fs_type not in ['exfat', 'fs_generic']):
+            raise ValueError(f"Unsupported filesystem type '{fs_type}'")
+
+        self.config = config
+        self.fs_type = fs_type
+        self.size_mb = size_mb
+        self.prefix = prefix
+        self.quiet = True
+        self.fs_img = None
+        self.tmpdir = None
+        self.srcdir = None
+        self._do_cleanup = False
+
+    def mk_fs(self):
+        """Make a new filesystem and copy in the files"""
+        self.setup()
+        self._do_cleanup = True
+        self.fs_img = mk_fs(self.config, self.fs_type, self.size_mb << 20,
+                            self.prefix, self.srcdir, quiet=self.quiet)
+
+    def setup(self):
+        """Set up the srcdir ready to receive files"""
+        if not self.srcdir:
+            if self.config:
+                self.srcdir = os.path.join(self.config.persistent_data_dir,
+                                           f'{self.prefix}.{self.fs_type}.tmp')
+                if os.path.exists(self.srcdir):
+                    shutil.rmtree(self.srcdir)
+                os.mkdir(self.srcdir)
+            else:
+                self.tmpdir = tempfile.TemporaryDirectory('fs_helper')
+                self.srcdir = self.tmpdir.name
+
+    def cleanup(self):
+        """Remove created image"""
+        if self.tmpdir:
+            self.tmpdir.cleanup()
+        if self._do_cleanup:
+            os.remove(self.fs_img)
+
+    def __enter__(self):
+        self.setup()
+        return self
+
+    def __exit__(self, extype, value, traceback):
+        self.cleanup()
+
+
 def mk_fs(config, fs_type, size, prefix, src_dir=None, fs_img=None, quiet=False):
     """Create a file system volume
 
Signature · 1 line
2.43.0
#7 lore raw

Re: [PATCH v3 5/7] test: Convert fs_helper to use a class

Quoted 12 lines · Simon Glass

From: Simon Glass <[email protected]>

Create a class around mk_fs() (and later setup_image()) to handle the common tasks of image creation. Many callers of fs_helper.mk_fs() create their own scratch directories while users of fs_helper.setup_image() rely on one being returned. Unify this by adding 'srcdir' as a field while converting to a class.

The class delegates to the existing mk_fs() function for the actual filesystem creation, adding lifecycle management for scratch directories and the image file.

Quoted 5 lines

---

Changes in v3:
- Rewrite the commit message as suggested by Tom Rini

Thanks.

Quoted 1 line

- Make the class a thin wrapper that delegates to mk_fs()

Oh, this does make it much easier to review, thanks!

[snip]

test/py/tests/fs_helper.py line 52

Quoted 10 lines
test/py/tests/fs_helper.py +10 -0
+        Args:
+            config (u_boot_config): U-Boot configuration
+            fs_type (str): File system type: one of ext2, ext3, ext4, vfat,
+                fat12, fat16, fat32, exfat, fs_generic (which means vfat)
+            size_mb (int): Size of file system in MB
+            prefix (str): Prefix string of volume's file name
+        """
+        if ('fat' not in fs_type and 'ext' not in fs_type and
+             fs_type not in ['exfat', 'fs_generic']):
+            raise ValueError(f"Unsupported filesystem type '{fs_type}'")

I don't think this works as expected. The first thing that caught my eye is that shouldn't '"fat' not in fs_type" see exfat as valid? But we now also pass along a bunch of nonsense like ext5 or fat128 or fatnotreal to mkfs.notreal to fail on. We did zero sanity checks before, which is bad. But maybe we should just add this as an explicit:
if (fs_type not in ['fat12', 'fat16', ...]):
raise ...
?

Otherwise looks good.

Signature · 1 line
Tom
#8 lore raw

PATCH v3 6/7 test: Add a helper class to create disk images

In reply to Simon Glass

From: Simon Glass <[email protected]>

Provide a way to create disk images which consist of multiple filesystem images.

---

Changes in v3:
- Remove cur_dir parameter from DiskHelper as suggested by Tom Rini
- Remove editorialising from commit message

Changes in v2:
- Explain why setup_image() is left to later

 test/py/tests/fs_helper.py | 95 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 95 insertions(+)
test/py/tests/fs_helper.py +95 -0
index 07c011fa430..9e0f24f28b4 100644
@@ -96,6 +96,101 @@ class FsHelper:
         self.cleanup()
 
 
+class DiskHelper:
+    """Helper class for creating disk images containing filesystems
+
+    Usage:
+        with DiskHelper(ubman.config, 0, 'mmc') as img, \
+                FsHelper(ubman.config, 'ext4', 1, 'mmc') as fsh:
+            # Write files to fsh.srcdir
+            ...
+
+            # Create the filesystem
+            fsh.mk_fs()
+
+            # Add this filesystem to the disk
+            img.add_fs(fsh, DiskHelper.VFAT)
+
+            # Add more filesystems as needed (add another 'with' clause)
+            ...
+
+            # Get the final disk image
+            data = img.create()
+    """
+
+    # Partition-type codes
+    VFAT  = 0xc
+    EXT4  = 0x83
+
+    def __init__(self, config, devnum, prefix):
+        """Set up a new disk image
+
+        Args:
+            config (u_boot_config): U-Boot configuration
+            devnum (int): Device number (for filename)
+            prefix (str): Prefix string of volume's file name
+        """
+        self.fs_list = []
+        self.fname = os.path.join(config.persistent_data_dir,
+                                  f'{prefix}{devnum}.img')
+        self.remove_img = True
+        self._do_cleanup = False
+
+    def add_fs(self, fs_img, part_type, bootable=False):
+        """Add a new filesystem
+
+        Args:
+            fs_img (FsHelper): Filesystem to add
+            part_type (DiskHelper.VFAT or DiskHelper.EXT4): Partition type
+            bootable (bool): True to set the 'bootable' flag
+        """
+        self.fs_list.append([fs_img, part_type, bootable])
+
+    def create(self):
+        """Create the disk image
+
+        Create an image with a partition table and the filesystems
+        """
+        spec = ''
+        pos = 1   # Reserve 1MB for the partition table itself
+        for fsi, part_type, bootable in self.fs_list:
+            if spec:
+                spec += '\n'
+            spec += f'type={part_type:x}, size={fsi.size_mb}M, start={pos}M'
+            if bootable:
+                spec += ', bootable'
+            pos += fsi.size_mb
+
+        img_size = pos
+        try:
+            check_call(f'qemu-img create {self.fname} {img_size}M', shell=True)
+            self._do_cleanup = True
+            check_call(f'printf "{spec}" | sfdisk {self.fname}', shell=True)
+        except CalledProcessError:
+            os.remove(self.fname)
+            raise
+
+        pos = 1   # Reserve 1MB for the partition table itself
+        for fsi, part_type, bootable in self.fs_list:
+            check_call(
+                f'dd if={fsi.fs_img} of={self.fname} bs=1M seek={pos} conv=notrunc',
+                shell=True)
+            pos += fsi.size_mb
+        return self.fname
+
+    def cleanup(self):
+        """Remove created file"""
+        if self._do_cleanup:
+            os.remove(self.fname)
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, extype, value, traceback):
+        if self.remove_img:
+            self.cleanup()
+
+
 def mk_fs(config, fs_type, size, prefix, src_dir=None, fs_img=None, quiet=False):
     """Create a file system volume
 
Signature · 1 line
2.43.0
#9 lore raw

Re: [PATCH v3 6/7] test: Add a helper class to create disk images

Quoted 12 lines · Simon Glass

From: Simon Glass <[email protected]>

Provide a way to create disk images which consist of multiple filesystem images.

---

Changes in v3:
- Remove cur_dir parameter from DiskHelper as suggested by Tom Rini
- Remove editorialising from commit message

Quoted 5 lines

Changes in v2:
- Explain why setup_image() is left to later

 test/py/tests/fs_helper.py | 95 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 95 insertions(+)

Can we please move this to a follow-up series? This is harder to follow in part because test/py/tests/test_ut.py is the only test that calls fs_helper.setup_image with second_part=True, but then maybe I'm just missing it, doesn't do anything with it, we just need an empty partition to exist?

I'd like to take the first part of this series, then convert the fs_helper.mk_fs using tests. Then convert test_ut.py (which is open-coded fallocate/mkfs.vfat/etc calls) to the new class. Then understand what DiskHelper really needs to do. Perhaps include having a case where multiple (and non-empty secondary) partitions are used. Then we'll know we have both the right abstraction and that it works. Thanks.

Signature · 1 line
Tom
#10 lore raw

PATCH v3 7/7 test: Convert test_efi_bootmgr to use FsHelper

In reply to Simon Glass

From: Simon Glass <[email protected]>

As an example of how to use the helper, use it to simplify this test.

---

(no changes since v1)

 test/py/tests/test_efi_bootmgr.py | 38 ++++++++++++-------------------
 1 file changed, 14 insertions(+), 24 deletions(-)
test/py/tests/test_efi_bootmgr.py +14 -24
index 4c10cbdf17d..7d1f3f16d00 100644
@@ -5,7 +5,7 @@
 import shutil
 import pytest
 from subprocess import call, check_call, CalledProcessError
-from tests import fs_helper
+from tests.fs_helper import DiskHelper, FsHelper
 
 @pytest.mark.boardspec('sandbox')
 @pytest.mark.buildconfigspec('cmd_efidebug')
@@ -20,22 +20,19 @@ def test_efi_bootmgr(ubman):
     Args:
         ubman -- U-Boot console
     """
-    try:
-        efi_bootmgr_data, mnt = fs_helper.setup_image(ubman, 0, 0xc,
-                                                      basename='test_efi_bootmgr')
-
-        with open(mnt + '/initrd-1.img', 'w', encoding = 'ascii') as file:
-            file.write("initrd 1")
-
-        with open(mnt + '/initrd-2.img', 'w', encoding = 'ascii') as file:
-            file.write("initrd 2")
-
-        shutil.copyfile(ubman.config.build_dir + '/lib/efi_loader/initrddump.efi',
-                        mnt + '/initrddump.efi')
-
-        fsfile = fs_helper.mk_fs(ubman.config, 'vfat', 0x100000,
-                                 'test_efi_bootmgr', mnt)
-        check_call(f'dd if={fsfile} of={efi_bootmgr_data} bs=1M seek=1', shell=True)
+    with DiskHelper(ubman.config, 0, 'test_efi_bootmgr') as img, \
+            FsHelper(ubman.config, 'vfat', 1, 'test_efi_bootmgr') as fsh:
+        with open(f'{fsh.srcdir}/initrd-1.img', 'w', encoding = 'ascii') as outf:
+            outf.write("initrd 1")
+        with open(f'{fsh.srcdir}/initrd-2.img', 'w', encoding = 'ascii') as outf:
+            outf.write("initrd 2")
+        shutil.copyfile(
+            ubman.config.build_dir + '/lib/efi_loader/initrddump.efi',
+            f'{fsh.srcdir}/initrddump.efi')
+        fsh.mk_fs()
+
+        img.add_fs(fsh, DiskHelper.VFAT)
+        efi_bootmgr_data = img.create()
 
         ubman.run_command(cmd = f'host bind 0 {efi_bootmgr_data}')
 
@@ -61,10 +58,3 @@ def test_efi_bootmgr(ubman):
 
         ubman.run_command(cmd = 'efidebug boot rm 0001')
         ubman.run_command(cmd = 'efidebug boot rm 0002')
-    except CalledProcessError as err:
-        pytest.skip('Preparing test_efi_bootmgr image failed')
-        call('rm -f %s' % efi_bootmgr_data, shell=True)
-        return
-    finally:
-        call('rm -rf %s' % mnt, shell=True)
-        call('rm -f %s' % efi_bootmgr_data, shell=True)
Signature · 1 line
2.43.0