source: client/engine/FileSystem.lib @ 9dba4c18

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since 9dba4c18 was 0390d46, checked in by ramon <ramongomez@…>, 12 years ago

#598: Corregir errata en comentario en función ogGetFreeSize.

git-svn-id: https://opengnsys.es/svn/branches/version1.0@3859 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100755
File size: 31.6 KB
Line 
1#!/bin/bash
2#/**
3#@file    FileSystem.lib
4#@brief   Librería o clase FileSystem
5#@class   FileSystem
6#@brief   Funciones para gestión de sistemas de archivos.
7#@version 1.0.5
8#@warning License: GNU GPLv3+
9#*/
10
11
12#/**
13#         ogCheckFs int_ndisk int_nfilesys
14#@brief   Comprueba el estado de un sistema de archivos.
15#@param   int_ndisk      nº de orden del disco
16#@param   int_nfilesys   nº de orden del sistema de archivos
17#@return  (nada)
18#@exception OG_ERR_FORMAT    Formato incorrecto.
19#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
20#@exception OG_ERR_PARTITION Partición desconocida o no accesible.
21#@note    Requisitos: *fsck*
22#@warning No se comprueban sistemas de archivos montados o bloqueados.
23#@todo    Definir salidas.
24#@version 0.9 - Primera adaptación para OpenGnSys.
25#@author  Ramon Gomez, ETSII Universidad de Sevilla
26#@date    2009-10-07
27#@version 1.0.2 - Ignorar códigos de salida de comprobación (no erróneos).
28#@author  Ramon Gomez, ETSII Universidad de Sevilla
29#@date    2011-09-23
30#@version 1.0.4 - Soportar HFS/HFS+.
31#@author  Ramon Gomez, ETSII Universidad de Sevilla
32#@date    2012-05-21
33#@version 1.0.5 - Desmontar antes de comprobar, soportar Btrfs y ExFAT.
34#@author  Ramon Gomez, ETSII Universidad de Sevilla
35#@date    2012-09-05
36#*/ ##
37function ogCheckFs ()
38{
39# Variables locales.
40local PART TYPE PROG PARAMS CODES ERRCODE
41# Si se solicita, mostrar ayuda.
42if [ "$*" == "help" ]; then
43    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
44           "$FUNCNAME 1 1"
45    return
46fi
47
48# Error si no se reciben 2 parámetros.
49[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
50# Obtener partición.
51PART="$(ogDiskToDev $1 $2)" || return $?
52
53TYPE=$(ogGetFsType $1 $2)
54case "$TYPE" in
55    EXT[234])     PROG="e2fsck"; PARAMS="-y"; CODES=(1 2) ;;
56    BTRFS)        PROG="btrfsck"; CODES=1 ;;
57    REISERFS)     PROG="fsck.reiserfs"; PARAMS="<<<\"Yes\""; CODES=(1 2) ;;
58    REISER4)      PROG="fsck.reiser4"; PARAMS="-ay" ;;
59    JFS)          PROG="fsck.jfs"; CODES=(1 2) ;;
60    XFS)          PROG="fsck.xfs" ;;
61    NTFS)         PROG="ntfsfix" ;;
62    EXFAT)        PROG="fsck.exfat" ;;
63    FAT32)        PROG="dosfsck"; PARAMS="-a"; CODES=1 ;;
64    FAT16)        PROG="dosfsck"; PARAMS="-a"; CODES=1 ;;
65    FAT12)        PROG="dosfsck"; PARAMS="-a"; CODES=1 ;;
66    HFS)          PROG="fsck.hfs" ;;
67    HFSPLUS)      PROG="fsck.hfsplus" ;;
68    UFS)          PROG="fsck.ufs" ;;
69    *)            ogRaiseError $OG_ERR_PARTITION "$1, $2, $TYPE"
70                  return $? ;;
71esac
72# Error si el sistema de archivos esta montado o bloqueado.
73ogUnmount $1 $2
74if ogIsMounted $1 $2; then
75    ogRaiseError $OG_ERR_PARTITION "$1 $2"       # Indicar nuevo error
76    return $?
77fi
78if ogIsLocked $1 $2; then
79    ogRaiseError $OG_ERR_LOCKED "$1 $2"
80    return $?
81fi
82# Comprobar en modo uso exclusivo.
83ogLock $1 $2
84trap "ogUnlock $1 $2" 1 2 3 6 9
85eval $PROG $PARAMS $PART
86ERRCODE=$?
87case $ERRCODE in
88    0|${CODES[*]})
89            ERRCODE=0 ;;
90    127)    ogRaiseError $OG_ERR_NOTEXEC "$PROG"
91            ERRCODE=$OG_ERR_NOTEXEC ;;
92    *)      ogRaiseError $OG_ERR_PARTITION "$1 $2"
93            ERRCODE=$OG_ERR_PARTITION ;;
94esac
95ogUnlock $1 $2
96return $ERRCODE
97}
98
99
100#/**
101#         ogExtendFs int_ndisk int_nfilesys
102#@brief   Extiende un sistema de archivos al tamaño de su partición.
103#@param   int_ndisk      nº de orden del disco
104#@param   int_nfilesys   nº de orden del sistema de archivos
105#@return  (nada)
106#@exception OG_ERR_FORMAT   Formato incorrecto.
107#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
108#@exception OG_ERR_PARTITION Partición desconocida o no accesible.
109#@note    Requisitos: *resize*
110#@version 0.1 -  Integracion para Opengnsys  -  EAC:   EnlargeFileSystem() en ATA.lib
111#@author  Antonio J. Doblas Viso. Universidad de Malaga
112#@date    2008-10-27
113#@version 0.9 - Primera adaptacion para OpenGnSys.
114#@author  Ramon Gomez, ETSII Universidad de Sevilla
115#@date    2009-09-23
116#@version 1.0.5 - Soporte para BTRFS.
117#@author  Ramon Gomez, ETSII Universidad de Sevilla
118#@date    2012-06-28
119#*/ ##
120function ogExtendFs ()
121{
122# Variables locales.
123local PART TYPE PROG PARAMS ERRCODE DOMOUNT
124
125# Si se solicita, mostrar ayuda.
126if [ "$*" == "help" ]; then
127    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
128           "$FUNCNAME 1 1"
129    return
130fi
131# Error si no se reciben 2 parámetros.
132[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
133
134# Obtener partición.
135PART="$(ogDiskToDev $1 $2)" || return $?
136
137# Redimensionar al tamano máximo según el tipo de partición.
138TYPE=$(ogGetFsType $1 $2)
139case "$TYPE" in
140    EXT[234])   PROG="resize2fs"; PARAMS="-f" ;;
141    BTRFS)      PROG="btrfs"; PARAMS="filesystem resize max"
142                DOMOUNT=1     # Debe estar montado.
143                ;;
144    REISERFS|REISER4)
145                PROG="resize_reiserfs"; PARAMS="-f" ;;
146    NTFS)       PROG="ntfsresize"; PARAMS="<<<\"y\" -f" ;;
147#    FAT32|FAT16)       # Usar "fatresize"
148    *)          ogRaiseError $OG_ERR_PARTITION "$1 $2 $TYPE"
149                return $? ;;
150esac
151# Error si el sistema de archivos no se queda en el estado de montaje adecuado.
152if [ "$DOMOUNT" ]; then
153    PART=$(ogMount $1 $2)
154    [ -n "$PART" ] || ogRaiseError $OG_ERR_PARTITION "$1 $2" || return $?   # Indicar nuevo error
155else
156    ogUnmount $1 $2 2>/dev/null
157    ogIsMounted $1 $2 && ogRaiseError $OG_ERR_PARTITION "$1 $2" || return $?   # Indicar nuevo error
158fi
159# Error si el sistema de archivos está bloqueado.
160if ogIsLocked $1 $2; then
161    ogRaiseError $OG_ERR_LOCKED "$1 $2"
162    return $?
163fi
164# Redimensionar en modo uso exclusivo.
165ogLock $1 $2
166trap "ogUnlock $1 $2" 1 2 3 6 9
167eval $PROG $PARAMS $PART &>/dev/null
168ERRCODE=$?
169case $ERRCODE in
170    0)    ;;
171    127)  ogRaiseError $OG_ERR_NOTEXEC "$PROG"
172          ERRCODE=$OG_ERR_NOTEXEC ;;
173    *)    ogRaiseError $OG_ERR_PARTITION "$1 $2"
174          ERRCODE=$OG_ERR_PARTITION ;;
175esac
176ogUnlock $1 $2
177return $ERRCODE
178}
179
180
181#/**
182#         ogFormat int_ndisk int_nfilesys | CACHE
183#@see     ogFormatFs ogFormatCache
184#*/ ##
185function ogFormat ()
186{
187case "$*" in
188    CACHE|cache)  ogFormatCache ;;
189    *)            ogFormatFs "$@" ;;
190esac
191}
192
193
194#/**
195#         ogFormatFs int_ndisk int_nfilesys [type_fstype] [str_label]
196#@brief   Formatea un sistema de ficheros según el tipo de su partición.
197#@param   int_ndisk      nº de orden del disco
198#@param   int_nfilesys   nº de orden del sistema de archivos
199#@param   type_fstype    mnemónico de sistema de ficheros a formatear (opcional al reformatear)
200#@param   str_label      etiqueta de volumen (opcional)
201#@return  (por determinar)
202#@exception OG_ERR_FORMAT    Formato de ejecución incorrecto.
203#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
204#@exception OG_ERR_PARTITION Partición no accesible o desconocida.
205#@note    Requisitos:   mkfs*
206#@warning No formatea particiones montadas ni bloqueadas.
207#@todo    Definir salidas.
208#@version 0.9 - Primera versión para OpenGnSys.
209#@author  Ramon Gomez, ETSII Universidad de Sevilla
210#@date    2009-10-08
211#@version 1.0.4 - Solucionado error cuando no se detecta tipo de sistema de ficheros pero si se indica.
212#@author  Universidad de Huelva
213#@date    2012-04-11
214#@version 1.0.5 - Comprobar errores al inicio e independizar del tipo de tabla de particiones.
215#@author  Universidad de Huelva
216#@date    2013-05-16
217#*/ ##
218function ogFormatFs ()
219{
220# Variables locales
221local PART ID TYPE LABEL PROG PARAMS LABELPARAM ERRCODE
222
223# Si se solicita, mostrar ayuda.
224if [ "$*" == "help" ]; then
225    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_label]" \
226           "$FUNCNAME 1 1" \
227           "$FUNCNAME 1 1 EXT4" \
228           "$FUNCNAME 1 1 \"DATA\"" \
229           "$FUNCNAME 1 1 EXT4 \"DATA\""
230    return
231fi
232# Error si no se reciben entre 2 y 4 parámetros.
233[ $# -ge 2 -a $# -le 4 ] || ogRaiseError $OG_ERR_FORMAT || return $?
234# Obtener fichero de dispositivo.
235PART="$(ogDiskToDev $1 $2)" || return $?
236# Error si la partición está montada o bloqueada.
237if ogIsMounted $1 $2; then
238    ogRaiseError $OG_ERR_PARTITION "$1 $2"       # Indicar nuevo error
239    return $?
240fi
241if ogIsLocked $1 $2; then
242    ogRaiseError $OG_ERR_LOCKED "$1 $2"
243    return $?
244fi
245# Si no se indica el tipo de sisitema de archivos, intentar obtenerlo.
246TYPE="${3:-$(ogGetFsType $1 $2)}"
247# Error, si no especifica el tipo de sistema de archivos a formatear.
248[ -n "$TYPE" ] || ogRaiseError $OG_ERR_FORMAT "$1 $2 ..." || return $?
249
250# Elegir tipo de formato.
251case "$TYPE" in
252    EXT2)         PROG="mkfs.ext2" ;;
253    EXT3)         PROG="mkfs.ext3" ;;
254    EXT4)         PROG="mkfs.ext4" ;;
255    BTRFS)        PROG="mkfs.btrfs" ;;
256    REISERFS)     PROG="mkfs.reiserfs"; PARAMS="-f"; LABELPARAM="-l" ;;
257    REISER4)      PROG="mkfs.reiser4"; PARAMS="-fy" ;;
258    XFS)          PROG="mkfs.xfs"; PARAMS="-f" ;;
259    JFS)          PROG="mkfs.jfs"; PARAMS="<<<\"y\"" ;;
260    LINUX-SWAP)   PROG="mkswap" ;;
261    NTFS)         PROG="mkntfs"; PARAMS="-f" ;;
262    EXFAT)        PROG="mkfs.exfat"; LABELPARAM="-n" ;;
263    FAT32)        PROG="mkdosfs"; PARAMS="-F 32"; LABELPARAM="-n" ;;
264    FAT16)        PROG="mkdosfs"; PARAMS="-F 16"; LABELPARAM="-n" ;;
265    FAT12)        PROG="mkdosfs"; PARAMS="-F 12"; LABELPARAM="-n" ;;
266    HFS)          PROG="mkfs.hfs" ;;
267    HFSPLUS)      PROG="mkfs.hfsplus"; LABELPARAM="-v" ;;
268    UFS)          PROG="mkfs.ufs"; PARAMS="-O 2" ;;
269    *)            ogRaiseError $OG_ERR_PARTITION "$1 $2 $TYPE"
270                  return $? ;;
271esac
272
273# Etiquetas de particion.
274if [ -z "$LABEL" ]; then
275    [ "$4" != "CACHE" ] || ogRaiseError $OG_ERR_FORMAT "$MSG_RESERVEDVALUE: CACHE" || return $?
276    [ -n "$4" ] && PARAMS="$PARAMS ${LABELPARAM:-"-L"} $4"
277else
278    PARAMS="$PARAMS ${LABELPARAM:-"-L"} $LABEL"
279fi
280
281# Formatear en modo uso exclusivo (desmontar siempre).
282ogLock $1 $2
283trap "ogUnlock $1 $2" 1 2 3 6 9
284umount $PART 2>/dev/null
285eval $PROG $PARAMS $PART 2>/dev/null
286ERRCODE=$?
287case $ERRCODE in
288    0)    ;;
289    127)  ogRaiseError $OG_ERR_NOTEXEC "$PROG" ;;
290    *)    ogRaiseError $OG_ERR_PARTITION "$1 $2" ;;
291esac
292ogUnlock $1 $2
293return $ERRCODE
294}
295
296
297#/**
298#         ogGetFsSize int_ndisk int_npartition [str_unit]
299#@brief Muestra el tamanio del sistema de archivos indicado, permite definir la unidad de medida, por defecto GB
300#@param   int_ndisk      nº de orden del disco
301#@param   int_npartition nº de orden de la partición
302#@param   str_unit       unidad (opcional, por defecto: KB)
303#@return  float_size - Tamaño del sistema de archivos
304#@note    str_unit = { KB, MB, GB, TB }
305#@exception OG_ERR_FORMAT   Formato incorrecto.
306#@exception OG_ERR_NOTFOUND Disco o partición no corresponden con un dispositivo.
307#@version 0.1 -  Integracion para Opengnsys  -  EAC:  SizeFileSystem() en FileSystem.lib
308#@author  Antonio J. Doblas Viso. Universidad de Malaga
309#@date    2008-10-27
310#@version 1.0.4 - Adaptación de las salidas.
311#@author  Ramon Gomez, ETSII Universidad de Sevilla
312#@date    2012-06-18
313#*/ ##
314function ogGetFsSize ()
315{
316# Variables locales.
317local MNTDIR UNIT VALUE FACTOR SIZE
318# Si se solicita, mostrar ayuda.
319if [ "$*" == "help" ]; then
320    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition [str_unit]" \
321           "$FUNCNAME 1 1  =>  15624188" \
322           "$FUNCNAME 1 1 KB  =>  15624188"
323    return
324fi
325# Error si no se reciben 2 o 3 parámetros.
326[ $# == 2 ] || [ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
327# Obtener unidad y factor de medida.
328UNIT="$3"
329UNIT=${UNIT:-"KB"}
330case "$UNIT" in
331    [kK]B)
332        FACTOR=1 ;;
333    MB) FACTOR=1024 ;;
334    GB) FACTOR=$[1024*1024] ;;
335    TB) FACTOR=$[1024*1024*1024] ;;
336    *)  ogRaiseError $OG_ERR_FORMAT "$3 != { KB, MB, GB, TB }"
337        return $? ;;
338esac
339
340# Obtener el tamaño del sistema de archivo (si no está formateado; tamaño = 0).
341MNTDIR="$(ogMount $1 $2 2>/dev/null)"
342if [ -n "$MNTDIR" ]; then
343    VALUE=$(df -BK "$MNTDIR" | awk '{getline; print $2}')
344    SIZE=$(echo "$VALUE $FACTOR" | awk '{printf "%f\n", $1/$2}')
345else
346    SIZE=0
347fi
348# Devolver el tamaño (quitar decimales si son 0).
349echo ${SIZE%.0*}
350}
351
352
353#/**
354#         ogGetFsType int_ndisk int_nfilesys
355#@brief   Devuelve el mnemonico con el tipo de sistema de archivos.
356#@param   int_ndisk      nº de orden del disco
357#@param   int_nfilesys   nº de orden del sistema de archivos
358#@return  Mnemonico
359#@note    Mnemonico: { EXT2, EXT3, EXT4, BTRFS, REISERFS, XFS, JFS, FAT32, NTFS, CACHE }
360#@exception OG_ERR_FORMAT   Formato incorrecto.
361#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
362#@version 0.1 -  Integracion para Opengnsys  -  EAC:   TypeFS() en ATA.lib
363#@author  Antonio J. Doblas Viso. Universidad de Malaga
364#@date    2008-10-27
365#@version 0.9 - Primera adaptacion para OpenGnSys.
366#@author  Ramon Gomez, ETSII Universidad de Sevilla
367#@date    2009-07-21
368#@version 1.0.2 - Obtención de datos reales de sistemas de ficheros.
369#@author  Ramon Gomez, ETSII Universidad de Sevilla
370#@date    2011-12-02
371#@version 1.0.5 - Usar "mount" en vez de "parted".
372#@author  Ramon Gomez, ETSII Universidad de Sevilla
373#@date    2012-09-04
374#*/ ##
375function ogGetFsType ()
376{
377# Variables locales.
378local PART ID TYPE
379# Si se solicita, mostrar ayuda.
380if [ "$*" == "help" ]; then
381    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
382           "$FUNCNAME 1 1  =>  NTFS"
383    return
384fi
385# Error si no se reciben 2 parámetros.
386[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
387
388# Detectar id. de tipo de partición.
389PART=$(ogDiskToDev "$1" "$2") || return $?
390ID=$(ogGetPartitionId "$1" "$2")
391[ "$ID" == "a7" ] && ID="ca"    # Traducir antiguo id. de partición de caché.
392TYPE=""
393case "$ID" in
394     ca|CA00)  # Detectar caché local (revisar detección en tablas GPT).
395               ogIsFormated $1 $2 2>/dev/null && TYPE="CACHE"
396               ;;
397     *)        # Detectar sistema de ficheros.
398               TYPE=$(blkid -o export $PART | awk -F= '$1~/^TYPE/ { print toupper($2) }')
399               # Componer valores correctos.
400               case "$TYPE" in
401                    VFAT)      TYPE="FAT32" ;;  # Nota: usar "file -Ls" para detectar.
402                    SWAP)      TYPE="LINUX-SWAP" ;;
403                    LVM*)      TYPE="LINUX-LVM" ;;
404                    *RAID*)    TYPE="LINUX-RAID" ;;
405                    *_MEMBER)  TYPE="${TYPE/_MEMBER/}" ;;
406               esac
407               ;;
408esac
409
410[ -n "$TYPE" ] && echo "$TYPE"
411}
412
413
414#/**
415#         ogGetMountPoint int_ndisk int_nfilesys
416#@brief   Devuelve el punto de montaje de un sistema de archivos.
417#@param   int_ndisk      nº de orden del disco
418#@param   int_nfilesys   nº de orden del sistema de archivos
419#@return  Punto de montaje
420#@exception OG_ERR_FORMAT    Formato incorrecto.
421#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
422#@note    Requisitos: \c mount* \c awk
423#@version 0.9 - Primera versión para OpenGnSys.
424#@author  Ramon Gomez, ETSII Universidad de Sevilla
425#@date    2009-10-15
426#*/ ##
427function ogGetMountPoint ()
428{
429# Variables locales
430local PART
431# Si se solicita, mostrar ayuda.
432if [ "$*" == "help" ]; then
433    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
434           "$FUNCNAME 1 1  =>  /mnt/sda1"
435    return
436fi
437# Error si no se reciben 2 parámetros.
438[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
439# Obtener partición.
440PART="$(ogDiskToDev $1 $2)" || return $?
441
442mount | awk -v P=$PART '{if ($1==P) {print $3}}'
443}
444
445
446#/**
447#         ogIsFormated int_ndisk int_nfilesys
448#@brief   Comprueba si un sistema de archivos está formateado.
449#@param   int_ndisk      nº de orden del disco o volumen.
450#@param   int_nfilesys   nº de orden del sistema de archivos
451#@return  Código de salida: 0 - formateado, 1 - sin formato o error.
452#@version 0.91 - Adaptación inicial para comprobar que existe caché.
453#@author  Ramon Gomez, ETSII Universidad de Sevilla
454#@date    2010-03-18
455#@version 1.0.1 - Devolver falso en caso de error.
456#@author  Ramon Gomez, ETSII Universidad de Sevilla
457#@date    2011-05-18
458#@version 1.0.5 - Dejar de usar "parted".
459#@author  Ramon Gomez, ETSII Universidad de Sevilla
460#@date    2012-09-04
461#*/ ##
462function ogIsFormated ()
463{
464# Variables locales
465local DISK
466if [ "$*" == "help" ]; then
467    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
468           "if $FUNCNAME 1 1; then ... ; fi"
469    return
470fi
471# Falso, en caso de error.
472[ $# == 2 ] || return 1
473
474test -n "$(ogMount "$1" "$2")"
475}
476
477
478#/**
479#         ogIsMounted int_ndisk int_nfilesys
480#@brief   Comprueba si un sistema de archivos está montado.
481#@param   int_ndisk      nº de orden del disco
482#@param   int_nfilesys   nº de orden del sistema de archivos
483#@return  Código de salida: 0 - montado, 1 - sin montar o error.
484#@version 0.9 - Primera versión para OpenGnSys.
485#@author  Ramon Gomez, ETSII Universidad de Sevilla
486#@date    2009-10-15
487#@version 1.0.1 - Devolver falso en caso de error.
488#@author  Ramon Gomez, ETSII Universidad de Sevilla
489#@date    2011-05-18
490#*/ ##
491function ogIsMounted ()
492{
493# Si se solicita, mostrar ayuda.
494if [ "$*" == "help" ]; then
495    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
496           "if $FUNCNAME 1 1; then ... ; fi"
497    return
498fi
499# Falso, en caso de error.
500[ $# == 2 ] || return 1
501
502test -n "$(ogGetMountPoint $1 $2)"
503}
504
505
506#/**
507#         ogIsLocked int_ndisk int_npartition
508#@brief   Comprueba si una partición está bloqueada por una operación de uso exclusivo.
509#@param   int_ndisk      nº de orden del disco
510#@param   int_npartition nº de orden de la partición
511#@return  Código de salida: 0 - bloqueado, 1 - sin bloquear o error.
512#@note    El fichero de bloqueo se localiza en \c /var/lock/part, siendo \c part el dispositivo de la partición, sustituyendo el carácter "/" por "-".
513#@version 0.9 - Primera versión para OpenGnSys.
514#@author  Ramon Gomez, ETSII Universidad de Sevilla
515#@date    2009-09-03
516#@version 1.0.1 - Devolver falso en caso de error.
517#@author  Ramon Gomez, ETSII Universidad de Sevilla
518#@date    2011-05-18
519#*/ ##
520function ogIsLocked ()
521{
522# Variables locales
523local PART LOCKFILE
524
525# Si se solicita, mostrar ayuda.
526if [ "$*" == "help" ]; then
527    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
528           "if $FUNCNAME 1 1; then ... ; fi"
529    return
530fi
531# Falso, en caso de error.
532[ $# == 2 ] || return 1
533
534# Obtener partición.
535PART="$(ogDiskToDev $1 $2)" || return 1
536
537# Comprobar existencia del fichero de bloqueo.
538LOCKFILE="/var/lock/lock${PART//\//-}"
539test -f $LOCKFILE
540}
541
542
543#/**
544#         ogLock int_ndisk int_npartition
545#@see     ogLockPartition
546#*/
547function ogLock ()
548{
549ogLockPartition "$@"
550}
551
552#/**
553#         ogLockPartition int_ndisk int_npartition
554#@brief   Genera un fichero de bloqueo para una partición en uso exlusivo.
555#@param   int_ndisk      nº de orden del disco
556#@param   int_npartition nº de orden de la partición
557#@return  (nada)
558#@exception OG_ERR_FORMAT    Formato incorrecto.
559#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
560#@note    El fichero de bloqueo se localiza en \c /var/lock/part, siendo \c part el dispositivo de la partición, sustituyendo el carácter "/" por "-".
561#@version 0.9 - Primera versión para OpenGnSys.
562#@author  Ramon Gomez, ETSII Universidad de Sevilla
563#@date    2009-09-03
564#*/ ##
565function ogLockPartition ()
566{
567# Variables locales
568local PART LOCKFILE
569
570# Si se solicita, mostrar ayuda.
571if [ "$*" == "help" ]; then
572    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
573           "$FUNCNAME 1 1"
574    return
575fi
576# Error si no se reciben 2 parámetros.
577[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
578
579# Obtener partición.
580PART="$(ogDiskToDev $1 $2)" || return $?
581
582# Crear archivo de bloqueo exclusivo.
583LOCKFILE="/var/lock/lock${PART//\//-}"
584touch $LOCKFILE
585}
586
587
588#/**
589#         ogMount int_ndisk int_nfilesys
590#@see     ogMountFs ogMountCache ogMountCdrom
591#*/ ##
592function ogMount ()
593{
594case "$*" in
595    CACHE|cache)
596        ogMountCache ;;
597    CDROM|cdrom)
598        ogMountCdrom ;;
599    *)  ogMountFs "$@" ;;
600esac
601}
602
603
604#/**
605#         ogMountFs int_ndisk int_nfilesys
606#@brief   Monta un sistema de archivos.
607#@param   int_ndisk      nº de orden del disco
608#@param   int_nfilesys   nº de orden del sistema de archivos
609#@return  Punto de montaje
610#@exception OG_ERR_FORMAT    Formato incorrecto.
611#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
612#@exception OG_ERR_PARTITION Tipo de particion desconocido o no se puede montar.
613#@version 0.1 -  Integracion para Opengnsys  -  EAC:   MountPartition() en FileSystem.lib
614#@author  Antonio J. Doblas Viso. Universidad de Malaga
615#@date    2008-10-27
616#@version 0.9 - Primera version para OpenGnSys.
617#@author  Ramon Gomez, ETSII Universidad de Sevilla
618#@date    2009-09-28
619#@version 1.0.5 - Independiente del tipo de sistema de ficheros.
620#@author  Ramon Gomez, ETSII Universidad de Sevilla
621#@date    2012-09-04
622#*/ ##
623function ogMountFs ()
624{
625# Variables locales
626local PART MNTDIR
627
628# Si se solicita, mostrar ayuda.
629if [ "$*" == "help" ]; then
630    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
631           "$FUNCNAME 1 1  =>  /mnt/sda1"
632    return
633fi
634# Error si no se reciben 2 parámetros.
635[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
636
637# Obtener partición.
638PART="$(ogDiskToDev "$1" "$2")" || return $?
639
640# Comprobar si el sistema de archivos ya está montada.
641MNTDIR="$(ogGetMountPoint $1 $2)"
642# Si no, montarlo en un directorio de sistema.
643if [ -z "$MNTDIR" ]; then
644    # Error si la particion esta bloqueada.
645    if ogIsLocked $1 $2; then
646        ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION, $1 $2"
647        return $?
648    fi
649    # Crear punto de montaje o enlace simbólico para caché local.
650    MNTDIR=${PART/dev/mnt}
651    if [ "$(ogFindCache)" == "$1 $2" -a -n "$OGCAC" ]; then
652        mkdir -p $OGCAC
653        ln -fs $OGCAC $MNTDIR
654    else
655        mkdir -p $MNTDIR
656    fi
657    # Montar sistema de archivos.
658    mount $PART $MNTDIR &>/dev/null || \
659               mount $PART $MNTDIR -o force,remove_hiberfile &>/dev/null || \
660               ogRaiseError $OG_ERR_PARTITION "$1, $2" || return $?
661fi
662echo "$MNTDIR"
663}
664
665
666#####  PRUEBAS
667# Montar CDROM
668function ogMountCdrom ()
669{
670local DEV MNTDIR
671DEV="/dev/cdrom"            # Por defecto
672MNTDIR=$(mount | awk -v D=$DEV '{if ($1==D) {print $3}}')
673if [ -z "$MNTDIR" ]; then
674    MNTDIR=${DEV/dev/mnt}
675    mkdir -p $MNTDIR
676    mount -t iso9660 $DEV $MNTDIR || ogRaiseError $OG_ERR_PARTITION "cdrom" || return $?
677fi
678echo $MNTDIR
679}
680
681
682#/**
683#         ogReduceFs int_ndisk int_nfilesys
684#@brief   Reduce el tamaño del sistema de archivos, sin tener en cuenta el espacio libre.
685#@param   int_ndisk      nº de orden del disco
686#@param   int_nfilesys   nº de orden del sistema de archivos
687#@return  int_tamañoKB - tamaño en KB
688#@exception OG_ERR_FORMAT    Formato incorrecto.
689#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
690#@exception OG_ERR_PARTITION Partición desconocida o no accesible.
691#@warning En Windows, se borran los ficheros pagefile.sys e hiberfile.sys
692#@warning El sistema de archivos se amplía al mínimo + 10%.
693#@note    Requisitos:   *resize*
694#@version 0.1 -  Integracion para Opengnsys  -  EAC:   ReduceFileSystem() en ATA.lib
695#@author  Antonio J. Doblas Viso. Universidad de Malaga
696#@date    2008-10-27
697#@version 0.9 - Primera version para OpenGnSys.
698#@author  Ramon Gomez, ETSII Universidad de Sevilla
699#@date    2009-09-23
700#@version 0.9.2 - Añadir un 10% al tamaño mínimo requerido.
701#@author  Ramon Gomez, ETSII Universidad de Sevilla
702#@date    2010-09-27
703#@version 1.0 -  Deteccion automatica del tamaño minimo adecuado
704#@author  Antonio J. Doblas Viso. Universidad de Malaga
705#@date    2011-02-24
706#*/ ##
707function ogReduceFs ()
708{
709# Variables locales
710local PART BLKS SIZE
711
712# Si se solicita, mostrar ayuda.
713if [ "$*" == "help" ]; then
714    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
715           "$FUNCNAME 1 1"
716    return
717fi
718# Error si no se reciben 2 parámetros.
719[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
720
721# Obtener partición.
722PART="$(ogDiskToDev $1 $2)" || return $?
723
724# Redimensionar según el tipo de particion.
725case "$(ogGetFsType $1 $2)" in
726    EXT[234])
727        ogUnmount $1 $2 2>/dev/null
728        # Ext2/3/4: Tamaño de los bloques del sistema de archivos
729        BLKS=$(tune2fs -l $PART | awk '/Block size/ {print int($3/512)}')
730        # Traduce el num. en sectores de 512B a tamano en MB.
731        #SIZE=$(resize2fs -P $PART 2>/dev/null | \
732                #       awk -v B=$BLKS '/minimum size/ {print int($7*1.1*B/2048)}')
733        #resize2fs -fp $PART "${SIZE}M" &>/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
734        resize2fs -fpM $PART  &>/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
735        ;;
736    BTRFS)
737        MNTDIR=$(ogMount $1 $2)
738        # Calcular tamaño ocupado + 10%.
739        SIZE=$[ $(df -k $MNTDIR | awk '{getline;print $3}') * 110 / 100 ]
740        btrfs filesystem resize ${SIZE}k $MNTDIR
741        ;;
742    REISERFS|REISER4)
743        MNTDIR=$(ogMount $1 $2)
744        # Calcular tamaño ocupado + 10%.
745        SIZE=$[ $(df -k $MNTDIR | awk '{getline;print $3}') * 110 / 100 ]
746        ogUnmount $1 $2 2>/dev/null
747        resize_reiserfs -s${SIZE}K $PART
748        ;;
749    NTFS)
750        ogDeleteFile $1 $2 pagefile.sys
751        ogDeleteFile $1 $2 hiberfil.sys
752        ogUnmount $1 $2 2>/dev/null
753        ## NTFS: Obtiene tamaño mínimo en MB.
754        #SIZE=$(ntfsresize -fi $PART | awk '/resize at/ {print int($8*1.1)}')
755        #ntfsresize -fns "${SIZE}M" $PART >/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
756        #ntfsresize -fs "${SIZE}M" $PART <<<"y" >/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
757        SIZE=$(ogReduceFsCheck $1 $2)
758        [ "$SIZE" == 0 ] && return 1   
759        ntfsresize -fs "${SIZE}M" $PART <<<"y"  || ogRaiseError $OG_ERR_PARTITION "error reduciendo $1,$2" || return $?
760        ;;
761#    FAT32|FAT16)       # Usar "fatresize"
762#        ;;
763    *)  ogRaiseError $OG_ERR_PARTITION "$1,$2"
764        return $? ;;
765esac
766ogGetFsSize $1 $2
767}
768
769
770function ogReduceFsCheck ()
771{
772#IMPORTANTE: retorna el valor en MB que podrá reducir el FS de una particion ntfs
773#valor devuelto 0, y codigo error 1. No se puede reducir, probar a reiniciar windows y chkdsk
774
775
776local  PART RC MODE SIZE SIZEDATA
777[ $# == 2 ] && MODE=STAGE1
778[ $# == 3 ] && MODE=STAGE2
779[ -z $MODE ] && return
780
781PART="$(ogDiskToDev $1 $2)" || return $?
782ogUnmount $1 $2 &>/dev/null
783
784
785case $MODE in
786        STAGE1)
787        #       echo "primera etapa $*"
788                ntfsresize -fi $PART &>/dev/null
789                RC=`echo $?`
790        #       echo "RC es" $RC
791                if [ "$RC" -eq "1" ]
792                then
793                        echo "0"
794                        return 1       
795                fi 
796                SIZEDATA=$(ntfsresize -fi $PART | awk '/resize at/ {print $8+1000}')
797        #       echo "salida" $?
798        #       echo $SIZEDATA
799                ogReduceFsCheck $1 $2 $SIZEDATA
800                return 0
801       ;;
802        STAGE2)
803        #       echo "segunda etapa $*"
804                SIZEDATA=$3
805                ntfsresize -fns "${SIZEDATA}M" $PART &>/tmp/ntfsresize.txt
806                RC=$?
807                if [ "$RC" == "0" ]
808                then 
809                        SIZE=$SIZEDATA 
810                        echo $SIZE     
811                else
812                        SIZEEXTRA=$(cat /tmp/ntfsresize.txt | awk '/Needed relocations :/ {print $0}' | awk -F"(" '{print $2}' | awk '{print $1+500}')
813                        SIZE=$(expr $SIZEDATA + $SIZEEXTRA)
814                        ogReduceFsCheck $1 $2 $SIZE
815                        return 0
816                fi
817        ;;
818        *)
819        return
820        ;;
821esac
822}
823
824
825
826#/**
827#         ogUnlock int_ndisk int_npartition
828#@see     ogUnlockPartition
829#*/ ##
830function ogUnlock ()
831{
832ogUnlockPartition "$@"
833}
834
835#/**
836#         ogUnlockPartition int_ndisk int_npartition
837#@brief   Elimina el fichero de bloqueo para una particion.
838#@param   int_ndisk      nº de orden del disco
839#@param   int_npartition nº de orden de la partición
840#@return  (nada)
841#@exception OG_ERR_FORMAT    Formato incorrecto.
842#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
843#@note    El fichero de bloqueo se localiza en \c /var/lock/part, siendo \c part el dispositivo de la partición, sustituyendo el carácter "/" por "-".
844#@version 0.9 - Primera versión para OpenGnSys.
845#@author  Ramon Gomez, ETSII Universidad de Sevilla
846#@date    2009-09-03
847#*/ ##
848function ogUnlockPartition ()
849{
850# Variables locales
851local PART LOCKFILE
852
853# Si se solicita, mostrar ayuda.
854if [ "$*" == "help" ]; then
855    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
856           "$FUNCNAME 1 1"
857    return
858fi
859# Error si no se reciben 2 parámetros.
860[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
861
862# Obtener partición.
863PART="$(ogDiskToDev $1 $2)" || return $?
864
865# Borrar archivo de bloqueo exclusivo.
866LOCKFILE="/var/lock/lock${PART//\//-}"
867rm -f $LOCKFILE
868}
869
870
871#/**
872#         ogUnmount int_ndisk int_npartition
873#@see     ogUnmountFs
874#*/ ##
875function ogUnmount ()
876{
877ogUnmountFs "$@"
878}
879
880#/**
881#         ogUnmountFs int_ndisk int_nfilesys
882#@brief   Desmonta un sistema de archivos.
883#@param   int_ndisk      nº de orden del disco
884#@param   int_nfilesys   nº de orden del sistema de archivos
885#@return  Nada
886#@exception OG_ERR_FORMAT    Formato incorrecto.
887#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
888#@warning La partición no está previamente montada o no se puede desmontar.
889#@version 0.1 -  Integracion para Opengnsys  -  EAC:  UmountPartition() en FileSystem.lib
890#@author  Antonio J. Doblas Viso. Universidad de Malaga
891#@date    2008-10-27
892#@version 0.9 - Primera version para OpenGnSys.
893#@author  Ramon Gomez, ETSII Universidad de Sevilla
894#@date    2009-09-28
895#*/ ##
896function ogUnmountFs ()
897{
898# Variables locales
899local PART MNTDIR
900
901# Si se solicita, mostrar ayuda.
902if [ "$*" == "help" ]; then
903    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" "$FUNCNAME 1 1"
904    return
905fi
906# Error si no se reciben 2 parámetros.
907[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
908
909# Obtener partición y punto de montaje.
910PART="$(ogDiskToDev $1 $2)" || return $?
911MNTDIR="$(ogGetMountPoint $1 $2)"
912
913# Si está montada, desmontarla.
914if [ -n "$MNTDIR" ]; then
915    # Error si la particion está bloqueada.
916    if ogIsLocked $1 $2; then
917        ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION $1, $2"
918        return $?
919    fi
920    # Desmontar y borrar punto de montaje.
921    umount $PART 2>/dev/null || ogEcho warning "$FUNCNAME: $MSG_DONTUNMOUNT: \"$1, $2\""
922    rmdir $MNTDIR 2>/dev/null || rm -f $MNTDIR 2>/dev/null
923else
924    ogEcho warning "$MSG_DONTMOUNT: \"$1,$2\""
925fi
926}
927
928
929#/**
930#         ogUnmountAll int_ndisk
931#@brief   Desmonta todos los sistema de archivos de un disco, excepto el caché local.
932#@param   int_ndisk      nº de orden del disco
933#@return  Nada
934#@exception OG_ERR_FORMAT    Formato incorrecto.
935#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
936#@warning No se desmonta la partición marcada como caché local.
937#@version 0.9 - Versión para OpenGnSys.
938#@author  Ramon Gomez, ETSII Universidad de Sevilla
939#@date    2009/10/07
940#*/ ##
941function ogUnmountAll ()
942{
943# Variables locales
944local DISK PART
945# Si se solicita, mostrar ayuda.
946if [ "$*" == "help" ]; then
947    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" "FUNCNAME 1"
948    return
949fi
950# Error si no se recibe 1 parámetro.
951[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
952
953# Obtener partición y punto de montaje.
954DISK="$(ogDiskToDev $1)" || return $?
955for ((PART=1; PART<=$(ogGetPartitionsNumber $1); PART++)); do
956    case "$(ogGetFsType $1 $PART)" in
957        CACHE) ;;
958        *)     ogUnmount $1 $PART 2>/dev/null ;;
959    esac
960done
961}
962
963
964# AVISO:  Componer corretcamente esta función.
965function ogGetFreeSize () {
966local particion unit factor valor
967if [ $# = 0 ]
968then
969        echo "sintaxis: ogGetFreeSize int_disco int_partition str_SizeOutput [ kB MB GB -default GB]-]" red
970        echo "devuelve int_size : int_data : int_free" red
971return
972fi
973if [ $# -ge 2 ]
974then
975        particion=`ogMount $1 $2 ` #1>/dev/null 2>&1
976        if [ -z $3 ]
977                then
978                        unit=kB  # s B kB MB GB TB %
979                else
980                        unit=$3
981        fi
982        case $unit in
983                kB)
984                        factor="1.024";
985                        #valor=`df | grep  $particion | awk -F" " '{size=$2*1.024; used=$3*1.024; free=$4*1.024; printf "%d:%d:%d", size,used,free}'`
986                        valor=`df | grep  $particion | awk -F" " '{size=$2*1.024; used=$3*1.024; free=$4*1.024; printf "%d", free}'`
987                        ;;
988                MB)
989                        factor="1.024/1000";
990                        valor=`df | grep  $particion | awk -F" " '{size=$2*1.024/1000; used=$3*1.024/1000; free=$4*1.024/1000; printf "%d:%d:%d", size,used,free}'`
991                ;;
992                GB)
993                        factor="1.024/1000000";
994                        valor=`df | grep $particion | awk -F" " '{size=$2*1.024/1000000; used=$3*1.024/1000000; free=$4*1.024/1000000; printf "%f:%f:%f", size,used,free}'`
995                ;;
996        esac
997        #echo $valor
998        #NumberRound $valor
999        #valor=`NumberRound $valor`;
1000        echo $valor
1001fi
1002}
1003
Note: See TracBrowser for help on using the repository browser.