From 803ba74510df3400da4d5d02351f3858460cffda Mon Sep 17 00:00:00 2001 From: "Jose M. Guisado" Date: Tue, 2 May 2023 17:16:52 +0200 Subject: utils: rewrite ogExtendFs Drop subprocess call to bash function ogExtendFs. Use a native python solution with subprocess calls to the required underlying tools. Use get_filesystem_type to get the present filesystem from a partition and call the corresponding filesystem grow function. Filesystem specific functions are declared "_extend_{filesystem}" and should not be imported elsewhere. Each filesystem specific function wraps a subprocess call to the required underlying program: - NTFS filesystems: "ntfsresize -f [partition]" - ext4 filesystems: "resize2fs -f [partition]" Set NTFS related subprocess stdin to 'y' because human input cannot be unset with other ntfsresize parameters. --- src/utils/fs.py | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/src/utils/fs.py b/src/utils/fs.py index bffdb8c..a0c12d4 100644 --- a/src/utils/fs.py +++ b/src/utils/fs.py @@ -101,14 +101,21 @@ def ogReduceFs(disk, part): def ogExtendFs(disk, part): """ - Bash function 'ogExtendFs' wrapper + Grow filesystem of a partition. Supports ext4 and ntfs partitions. + Unsupported filesystem or invalid paths don't raise an exception, + instead this method logs a warning message and does nothing. """ - subprocess.run(f'ogMount {disk} {part}', - shell=True) - proc = subprocess.run(f'ogExtendFs {disk} {part}', - shell=True) - if proc.returncode != 0: - logging.warn(f'ogExtendFs exited with non zero code: {proc.returncode}') + partdev = get_partition_device(disk, part) + fstype = get_filesystem_type(partdev) + + umount(partdev) + if fstype == 'ext4': + _extend_resize2fs(partdev) + elif fstype == 'ntfs': + _extend_ntfsresize(partdev) + else: + logging.warn(f'Unable to grow filesystem at {partdev}. ' + f'Unsupported filesystem "{fstype}".') def mkfs(fs, disk, partition, label=None): @@ -220,3 +227,17 @@ def _reduce_ntfsresize(partdev): cmd_resize = shlex.split(f'ntfsresize -fs {new_size:.0f} {partdev}') with open('/tmp/command.log', 'ab', 0) as logfile: subprocess.run(cmd_resize, input='y', stderr=STDOUT, encoding='utf-8') + + +def _extend_resize2fs(partdev): + cmd_resize2fs = shlex.split(f'resize2fs -f {partdev}') + proc = subprocess.run(cmd_resize2fs) + if proc.returncode != 0: + raise RuntimeError(f'Error growing ext4 filesystem at {partdev}') + + +def _extend_ntfsresize(partdev): + cmd_ntfsresize = shlex.split(f'ntfsresize -f {partdev}') + proc = subprocess.run(cmd_resize2fs, input='y') + if proc.returncode != 0: + raise RuntimeError(f'Error growing ntfs filesystem at {partdev}') -- cgit v1.2.3-18-g5258