From bcbbe26573233f0f4f5adcac73185bd4bba3ad11 Mon Sep 17 00:00:00 2001 From: Alejandro Sirgo Rica Date: Mon, 19 Feb 2024 09:37:38 +0100 Subject: fs: improve value parsing from command output value extraction did not have error checking and was handled in a one-liner. The actual implementation expands the parsing logic and moves it into a function. --- src/utils/fs.py | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/src/utils/fs.py b/src/utils/fs.py index 5bc7956..9f9f98b 100644 --- a/src/utils/fs.py +++ b/src/utils/fs.py @@ -237,11 +237,28 @@ def _reduce_ntfsresize(partdev): # The first split operation leaves the wanted data at the second element of # the split ([1]). Finally do a second split with ' ' to get the data but # nothing else following it. - # - # In addition, increase by 10%+1K the reported shrink location on which the - # filesystem can be resized according to ntfsresize. - size = int(out_info.split('device size: ')[1].split(' ')[0]) - new_size = int(int(out_info.split('resize at ')[1].split(' ')[0])*1.1+1024) + def parse_ntfsresize(output_data, pattern): + data_split = output_data.split(pattern) + # If we fail to match pattern in the split then data_split will contain [output_data] + if len(data_split) == 1: + logging.error(f'nfsresize: failed to find: "{pattern}"') + raise ValueError(f'nfsresize: failed to find: "{pattern}"') + value_str = data_split[1].split(' ')[0] + + if not value_str.isdigit() or value_str.startswith('-'): + logging.error(f'nfsresize: failed to parse numeric value at "{pattern}"') + raise ValueError(f'nfsresize: failed to parse numeric value at "{pattern}"') + return int(value_str) + + try: + size = parse_ntfsresize(out_info, 'device size: ') + new_size = parse_ntfsresize(out_info, 'resize at ') + # Increase by 10%+1K the indicated reduction by which the file system + # can be resized according to ntfsresize. + new_size = int(new_size * 1.1 + 1024) + except ValueError: + return -1 + # Run ntfsresize with -n to to probe for the smallest size, this loop is # intentional. Acumulate size until ntfsresize in dry-run mode fails, then @@ -262,8 +279,13 @@ def _reduce_ntfsresize(partdev): if out_resize_dryrun.find('Needed relocations : ') == -1: break - extra_size = int(out_resize_dryrun.split('Needed relocations : ')[1].split(' ')[0])*1.1+1024 - new_size += int(extra_size) + try: + extra_size = parse_ntfsresize(out_resize_dryrun, 'Needed relocations : ') + # Add size padding + extra_size = int(extra_size * 1.1 + 1024) + new_size += extra_size + except ValueError: + return -1 if new_size < size: cmd_resize = shlex.split(f'ntfsresize -fs {new_size:.0f} {partdev}') -- cgit v1.2.3-18-g5258