source: client/engine/FileSystemLib.py @ f160ff2

test-python-scriptsticket-693
Last change on this file since f160ff2 was 7260bdc2, checked in by Antonio Emmanuel Guerrero Silva <aguerrero@…>, 9 months ago

refs #585 Libraries convert to Python3

  • Property mode set to 100644
File size: 27.6 KB
Line 
1import subprocess
2import sys
3
4from engine.SystemLib import *
5from engine.DiskLib import *
6from engine.CacheLib import *
7
8def ogCheckFs(int_ndisk, int_nfilesys):
9    # Si se solicita, mostrar ayuda.
10    if int_ndisk == "help":
11        ogHelp("ogCheckFs", "ogCheckFs int_ndisk int_nfilesys", "ogCheckFs 1 1")
12        return
13
14    # Error si no se reciben 2 parámetros.
15    if len(sys.argv) != 3:
16        ogRaiseError(OG_ERR_FORMAT)
17        return
18
19    # Obtener partición.
20    PART = ogDiskToDev(int_ndisk, int_nfilesys)
21    if not PART:
22        return
23
24    TYPE = ogGetFsType(int_ndisk, int_nfilesys)
25    if TYPE == "EXT[234]" or TYPE == "CACHE":
26        PROG = "e2fsck"
27        PARAMS = "-y"
28        CODES = [1, 2]
29    elif TYPE == "BTRFS":
30        PROG = "btrfsck"
31        CODES = [1]
32    elif TYPE == "REISERFS":
33        PROG = "fsck.reiserfs"
34        PARAMS = "<<<\"Yes\""
35        CODES = [1, 2]
36    elif TYPE == "REISER4":
37        PROG = "fsck.reiser4"
38        PARAMS = "-ay"
39    elif TYPE == "JFS":
40        PROG = "fsck.jfs"
41        CODES = [1, 2]
42    elif TYPE == "XFS":
43        PROG = "xfs_repair"
44    elif TYPE == "F2FS":
45        PROG = "fsck.f2fs"
46    elif TYPE == "NTFS":
47        PROG = "ntfsfix"
48    elif TYPE == "EXFAT":
49        PROG = "fsck.exfat"
50    elif TYPE == "FAT32":
51        PROG = "dosfsck"
52        PARAMS = "-a"
53        CODES = [1]
54    elif TYPE == "FAT16":
55        PROG = "dosfsck"
56        PARAMS = "-a"
57        CODES = [1]
58    elif TYPE == "FAT12":
59        PROG = "dosfsck"
60        PARAMS = "-a"
61        CODES = [1]
62    elif TYPE == "HFS":
63        PROG = "fsck.hfs"
64        PARAMS = "-f"
65    elif TYPE == "HFSPLUS":
66        PROG = "fsck.hfs"
67        PARAMS = "-f"
68    elif TYPE == "UFS":
69        PROG = "fsck.ufs"
70    elif TYPE == "ZFS":
71        PROG = "fsck.zfs"
72    else:
73        ogRaiseError(OG_ERR_PARTITION, f"{int_ndisk}, {int_nfilesys}")
74        return
75
76    # Error si el sistema de archivos esta montado o bloqueado.
77    ogUnmount(int_ndisk, int_nfilesys)
78    if ogIsMounted(int_ndisk, int_nfilesys):
79        ogRaiseError(OG_ERR_PARTITION, f"{int_ndisk} {int_nfilesys}")
80        return
81    if ogIsLocked(int_ndisk, int_nfilesys):
82        ogRaiseError(OG_ERR_LOCKED, f"{int_ndisk} {int_nfilesys}")
83        return
84
85    # Comprobar en modo uso exclusivo.
86    ogLock(int_ndisk, int_nfilesys)
87    try:
88        result = subprocess.run([PROG, PARAMS, PART], capture_output=True)
89        ERRCODE = result.returncode
90    except FileNotFoundError:
91        ogRaiseError(OG_ERR_NOTEXEC, PROG)
92        ERRCODE = OG_ERR_NOTEXEC
93    except:
94        ogRaiseError(OG_ERR_PARTITION, f"{int_ndisk} {int_nfilesys}")
95        ERRCODE = OG_ERR_PARTITION
96
97    ogUnlock(int_ndisk, int_nfilesys)
98    return ERRCODE
99
100def ogExtendFs():
101    # Si se solicita, mostrar ayuda.
102    if len(sys.argv) == 2 and sys.argv[1] == "help":
103        ogHelp("ogExtendFs", "ogExtendFs int_ndisk int_nfilesys", "ogExtendFs 1 1")
104        return
105
106    # Error si no se reciben 2 parámetros.
107    if len(sys.argv) != 3:
108        ogRaiseError(OG_ERR_FORMAT)
109        return
110
111    # Obtener partición.
112    PART = ogDiskToDev(int(sys.argv[1]), int(sys.argv[2]))
113    if not PART:
114        return
115
116    # Redimensionar al tamaño máximo según el tipo de partición.
117    TYPE = ogGetFsType(int(sys.argv[1]), int(sys.argv[2]))
118    if TYPE == "EXT[234]":
119        PROG = "resize2fs"
120        PARAMS = "-f"
121    elif TYPE == "BTRFS":
122        PROG = "btrfs"
123        PARAMS = "filesystem resize max"
124        DOMOUNT = True  # Debe estar montado.
125    elif TYPE == "REISERFS" or TYPE == "REISER4":
126        PROG = "resize_reiserfs"
127        PARAMS = "-f"
128    elif TYPE == "F2FS" or TYPE == "JFS" or TYPE == "NILFS2" or TYPE == "XFS" or TYPE == "EXFAT" or TYPE == "FAT32" or TYPE == "FAT16" or TYPE == "HFS" or TYPE == "HFSPLUS" or TYPE == "UFS":
129        return  # No se reduce (por el momento).
130    elif TYPE == "NTFS":
131        PROG = "ntfsresize"
132        PARAMS = "<<<\"y\" -f"
133    else:
134        ogRaiseError(OG_ERR_PARTITION, f"{int(sys.argv[1])} {int(sys.argv[2])} {TYPE}")
135        return
136
137    # Salida normal si no se va a aplicar la operación.
138    if not PROG:
139        return
140
141    # Error si el sistema de archivos no se queda en el estado de montaje adecuado.
142    if DOMOUNT:
143        PART = ogMount(int(sys.argv[1]), int(sys.argv[2]))
144        if not PART:
145            return
146    else:
147        ogUnmount(int(sys.argv[1]), int(sys.argv[2]))
148        if ogIsMounted(int(sys.argv[1]), int(sys.argv[2])):
149            ogRaiseError(OG_ERR_PARTITION, f"{int(sys.argv[1])} {int(sys.argv[2])}")
150            return
151
152    # Error si el sistema de archivos está bloqueado.
153    if ogIsLocked(int(sys.argv[1]), int(sys.argv[2])):
154        ogRaiseError(OG_ERR_LOCKED, f"{int(sys.argv[1])} {int(sys.argv[2])}")
155        return
156
157    # Redimensionar en modo uso exclusivo.
158    ogLock(int(sys.argv[1]), int(sys.argv[2]))
159    try:
160        subprocess.run([PROG, PARAMS, PART], capture_output=True)
161        ERRCODE = 0
162    except FileNotFoundError:
163        ogRaiseError(OG_ERR_NOTEXEC, PROG)
164        ERRCODE = OG_ERR_NOTEXEC
165    except:
166        ogRaiseError(OG_ERR_PARTITION, f"{int(sys.argv[1])} {int(sys.argv[2])}")
167        ERRCODE = OG_ERR_PARTITION
168
169    ogUnlock(int(sys.argv[1]), int(sys.argv[2]))
170    return ERRCODE
171
172def ogFormat(int_ndisk, int_nfilesys):
173    if int_nfilesys.lower() == "cache":
174        ogFormatCache()
175    else:
176        ogFormatFs(int_ndisk, int_nfilesys)
177
178def ogFormatFs(int_ndisk, int_nfilesys, str_label=None):
179    # Si se solicita, mostrar ayuda.
180    if str_label == "help":
181        ogHelp("ogFormatFs", "ogFormatFs int_ndisk int_nfilesys [str_label]", "ogFormatFs 1 1", "ogFormatFs 1 1 EXT4", "ogFormatFs 1 1 \"DATA\"", "ogFormatFs 1 1 EXT4 \"DATA\"")
182        return
183
184    # Error si no se reciben entre 2 y 4 parámetros.
185    if not (2 <= len(sys.argv) <= 4):
186        ogRaiseError(OG_ERR_FORMAT)
187        return
188
189    # Obtener fichero de dispositivo.
190    PART = ogDiskToDev(int_ndisk, int_nfilesys)
191    if not PART:
192        return
193
194    # Error si la partición está montada o bloqueada.
195    if ogIsMounted(int_ndisk, int_nfilesys):
196        ogRaiseError(OG_ERR_DONTFORMAT, f"{MSG_MOUNT}: {int_ndisk} {int_nfilesys}")
197        return
198    if ogIsLocked(int_ndisk, int_nfilesys):
199        ogRaiseError(OG_ERR_LOCKED, f"{int_ndisk} {int_nfilesys}")
200        return
201
202    # Si no se indica el tipo de sistema de archivos, intentar obtenerlo.
203    TYPE = ogGetFsType(int_ndisk, int_nfilesys)
204    if not TYPE:
205        TYPE = sys.argv[3]
206
207    # Error, si no especifica el tipo de sistema de archivos a formatear.
208    if not TYPE:
209        ogRaiseError(OG_ERR_FORMAT, f"{int_ndisk} {int_nfilesys} ...")
210        return
211
212    # Elegir tipo de formato.
213    if TYPE == "EXT2":
214        PROG = "mkfs.ext2"
215        PARAMS = "-F"
216    elif TYPE == "EXT3":
217        PROG = "mkfs.ext3"
218        PARAMS = "-F"
219    elif TYPE == "EXT4":
220        PROG = "mkfs.ext4"
221        PARAMS = "-F"
222    elif TYPE == "BTRFS":
223        PROG = "mkfs.btrfs"
224        PARAMS = "-f"
225    elif TYPE == "REISERFS":
226        PROG = "mkfs.reiserfs"
227        PARAMS = "-f"
228        LABELPARAM = "-l"
229    elif TYPE == "REISER4":
230        PROG = "mkfs.reiser4"
231        PARAMS = "-f <<<\"y\""
232    elif TYPE == "XFS":
233        PROG = "mkfs.xfs"
234        PARAMS = "-f"
235    elif TYPE == "JFS":
236        PROG = "mkfs.jfs"
237        PARAMS = "<<<\"y\""
238    elif TYPE == "F2FS":
239        PROG = "mkfs.f2fs"
240        LABELPARAM = "-l"
241    elif TYPE == "NILFS2":
242        PROG = "mkfs.nilfs2"
243        PARAMS = "-f"
244    elif TYPE == "LINUX-SWAP":
245        PROG = "mkswap"
246    elif TYPE == "NTFS":
247        PROG = "mkntfs"
248        PARAMS = "-f"
249    elif TYPE == "EXFAT":
250        PROG = "mkfs.exfat"
251        LABELPARAM = "-n"
252    elif TYPE == "FAT32":
253        PROG = "mkdosfs"
254        PARAMS = "-F 32"
255        LABELPARAM = "-n"
256    elif TYPE == "FAT16":
257        PROG = "mkdosfs"
258        PARAMS = "-F 16"
259        LABELPARAM = "-n"
260    elif TYPE == "FAT12":
261        PROG = "mkdosfs"
262        PARAMS = "-F 12"
263        LABELPARAM = "-n"
264    elif TYPE == "HFS":
265        PROG = "mkfs.hfs"
266    elif TYPE == "HFSPLUS":
267        PROG = "mkfs.hfsplus"
268        LABELPARAM = "-v"
269    elif TYPE == "UFS":
270        PROG = "mkfs.ufs"
271        PARAMS = "-O 2"
272    else:
273        ogRaiseError(OG_ERR_PARTITION, f"{int_ndisk} {int_nfilesys} {TYPE}")
274        return
275
276    # Etiquetas de particion.
277    if not str_label:
278        if sys.argv[4] == "CACHE":
279            ogRaiseError(OG_ERR_FORMAT, f"{MSG_RESERVEDVALUE}: CACHE")
280            return
281        if len(sys.argv) >= 4:
282            PARAMS = f"{PARAMS} {LABELPARAM or '-L'} {sys.argv[4]}"
283    else:
284        PARAMS = f"{PARAMS} {LABELPARAM or '-L'} {str_label}"
285
286    # Formatear en modo uso exclusivo (desmontar siempre).
287    ogLock(int_ndisk, int_nfilesys)
288    try:
289        subprocess.run([PROG, PARAMS, PART], capture_output=True)
290        ERRCODE = 0
291    except FileNotFoundError:
292        ogRaiseError(OG_ERR_NOTEXEC, PROG)
293        ERRCODE = OG_ERR_NOTEXEC
294    except:
295        ogRaiseError(OG_ERR_PARTITION, f"{int_ndisk} {int_nfilesys}")
296        ERRCODE = OG_ERR_PARTITION
297
298    ogUnlock(int_ndisk, int_nfilesys)
299    return ERRCODE
300
301def ogGetFsSize(int_ndisk, int_npartition, str_unit=None):
302    # Si se solicita, mostrar ayuda.
303    if str_unit == "help":
304        ogHelp("ogGetFsSize", "ogGetFsSize int_ndisk int_npartition [str_unit]", "ogGetFsSize 1 1", "ogGetFsSize 1 1 KB")
305        return
306
307    # Error si no se reciben 2 o 3 parámetros.
308    if not (2 <= len(sys.argv) <= 3):
309        ogRaiseError(OG_ERR_FORMAT)
310        return
311
312    # Obtener unidad y factor de medida.
313    UNIT = str_unit or "KB"
314    FACTOR = 1
315    if UNIT.upper() == "MB":
316        FACTOR = 1024
317    elif UNIT.upper() == "GB":
318        FACTOR = 1024 * 1024
319    elif UNIT.upper() == "TB":
320        FACTOR = 1024 * 1024 * 1024
321    elif UNIT.upper() != "KB":
322        ogRaiseError(OG_ERR_FORMAT, f"{UNIT} != {{ KB, MB, GB, TB }}")
323        return
324
325    # Obtener el tamaño del sistema de archivo (si no está formateado; tamaño = 0).
326    MNTDIR = ogMount(int_ndisk, int_npartition)
327    if MNTDIR:
328        result = subprocess.run(["df", "-BK", MNTDIR], capture_output=True, text=True)
329        VALUE = result.stdout.split("\n")[1].split()[1]
330        SIZE = float(VALUE) / FACTOR
331    else:
332        SIZE = 0
333
334    # Devolver el tamaño (quitar decimales si son 0).
335    return int(SIZE) if SIZE.is_integer() else SIZE
336
337def ogGetFsType(int_ndisk, int_nfilesys):
338    # Si se solicita, mostrar ayuda.
339    if len(sys.argv) == 3 and sys.argv[2] == "help":
340        ogHelp("ogGetFsType", "ogGetFsType int_ndisk int_nfilesys", "ogGetFsType 1 1")
341        return
342
343    # Error si no se reciben 2 parámetros.
344    if len(sys.argv) != 3:
345        ogRaiseError(OG_ERR_FORMAT)
346        return
347
348    # Obtener partición.
349    PART = ogDiskToDev(int_ndisk, int_nfilesys)
350    if not PART:
351        return
352
353    # Detectar tipo de sistema de archivo (independientemente del tipo de partición).
354    if PART.startswith("/"):
355        result = subprocess.run(["blkid", "-o", "export", PART], capture_output=True, text=True)
356        TYPE = ""
357        for line in result.stdout.split("\n"):
358            if line.startswith("TYPE="):
359                TYPE = line.split("=")[1].upper()
360                break
361    else:
362        subprocess.run(["zfs", "mount", PART], stderr=subprocess.DEVNULL)
363        result = subprocess.run(["mount"], capture_output=True, text=True)
364        TYPE = ""
365        for line in result.stdout.split("\n"):
366            if line.startswith(PART):
367                TYPE = line.split()[4].upper()
368                break
369
370    # Componer valores correctos.
371    if TYPE == "EXT4":
372        if f"{int_ndisk} {int_nfilesys}" == ogFindCache():
373            if ogIsFormated(int_ndisk, int_nfilesys):
374                TYPE = "CACHE"
375    elif TYPE == "VFAT":
376        result = subprocess.run(["blkid", "-po", "export", PART], capture_output=True, text=True)
377        for line in result.stdout.split("\n"):
378            if line.startswith("VERSION="):
379                TYPE = line.split("=")[1].upper()
380                break
381    elif TYPE == "SWAP":
382        TYPE = "LINUX-SWAP"
383    elif TYPE.startswith("LVM"):
384        TYPE = "LINUX-LVM"
385    elif "RAID" in TYPE:
386        TYPE = "LINUX-RAID"
387    elif TYPE == "ZFS_MEMBER":
388        TYPE = "ZVOL"
389    elif "_MEMBER" in TYPE:
390        TYPE = TYPE.replace("_MEMBER", "")
391
392    if TYPE:
393        return TYPE
394
395def ogGetMountPoint(int_ndisk, int_nfilesys):
396    # Si se solicita, mostrar ayuda.
397    if len(sys.argv) == 3 and sys.argv[2] == "help":
398        ogHelp("ogGetMountPoint", "ogGetMountPoint int_ndisk int_nfilesys", "ogGetMountPoint 1 1")
399        return
400
401    # Error si no se reciben 2 parámetros.
402    if len(sys.argv) != 3:
403        ogRaiseError(OG_ERR_FORMAT)
404        return
405
406    # Obtener partición.
407    PART = ogDiskToDev(int_ndisk, int_nfilesys)
408    if not PART:
409        return
410
411    # Devolver punto de montaje.
412    result = subprocess.run(["findmnt", "-n", "-o", "TARGET", PART], capture_output=True, text=True)
413    return result.stdout.strip()
414
415def ogIsFormated(int_ndisk, int_nfilesys):
416    # Si se solicita, mostrar ayuda.
417    if len(sys.argv) == 3 and sys.argv[2] == "help":
418        ogHelp("ogIsFormated", "ogIsFormated int_ndisk int_nfilesys", "ogIsFormated 1 1")
419        return
420
421    # Error si no se reciben 2 parámetros.
422    if len(sys.argv) != 3:
423        ogRaiseError(OG_ERR_FORMAT)
424        return
425
426    # Obtener partición.
427    PART = ogDiskToDev(int_ndisk, int_nfilesys)
428    if not PART:
429        return
430
431    # Revisar tipo de sistema de archivos.
432    if PART.startswith("/"):
433        result = subprocess.run(["blkid", "-s", "TYPE", PART], capture_output=True, text=True)
434        return bool(result.stdout.strip())
435    else:
436        result = subprocess.run(["zfs", "list", "-Hp", "-o", "canmount", PART], capture_output=True, text=True)
437        return result.stdout.strip() == "on"
438
439def ogIsLocked(int_ndisk, int_nfilesys):
440    return ogIsPartitionLocked(int_ndisk, int_nfilesys)
441
442def ogIsPartitionLocked(int_ndisk, int_npartition):
443    # Si se solicita, mostrar ayuda.
444    if len(sys.argv) == 3 and sys.argv[2] == "help":
445        ogHelp("ogIsPartitionLocked", "ogIsPartitionLocked int_ndisk int_npartition", "ogIsPartitionLocked 1 1")
446        return
447
448    # Error si no se reciben 2 parámetros.
449    if len(sys.argv) != 3:
450        ogRaiseError(OG_ERR_FORMAT)
451        return
452
453    # Obtener partición.
454    PART = ogDiskToDev(int_ndisk, int_npartition)
455    if not PART:
456        return
457
458    # Comprobar existencia de fichero de bloqueo de la partición o de su disco.
459    LOCKDISK = f"/var/lock/lock{ogDiskToDev(int_ndisk).replace('/', '-')}"
460    LOCKPART = f"/var/lock/lock{PART.replace('/', '-')}"
461    return os.path.isfile(LOCKDISK) or os.path.isfile(LOCKPART)
462
463def ogIsMounted(int_ndisk, int_nfilesys):
464    # Si se solicita, mostrar ayuda.
465    if len(sys.argv) == 3 and sys.argv[2] == "help":
466        ogHelp("ogIsMounted", "ogIsMounted int_ndisk int_nfilesys", "ogIsMounted 1 1")
467        return
468
469    # Error si no se reciben 2 parámetros.
470    if len(sys.argv) != 3:
471        ogRaiseError(OG_ERR_FORMAT)
472        return
473
474    # Obtener punto de montaje.
475    MNTDIR = ogGetMountPoint(int_ndisk, int_nfilesys)
476    return bool(MNTDIR)
477
478def ogIsReadonly(int_ndisk, int_nfilesys):
479    # Si se solicita, mostrar ayuda.
480    if len(sys.argv) == 3 and sys.argv[2] == "help":
481        ogHelp("ogIsReadonly", "ogIsReadonly int_ndisk int_nfilesys", "ogIsReadonly 1 1")
482        return
483
484    # Error si no se reciben 2 parámetros.
485    if len(sys.argv) != 3:
486        ogRaiseError(OG_ERR_FORMAT)
487        return
488
489    # Obtener partición.
490    PART = ogDiskToDev(int_ndisk, int_nfilesys)
491    if not PART:
492        return
493
494    # Comprobar si la partición está montada en modo de solo lectura.
495    result = subprocess.run(["findmnt", "-n", "-o", "OPTIONS", PART], capture_output=True, text=True)
496    options = result.stdout.strip().split(",")
497    return "ro" in options
498
499def ogIsWritable(int_ndisk, int_nfilesys):
500    # Si se solicita, mostrar ayuda.
501    if len(sys.argv) == 3 and sys.argv[2] == "help":
502        ogHelp("ogIsWritable", "ogIsWritable int_ndisk int_nfilesys", "ogIsWritable 1 1")
503        return
504
505    # Error si no se reciben 2 parámetros.
506    if len(sys.argv) != 3:
507        ogRaiseError(OG_ERR_FORMAT)
508        return
509
510    # Obtener partición.
511    PART = ogDiskToDev(int_ndisk, int_nfilesys)
512    if not PART:
513        return
514
515    # Comprobar si la partición está montada en modo de escritura.
516    result = subprocess.run(["findmnt", "-n", "-o", "OPTIONS", PART], capture_output=True, text=True)
517    options = result.stdout.strip().split(",")
518    return "rw" in options
519
520def ogLock(int_ndisk, int_nfilesys):
521    ogLockPartition(int_ndisk, int_nfilesys)
522
523def ogLockPartition(int_ndisk, int_npartition):
524    # Si se solicita, mostrar ayuda.
525    if len(sys.argv) == 3 and sys.argv[2] == "help":
526        ogHelp("ogLockPartition", "ogLockPartition int_ndisk int_npartition", "ogLockPartition 1 1")
527        return
528
529    # Error si no se reciben 2 parámetros.
530    if len(sys.argv) != 3:
531        ogRaiseError(OG_ERR_FORMAT)
532        return
533
534    # Obtener partición.
535    PART = ogDiskToDev(int_ndisk, int_npartition)
536    if not PART:
537        return
538
539    # Crear archivo de bloqueo exclusivo.
540    LOCKFILE = f"/var/lock/lock{PART.replace('/', '-')}"
541    open(LOCKFILE, 'a').close()
542
543def ogMount():
544    args = sys.argv[2:]
545    if args == ["CACHE"] or args == ["cache"]:
546        ogMountCache()
547    elif args == ["CDROM"] or args == ["cdrom"]:
548        ogMountCdrom()
549    else:
550        ogMountFs(*args)
551
552def ogMountFirstFs(int_ndisk):
553    # Obtener número de particiones del disco.
554    NPARTS = ogGetPartitionsNumber(int_ndisk)
555    for PART in range(1, NPARTS + 1):
556        MNTDIR = ogMount(int_ndisk, PART)
557        if MNTDIR:
558            return MNTDIR
559    ogRaiseError(OG_ERR_NOTFOUND, int_ndisk)
560    return OG_ERR_NOTFOUND
561
562def ogMountFs(int_ndisk, int_nfilesys):
563    FUNCNAME = ogExecAndLog.__name__
564    # Si se solicita, mostrar ayuda.
565    if len(sys.argv) == 3 and sys.argv[2] == "help":
566        ogHelp(f"{FUNCNAME}", "{FUNCNAME} int_ndisk int_nfilesys", "{FUNCNAME} 1 1  =>  /mnt/sda1")
567        return
568
569    # Error si no se reciben 2 parámetros.
570    if len(sys.argv) != 3:
571        ogRaiseError(OG_ERR_FORMAT)
572        return
573
574    # Obtener partición.
575    PART = ogDiskToDev(int_ndisk, int_nfilesys)
576    if not PART:
577        return
578
579    # Comprobar si el sistema de archivos ya está montada.
580    MNTDIR = ogGetMountPoint(int_ndisk, int_nfilesys)
581    # Si no, montarlo en un directorio de sistema.
582    if not MNTDIR:
583        # Error si la particion esta bloqueada.
584        if ogIsLocked(int_ndisk, int_nfilesys):
585            ogRaiseError(OG_ERR_LOCKED, f"{MSG_PARTITION}, {int_ndisk} {int_nfilesys}")
586            return
587
588        # El camino de un dispositivo normal comienza por el carácter "/".
589        if PART.startswith("/"):
590            # Crear punto de montaje o enlace simbólico para caché local.
591            MNTDIR = PART.replace("/dev", "/mnt")
592            DEBUG = "no"
593            if f"{int_ndisk} {int_nfilesys}" == ogFindCache() and OGCAC:
594                os.makedirs(OGCAC, exist_ok=True)
595                os.symlink(OGCAC, MNTDIR)
596            else:
597                os.makedirs(MNTDIR, exist_ok=True)
598            del DEBUG
599
600            # Montar sistema de archivos.
601            try:
602                subprocess.run(["mount", PART, MNTDIR], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
603            except subprocess.CalledProcessError:
604                try:
605                    subprocess.run(["mount", PART, MNTDIR, "-o", "force,remove_hiberfile"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
606                except subprocess.CalledProcessError:
607                    ogRaiseError(OG_ERR_PARTITION, f"{int_ndisk}, {int_nfilesys}")
608                    return
609            # Aviso de montaje de solo lectura.
610            if ogIsReadonly(int_ndisk, int_nfilesys):
611                ogEcho("warning", f"{FUNCNAME}: {MSG_MOUNTREADONLY}: \"{int_ndisk}, {int_nfilesys}\"")
612        else:
613            # Montar sistema de archivos ZFS (un ZPOOL no comienza por "/").
614            try:
615                subprocess.run(["zfs", "mount", PART], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
616            except subprocess.CalledProcessError:
617                pass
618
619    return MNTDIR
620
621def ogMountCdrom():
622    DEV = "/dev/cdrom"  # Por defecto
623    MNTDIR = subprocess.run(["mount", "-l", "-t", "iso9660", DEV], capture_output=True, text=True)
624    MNTDIR = MNTDIR.stdout.strip().split(" ")[2]
625    if not MNTDIR:
626        MNTDIR = DEV.replace("/dev", "/mnt")
627        os.makedirs(MNTDIR, exist_ok=True)
628        try:
629            subprocess.run(["mount", "-t", "iso9660", DEV, MNTDIR], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
630        except subprocess.CalledProcessError:
631            ogRaiseError(OG_ERR_PARTITION, "cdrom")
632            return
633    return MNTDIR
634
635def ogReduceFs(int_ndisk, int_nfilesys):
636    # Si se solicita, mostrar ayuda.
637    if len(sys.argv) == 3 and sys.argv[2] == "help":
638        ogHelp("ogReduceFs", "ogReduceFs int_ndisk int_nfilesys", "ogReduceFs 1 1")
639        return
640
641    # Error si no se reciben 2 parámetros.
642    if len(sys.argv) != 3:
643        ogRaiseError(OG_ERR_FORMAT)
644        return
645
646    # Obtener partición.
647    PART = ogDiskToDev(int_ndisk, int_nfilesys)
648    if not PART:
649        return
650
651    # Redimensionar según el tipo de partición.
652    TYPE = ogGetFsType(int_ndisk, int_nfilesys)
653    if TYPE == "EXT4":
654        ogUnmount(int_ndisk, int_nfilesys)
655        subprocess.run(["resize2fs", "-fpM", PART], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
656    elif TYPE == "BTRFS":
657        MNTDIR = ogMount(int_ndisk, int_nfilesys)
658        SIZE = subprocess.run(["btrfs", "filesystem", "show", MNTDIR], capture_output=True, text=True)
659        SIZE = SIZE.stdout.strip().split(" ")[6]
660        SIZE = int(float(SIZE) * 1.1 + 1)
661        subprocess.run(["btrfs", "filesystem", "resize", str(SIZE), MNTDIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
662    elif TYPE in ["REISERFS", "REISER4"]:
663        MNTDIR = ogMount(int_ndisk, int_nfilesys)
664        SIZE = int(subprocess.run(["df", "-k", MNTDIR], capture_output=True, text=True).stdout.strip().split("\n")[1].split()[2])
665        SIZE = SIZE * 110 // 100
666        ogUnmount(int_ndisk, int_nfilesys)
667        subprocess.run(["resize_reiserfs", "-s" + str(SIZE) + "K", PART], input="y\n", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
668    elif TYPE == "NTFS":
669        ogUnmount(int_ndisk, int_nfilesys)
670        MAXSIZE, SIZE = subprocess.run(["ntfsresize", "-fi", PART], capture_output=True, text=True)
671        MAXSIZE = MAXSIZE.strip().split(" ")[3]
672        SIZE = SIZE.strip().split(" ")[4]
673        SIZE = int(float(SIZE) * 1.1 / 1024 + 1) * 1024
674        RETVAL = 1
675        while RETVAL != 0 and SIZE + EXTRASIZE < MAXSIZE:
676            EXTRASIZE = subprocess.run(["ntfsresize", "-fns", str(SIZE), PART], capture_output=True, text=True)
677            EXTRASIZE = int(EXTRASIZE.stdout.strip()) if EXTRASIZE.stdout.strip() else 0
678            RETVAL = EXTRASIZE != 0
679            SIZE += EXTRASIZE
680        if SIZE < MAXSIZE:
681            subprocess.run(["ntfsresize", "-fs", str(SIZE), PART], input="y\n", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
682    elif TYPE in ["FAT32", "FAT16"]:
683        # No se reduce (por el momento).
684        pass
685    elif TYPE == "HFS" or TYPE == "HFSPLUS":
686        # No se reduce (por el momento).
687        pass
688    elif TYPE == "UFS":
689        # No se reduce (por el momento).
690        pass
691    else:
692        ogRaiseError(OG_ERR_PARTITION, f"{int_ndisk}, {int_nfilesys}")
693
694    # Devuelve tamaño del sistema de ficheros.
695    return ogGetFsSize(int_ndisk, int_nfilesys)
696
697def ogUnlock(int_ndisk, int_npartition):
698    ogUnlockPartition(int_ndisk, int_npartition)
699
700def ogUnlockPartition(int_ndisk, int_npartition):
701    # Si se solicita, mostrar ayuda.
702    if len(sys.argv) == 3 and sys.argv[2] == "help":
703        ogHelp("ogUnlockPartition", "ogUnlockPartition int_ndisk int_npartition", "ogUnlockPartition 1 1")
704        return
705
706    # Error si no se reciben 2 parámetros.
707    if len(sys.argv) != 3:
708        ogRaiseError(OG_ERR_FORMAT)
709        return
710
711    # Obtener partición.
712    PART = ogDiskToDev(int_ndisk, int_npartition)
713    if not PART:
714        return
715
716    # Borrar archivo de bloqueo exclusivo.
717    LOCKFILE = f"/var/lock/lock{PART.replace('/', '-')}"
718    os.remove(LOCKFILE)
719
720def ogUnmount():
721    ogUnmountFs(*sys.argv[2:])
722
723def ogUnmountFs(int_ndisk, int_npartition):
724    FUNCNAME = ogUnmountFs.__name__
725    # Si se solicita, mostrar ayuda.
726    if len(sys.argv) == 3 and sys.argv[2] == "help":
727        ogHelp("ogUnmountFs", "ogUnmountFs int_ndisk int_npartition", "ogUnmountFs 1 1")
728        return
729
730    # Error si no se reciben 2 parámetros.
731    if len(sys.argv) != 3:
732        ogRaiseError(OG_ERR_FORMAT)
733        return
734
735    # Obtener partición y punto de montaje.
736    PART = ogDiskToDev(int_ndisk, int_npartition)
737    MNTDIR = ogGetMountPoint(int_ndisk, int_npartition)
738
739    # Si está montada, desmontarla.
740    if MNTDIR:
741        # Error si la particion está bloqueada.
742        if ogIsPartitionLocked(int_ndisk, int_npartition):
743            ogRaiseError(OG_ERR_LOCKED, f"{MSG_PARTITION}, {int_ndisk} {int_npartition}")
744            return
745
746        # Desmontar y borrar punto de montaje.
747        try:
748            subprocess.run(["umount", PART], check=True, stderr=subprocess.DEVNULL)
749        except subprocess.CalledProcessError:
750            ogEcho("warning", f"{FUNCNAME}: {MSG_DONTUNMOUNT}: \"{int_ndisk}, {int_npartition}\"")
751        try:
752            os.rmdir(MNTDIR)
753        except OSError:
754            os.remove(MNTDIR)
755    else:
756        ogEcho("warning", f"{MSG_DONTMOUNT}: \"{int_ndisk},{int_npartition}\"")
757        ogUnmountFs(int_ndisk, int_npartition)
758
759def ogUnmountAll(int_ndisk):
760    # Si se solicita, mostrar ayuda.
761    if len(sys.argv) == 3 and sys.argv[2] == "help":
762        ogHelp("ogUnmountAll", "ogUnmountAll int_ndisk", "ogUnmountAll 1")
763        return
764
765    # Error si no se recibe 1 parámetro.
766    if len(sys.argv) != 3:
767        ogRaiseError(OG_ERR_FORMAT)
768        return
769
770    # Obtener partición y punto de montaje.
771    DISK = ogDiskToDev(int_ndisk)
772    for PART in range(1, ogGetPartitionsNumber(int_ndisk) + 1):
773        if ogGetFsType(int_ndisk, PART) != "CACHE":
774            ogUnmount(int_ndisk, PART)
775
776def ogUnsetDirtyBit(int_ndisk, int_nfilesys):
777    # Si se solicita, mostrar ayuda.
778    if len(sys.argv) == 3 and sys.argv[2] == "help":
779        ogHelp("ogUnsetDirtyBit", "ogUnsetDirtyBit int_ndisk int_nfilesys", "ogUnsetDirtyBit 1 1")
780        return
781
782    # Error si no se reciben 2 parámetros.
783    if len(sys.argv) != 3:
784        ogRaiseError(OG_ERR_FORMAT)
785        return
786
787    # Obtener partición y punto de montaje.
788    PART = ogDiskToDev(int_ndisk, int_nfilesys)
789    if not PART:
790        return
791
792    # Realizar acciones específicas según el tipo de sistema de archivos.
793    TYPE = ogGetFsType(int_ndisk, int_nfilesys)
794    if TYPE == "NTFS":
795        ogUnmount(int_ndisk, int_nfilesys)
796        subprocess.run(["ntfsfix", "-d", PART], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
797    else:
798        pass  # Add more specific actions for other file systems if needed.
799
800def ogGetFreeSize(int_ndisk, int_npartition, str_SizeOutput):
801    if len(sys.argv) == 3 and sys.argv[2] == "help":
802        ogHelp("ogGetFreeSize", "ogGetFreeSize int_ndisk int_npartition str_SizeOutput", "ogGetFreeSize 1 1 GB")
803        return
804
805    if len(sys.argv) < 3:
806        ogRaiseError(OG_ERR_FORMAT)
807        return
808
809    PART = ogDiskToDev(int_ndisk, int_npartition)
810    if not PART:
811        return
812
813    unit = str_SizeOutput
814    if not unit:
815        unit = "GB"
816
817    factor = 1.024 / 1000000
818    if unit == "kB":
819        factor = 1.024
820    elif unit == "MB":
821        factor = 1.024 / 1000
822
823    result = subprocess.run(["df", PART], capture_output=True, text=True)
824    output = result.stdout.strip().split("\n")[1].split()
825    size = float(output[1]) * factor
826    used = float(output[2]) * factor
827    free = float(output[3]) * factor
828
829    return free
Note: See TracBrowser for help on using the repository browser.