refs #1527 add ogCreateGptPartitions
parent
bc16613939
commit
5e40504eff
|
@ -227,7 +227,7 @@ def ogFormatCache():
|
||||||
# Crear estructura básica.
|
# Crear estructura básica.
|
||||||
mntdir = ogMountCache()
|
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"
|
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)
|
os.makedirs (j, exist_ok=True)
|
||||||
|
|
||||||
# Incluir kernel e Initrd del ogLive
|
# Incluir kernel e Initrd del ogLive
|
||||||
|
|
|
@ -168,82 +168,83 @@ def ogCreatePartitions(*args):
|
||||||
#@note Requisitos: sfdisk, parted, partprobe, awk
|
#@note Requisitos: sfdisk, parted, partprobe, awk
|
||||||
#@todo Definir atributos (arranque, oculta) y tamaños en MB, GB, etc.
|
#@todo Definir atributos (arranque, oculta) y tamaños en MB, GB, etc.
|
||||||
#*/ ##
|
#*/ ##
|
||||||
def ogCreateGptPartitions(*args):
|
def ogCreateGptPartitions (disk, parts):
|
||||||
# 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
|
|
||||||
|
|
||||||
# Nº total de sectores, para evitar desbordamiento (evitar redondeo).
|
# Nº total de sectores, para evitar desbordamiento (evitar redondeo).
|
||||||
ND = args[0]
|
ND = disk
|
||||||
DISK = ogDiskToDev (ND)
|
DISK = ogDiskToDev (ND)
|
||||||
if DISK is None:
|
if not DISK: return None
|
||||||
return
|
|
||||||
|
|
||||||
# Se calcula el ultimo sector del disco (total de sectores usables)
|
# 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é.
|
# Se recalcula el nº de sectores del disco si existe partición de caché.
|
||||||
|
CACHESIZE = 0
|
||||||
CACHEPART = CacheLib.ogFindCache()
|
CACHEPART = CacheLib.ogFindCache()
|
||||||
if ND == CACHEPART.split()[0]:
|
if CACHEPART:
|
||||||
CACHESIZE = int(ogGetCacheSize()) * 2
|
cache_disk, cache_part = CACHEPART.split()
|
||||||
|
if ND == cache_disk:
|
||||||
|
CACHESIZE = int (CacheLib.ogGetCacheSize()) * 2
|
||||||
if CACHESIZE:
|
if CACHESIZE:
|
||||||
SECTORS -= CACHESIZE
|
SECTORS -= CACHESIZE
|
||||||
|
|
||||||
# Si el disco es GPT empieza en el sector 2048 por defecto, pero podria cambiarse
|
# 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
|
START = ALIGN
|
||||||
PART = 1
|
PART = 1
|
||||||
|
|
||||||
# Leer parámetros con definición de particionado.
|
# Leer parámetros con definición de particionado.
|
||||||
args = args[1:] # Shift
|
DELOPTIONS = []
|
||||||
while args:
|
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é.
|
# 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
|
PART += 1
|
||||||
|
|
||||||
# Leer formato de cada parámetro - Tipo:Tamaño
|
# Leer formato de cada parámetro - Tipo:Tamaño
|
||||||
TYPE = args[0].split(":")[0]
|
TYPE, SIZE = p.split (':')
|
||||||
SIZE = int(args[0].split(":")[1])
|
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).
|
# Error si la partición es extendida (no válida en discos GPT).
|
||||||
if TYPE == "EXTENDED":
|
if 'EXTENDED' == TYPE:
|
||||||
SystemLib.ogRaiseError(OG_ERR_PARTITION, "EXTENDED")
|
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, 'EXTENDED')
|
||||||
return
|
return None
|
||||||
|
|
||||||
# Comprobar si existe la particion actual, capturamos su tamaño para ver si cambio o no
|
# 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
|
# En sgdisk no se pueden redimensionar las particiones, es necesario borrarlas y volver a crealas
|
||||||
if PARTSIZE:
|
if PARTSIZE:
|
||||||
DELOPTIONS += f" -d{PART}"
|
DELOPTIONS.append (f'-d{PART}')
|
||||||
|
|
||||||
# Creamos la particion
|
# Creamos la particion
|
||||||
# Obtener identificador de tipo de partición válido.
|
# Obtener identificador de tipo de partición válido.
|
||||||
ID = ogTypeToId(TYPE, "GPT")
|
ID = ogTypeToId (TYPE, 'GPT')
|
||||||
if TYPE != "CACHE" and ID:
|
if 'CACHE' == TYPE or not ID:
|
||||||
OPTIONS += f" -n{PART}:{START}:+{SIZE} -t{PART}:{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
|
START += SIZE
|
||||||
|
|
||||||
# Error si se supera el nº total de sectores.
|
# Error si se supera el nº total de sectores.
|
||||||
if START > SECTORS:
|
if START > SECTORS:
|
||||||
SystemLib.ogRaiseError(OG_ERR_FORMAT, f"{START//2} > {SECTORS//2}")
|
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'{START//2} > {SECTORS//2}')
|
||||||
return
|
return None
|
||||||
|
|
||||||
PART += 1
|
PART += 1
|
||||||
args = args[1:]
|
|
||||||
|
|
||||||
# Desmontar los sistemas de archivos del disco antes de realizar las operaciones.
|
# Desmontar los sistemas de archivos del disco antes de realizar las operaciones.
|
||||||
ogUnmountAll(ND)
|
FileSystemLib.ogUnmountAll (ND)
|
||||||
if CACHESIZE:
|
if CACHESIZE:
|
||||||
CacheLib.ogUnmountCache()
|
CacheLib.ogUnmountCache()
|
||||||
|
|
||||||
|
@ -252,12 +253,12 @@ def ogCreateGptPartitions(*args):
|
||||||
|
|
||||||
# Definir particiones y notificar al kernel.
|
# Definir particiones y notificar al kernel.
|
||||||
# Borramos primero las particiones y luego creamos las nuevas
|
# Borramos primero las particiones y luego creamos las nuevas
|
||||||
subprocess.run(["sgdisk"] + DELOPTIONS.split() + OPTIONS.split() + [DISK], stderr=subprocess.DEVNULL)
|
subprocess.run (['sgdisk'] + DELOPTIONS + OPTIONS + [DISK])
|
||||||
subprocess.run(["partprobe", DISK], stderr=subprocess.DEVNULL)
|
subprocess.run (['partprobe', DISK])
|
||||||
|
|
||||||
if CACHESIZE:
|
if CACHESIZE: CacheLib.ogMountCache()
|
||||||
CacheLib.ogMountCache()
|
|
||||||
return 0
|
return True
|
||||||
|
|
||||||
|
|
||||||
#/**
|
#/**
|
||||||
|
@ -283,14 +284,14 @@ def ogCreatePartitionTable (disk, createptt=None):
|
||||||
if createptt == pttype:
|
if createptt == pttype:
|
||||||
if 'GPT' == pttype:
|
if 'GPT' == pttype:
|
||||||
try:
|
try:
|
||||||
result = subprocess.run (['sgdisk', '-p', DISK])
|
result = subprocess.run (['sgdisk', '-p', DISK], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
if result.returncode:
|
if result.returncode:
|
||||||
CREATE = 'GPT'
|
CREATE = 'GPT'
|
||||||
except subprocess.CalledProcessError:
|
except subprocess.CalledProcessError:
|
||||||
CREATE = 'GPT'
|
CREATE = 'GPT'
|
||||||
elif 'MSDOS' == pttype:
|
elif 'MSDOS' == pttype:
|
||||||
try:
|
try:
|
||||||
result = subprocess.run (['parted', '-s', DISK, 'print'])
|
result = subprocess.run (['parted', '-s', DISK, 'print'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
if result.returncode:
|
if result.returncode:
|
||||||
CREATE = 'MSDOS'
|
CREATE = 'MSDOS'
|
||||||
except subprocess.CalledProcessError:
|
except subprocess.CalledProcessError:
|
||||||
|
|
|
@ -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)
|
Loading…
Reference in New Issue