source: client/engine/FileSystem.lib @ 4d2cdae

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 4d2cdae was c452625, checked in by ramon <ramongomez@…>, 12 years ago

#602: Ignorar operaciones aún no implementadas para algunos sistemas de archivos, evitando errores inadecuados.

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

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