From 5e40504effa7ee4cf9bcab249744ce44a3d8541b Mon Sep 17 00:00:00 2001 From: Natalia Serrano Date: Mon, 17 Feb 2025 13:48:03 +0100 Subject: [PATCH] refs #1527 add ogCreateGptPartitions --- client/lib/engine/bin/CacheLib.py | 2 +- client/lib/engine/bin/DiskLib.py | 101 +++++++++--------- client/shared/functions/ogCreateGptPartitions | 23 ++++ 3 files changed, 75 insertions(+), 51 deletions(-) create mode 100755 client/shared/functions/ogCreateGptPartitions diff --git a/client/lib/engine/bin/CacheLib.py b/client/lib/engine/bin/CacheLib.py index 0d1a43b..e6f0659 100755 --- a/client/lib/engine/bin/CacheLib.py +++ b/client/lib/engine/bin/CacheLib.py @@ -227,7 +227,7 @@ def ogFormatCache(): # Crear estructura básica. mntdir = ogMountCache() j = '/'.join ([mntdir, ogGlobals.OGIMG]) ## os.path.join doesn't work: "If a segment […] is an absolute path, all previous segments are ignored" - print (f'cucu mntdir ({mntdir}) OGIMG ({ogGlobals.OGIMG}) j ({j})') + #print (f'cucu mntdir ({mntdir}) OGIMG ({ogGlobals.OGIMG}) j ({j})') os.makedirs (j, exist_ok=True) # Incluir kernel e Initrd del ogLive diff --git a/client/lib/engine/bin/DiskLib.py b/client/lib/engine/bin/DiskLib.py index d3bd286..21db54a 100755 --- a/client/lib/engine/bin/DiskLib.py +++ b/client/lib/engine/bin/DiskLib.py @@ -168,96 +168,97 @@ def ogCreatePartitions(*args): #@note Requisitos: sfdisk, parted, partprobe, awk #@todo Definir atributos (arranque, oculta) y tamaños en MB, GB, etc. #*/ ## -def ogCreateGptPartitions(*args): - # Variables locales - ND = DISK = PART = SECTORS = ALIGN = START = SIZE = TYPE = CACHEPART = CACHESIZE = DELOPTIONS = OPTIONS = None - - # Si se solicita, mostrar ayuda. - if len(args) == 1 and args[0] == "help": - SystemLib.ogHelp('ogCreateGptPartitions', 'ogCreateGptPartitions int_ndisk str_parttype:int_partsize ...', - 'ogCreateGptPartitions 1 NTFS:10000000 EXT3:5000000 LINUX-SWAP:1000000') - return - - # Error si no se reciben menos de 2 parámetros. - if len(args) < 2: - SystemLib.ogRaiseError(OG_ERR_FORMAT) - return - +def ogCreateGptPartitions (disk, parts): # Nº total de sectores, para evitar desbordamiento (evitar redondeo). - ND = args[0] - DISK = ogDiskToDev(ND) - if DISK is None: - return + ND = disk + DISK = ogDiskToDev (ND) + if not DISK: return None # Se calcula el ultimo sector del disco (total de sectores usables) - SECTORS = ogGetLastSector(ND) + SECTORS = ogGetLastSector (disk) # Se recalcula el nº de sectores del disco si existe partición de caché. + CACHESIZE = 0 CACHEPART = CacheLib.ogFindCache() - if ND == CACHEPART.split()[0]: - CACHESIZE = int(ogGetCacheSize()) * 2 - if CACHESIZE: - SECTORS -= CACHESIZE + if CACHEPART: + cache_disk, cache_part = CACHEPART.split() + if ND == cache_disk: + CACHESIZE = int (CacheLib.ogGetCacheSize()) * 2 + if CACHESIZE: + SECTORS -= CACHESIZE # Si el disco es GPT empieza en el sector 2048 por defecto, pero podria cambiarse - ALIGN = subprocess.getoutput(f"sgdisk -D {DISK} 2>/dev/null") + ALIGN = int (subprocess.run (['sgdisk', '-D', DISK], capture_output=True, text=True).stdout) START = ALIGN PART = 1 # Leer parámetros con definición de particionado. - args = args[1:] # Shift - while args: + DELOPTIONS = [] + OPTIONS = [] + for p in parts: # Si PART es la cache, nos la saltamos y seguimos con el siguiente numero para conservar los datos de la partición de caché. - if f"{ND} {PART}" == CACHEPART and CACHESIZE: + if f'{ND} {PART}' == CACHEPART and CACHESIZE: PART += 1 # Leer formato de cada parámetro - Tipo:Tamaño - TYPE = args[0].split(":")[0] - SIZE = int(args[0].split(":")[1]) + TYPE, SIZE = p.split (':') + try: + SIZE = int (SIZE) + except ValueError: + SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, SIZE) + return None # Error si la partición es extendida (no válida en discos GPT). - if TYPE == "EXTENDED": - SystemLib.ogRaiseError(OG_ERR_PARTITION, "EXTENDED") - return + if 'EXTENDED' == TYPE: + SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, 'EXTENDED') + return None # Comprobar si existe la particion actual, capturamos su tamaño para ver si cambio o no - PARTSIZE = ogGetPartitionSize(ND, PART) + PARTSIZE = ogGetPartitionSize (ND, PART) # En sgdisk no se pueden redimensionar las particiones, es necesario borrarlas y volver a crealas if PARTSIZE: - DELOPTIONS += f" -d{PART}" + DELOPTIONS.append (f'-d{PART}') # Creamos la particion # Obtener identificador de tipo de partición válido. - ID = ogTypeToId(TYPE, "GPT") - if TYPE != "CACHE" and ID: - OPTIONS += f" -n{PART}:{START}:+{SIZE} -t{PART}:{ID} " + ID = ogTypeToId (TYPE, 'GPT') + if 'CACHE' == TYPE or not ID: + SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, TYPE) + return None + # Comprobar tamaño numérico y convertir en sectores de 512 B. + SIZE = 2 * SIZE + # SIZE debe ser múltiplo de ALIGN, si no gdisk lo mueve automáticamente. + DIV = SIZE // ALIGN + SIZE = DIV * ALIGN + # En el caso de que la partición sea EMPTY no se crea nada + if 'EMPTY' != TYPE: + OPTIONS += [f'-n{PART}:{START}:+{SIZE}', f'-t{PART}:{ID}'] START += SIZE # Error si se supera el nº total de sectores. if START > SECTORS: - SystemLib.ogRaiseError(OG_ERR_FORMAT, f"{START//2} > {SECTORS//2}") - return + SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'{START//2} > {SECTORS//2}') + return None PART += 1 - args = args[1:] # Desmontar los sistemas de archivos del disco antes de realizar las operaciones. - ogUnmountAll(ND) + FileSystemLib.ogUnmountAll (ND) if CACHESIZE: CacheLib.ogUnmountCache() # Si la tabla de particiones no es valida, volver a generarla. - ogCreatePartitionTable(ND) + ogCreatePartitionTable (ND) # Definir particiones y notificar al kernel. # Borramos primero las particiones y luego creamos las nuevas - subprocess.run(["sgdisk"] + DELOPTIONS.split() + OPTIONS.split() + [DISK], stderr=subprocess.DEVNULL) - subprocess.run(["partprobe", DISK], stderr=subprocess.DEVNULL) + subprocess.run (['sgdisk'] + DELOPTIONS + OPTIONS + [DISK]) + subprocess.run (['partprobe', DISK]) - if CACHESIZE: - CacheLib.ogMountCache() - return 0 + if CACHESIZE: CacheLib.ogMountCache() + + return True #/** @@ -283,14 +284,14 @@ def ogCreatePartitionTable (disk, createptt=None): if createptt == pttype: if 'GPT' == pttype: try: - result = subprocess.run (['sgdisk', '-p', DISK]) + result = subprocess.run (['sgdisk', '-p', DISK], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) if result.returncode: CREATE = 'GPT' except subprocess.CalledProcessError: CREATE = 'GPT' elif 'MSDOS' == pttype: try: - result = subprocess.run (['parted', '-s', DISK, 'print']) + result = subprocess.run (['parted', '-s', DISK, 'print'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) if result.returncode: CREATE = 'MSDOS' except subprocess.CalledProcessError: diff --git a/client/shared/functions/ogCreateGptPartitions b/client/shared/functions/ogCreateGptPartitions new file mode 100755 index 0000000..0259325 --- /dev/null +++ b/client/shared/functions/ogCreateGptPartitions @@ -0,0 +1,23 @@ +#!/usr/bin/python3 + +import sys +import argparse +from SystemLib import ogHelp +from DiskLib import ogCreateGptPartitions + +if 2 == len (sys.argv) and 'help' == sys.argv[1]: + #parser.print_help() sale en inglés aunque la locale indique otra cosa + ogHelp ('ogCreateGptPartitions', 'ogCreateGptPartitions int_ndisk str_parttype:int_partsize ...', ['ogCreateGptPartitions 1 NTFS:10000000 EXT3:5000000 LINUX-SWAP:1000000']) + sys.exit (0) + +parser = argparse.ArgumentParser (add_help=False) +parser.add_argument ('disk') +parser.add_argument ('parts', nargs='+') +args = parser.parse_args() + +ret = ogCreateGptPartitions (args.disk, args.parts) + +if ret is not None: + if ret == True: sys.exit (0) + elif ret == False: sys.exit (1) + else: print (ret)