source: client/engine/FileSystem.lib @ 499a7ec

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 499a7ec was 49b2deb, checked in by irina <irinagomez@…>, 12 years ago

Comando ogReduceFsCheck muestra informacion de error del comando ntfsresize. Se usa al crear las imagenes

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

  • Property mode set to 100755
File size: 33.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#         ogIsLocked int_ndisk int_npartition
490#@brief   Comprueba si una partición está bloqueada por una operación de uso exclusivo.
491#@param   int_ndisk      nº de orden del disco
492#@param   int_npartition nº de orden de la partición
493#@return  Código de salida: 0 - bloqueado, 1 - sin bloquear o error.
494#@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 "-".
495#@version 0.9 - Primera versión para OpenGnSys.
496#@author  Ramon Gomez, ETSII Universidad de Sevilla
497#@date    2009-09-03
498#@version 1.0.1 - Devolver falso en caso de error.
499#@author  Ramon Gomez, ETSII Universidad de Sevilla
500#@date    2011-05-18
501#*/ ##
502function ogIsLocked ()
503{
504# Variables locales
505local PART LOCKFILE
506
507# Si se solicita, mostrar ayuda.
508if [ "$*" == "help" ]; then
509    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
510           "if $FUNCNAME 1 1; then ... ; fi"
511    return
512fi
513# Falso, en caso de error.
514[ $# == 2 ] || return 1
515
516# Obtener partición.
517PART="$(ogDiskToDev $1 $2)" || return 1
518
519# Comprobar existencia del fichero de bloqueo.
520LOCKFILE="/var/lock/lock${PART//\//-}"
521test -f $LOCKFILE
522}
523
524
525#/**
526#         ogIsMounted int_ndisk int_nfilesys
527#@brief   Comprueba si un sistema de archivos está montado.
528#@param   int_ndisk      nº de orden del disco
529#@param   int_nfilesys   nº de orden del sistema de archivos
530#@return  Código de salida: 0 - montado, 1 - sin montar o error.
531#@version 0.9 - Primera versión para OpenGnSys.
532#@author  Ramon Gomez, ETSII Universidad de Sevilla
533#@date    2009-10-15
534#@version 1.0.1 - Devolver falso en caso de error.
535#@author  Ramon Gomez, ETSII Universidad de Sevilla
536#@date    2011-05-18
537#*/ ##
538function ogIsMounted ()
539{
540# Si se solicita, mostrar ayuda.
541if [ "$*" == "help" ]; then
542    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
543           "if $FUNCNAME 1 1; then ... ; fi"
544    return
545fi
546# Falso, en caso de error.
547[ $# == 2 ] || return 1
548
549test -n "$(ogGetMountPoint $1 $2)"
550}
551
552
553#/**
554#         ogIsWritable int_ndisk int_nfilesys
555#@brief   Comprueba si un sistema de archivos está montado de lectura y escritura.
556#@param   int_ndisk      nº de orden del disco
557#@param   int_nfilesys   nº de orden del sistema de archivos
558#@return  Código de salida: 0 - lectura y escritura, 1 - solo lectura o no montado.
559#@version 1.0.5 - Primera versión para OpenGnSys.
560#@author  Ramon Gomez, ETSII Universidad de Sevilla
561#@date    2013-10-09
562#/**
563function ogIsWritable ()
564{
565# Variables locales
566local PART
567
568# Si se solicita, mostrar ayuda.
569if [ "$*" == "help" ]; then
570    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys" \
571           "if $FUNCNAME 1 1; then ... ; fi"
572    return
573fi
574# Falso, en caso de error.
575[ $# == 2 ] || return 1
576
577# Obtener partición.
578PART="$(ogDiskToDev $1 $2)" || return 1
579
580test -n "$(findmnt -n -o OPTIONS $PART | awk 'BEGIN {RS=","} /^rw$/ {print}')"
581}
582
583
584#/**
585#         ogLock int_ndisk int_npartition
586#@see     ogLockPartition
587#*/
588function ogLock ()
589{
590ogLockPartition "$@"
591}
592
593#/**
594#         ogLockPartition int_ndisk int_npartition
595#@brief   Genera un fichero de bloqueo para una partición en uso exlusivo.
596#@param   int_ndisk      nº de orden del disco
597#@param   int_npartition nº de orden de la partición
598#@return  (nada)
599#@exception OG_ERR_FORMAT    Formato incorrecto.
600#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
601#@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 "-".
602#@version 0.9 - Primera versión para OpenGnSys.
603#@author  Ramon Gomez, ETSII Universidad de Sevilla
604#@date    2009-09-03
605#*/ ##
606function ogLockPartition ()
607{
608# Variables locales
609local PART LOCKFILE
610
611# Si se solicita, mostrar ayuda.
612if [ "$*" == "help" ]; then
613    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
614           "$FUNCNAME 1 1"
615    return
616fi
617# Error si no se reciben 2 parámetros.
618[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
619
620# Obtener partición.
621PART="$(ogDiskToDev $1 $2)" || return $?
622
623# Crear archivo de bloqueo exclusivo.
624LOCKFILE="/var/lock/lock${PART//\//-}"
625touch $LOCKFILE
626}
627
628
629#/**
630#         ogMount int_ndisk int_nfilesys
631#@see     ogMountFs ogMountCache ogMountCdrom
632#*/ ##
633function ogMount ()
634{
635case "$*" in
636    CACHE|cache)
637        ogMountCache ;;
638    CDROM|cdrom)
639        ogMountCdrom ;;
640    *)  ogMountFs "$@" ;;
641esac
642}
643
644
645#/**
646#         ogMountFs int_ndisk int_nfilesys
647#@brief   Monta un sistema de archivos.
648#@param   int_ndisk      nº de orden del disco
649#@param   int_nfilesys   nº de orden del sistema de archivos
650#@return  Punto de montaje
651#@exception OG_ERR_FORMAT    Formato incorrecto.
652#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
653#@exception OG_ERR_PARTITION Tipo de particion desconocido o no se puede montar.
654#@version 0.1 -  Integracion para Opengnsys  -  EAC:   MountPartition() en FileSystem.lib
655#@author  Antonio J. Doblas Viso. Universidad de Malaga
656#@date    2008-10-27
657#@version 0.9 - Primera version para OpenGnSys.
658#@author  Ramon Gomez, ETSII Universidad de Sevilla
659#@date    2009-09-28
660#@version 1.0.5 - Independiente del tipo de sistema de ficheros.
661#@author  Ramon Gomez, ETSII Universidad de Sevilla
662#@date    2012-09-04
663#*/ ##
664function ogMountFs ()
665{
666# Variables locales
667local PART MNTDIR
668
669# Si se solicita, mostrar ayuda.
670if [ "$*" == "help" ]; then
671    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
672           "$FUNCNAME 1 1  =>  /mnt/sda1"
673    return
674fi
675# Error si no se reciben 2 parámetros.
676[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
677
678# Obtener partición.
679PART="$(ogDiskToDev "$1" "$2")" || return $?
680
681# Comprobar si el sistema de archivos ya está montada.
682MNTDIR="$(ogGetMountPoint $1 $2)"
683# Si no, montarlo en un directorio de sistema.
684if [ -z "$MNTDIR" ]; then
685    # Error si la particion esta bloqueada.
686    if ogIsLocked $1 $2; then
687        ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION, $1 $2"
688        return $?
689    fi
690    # Crear punto de montaje o enlace simbólico para caché local.
691    MNTDIR=${PART/dev/mnt}
692    if [ "$(ogFindCache)" == "$1 $2" -a -n "$OGCAC" ]; then
693        mkdir -p $OGCAC
694        ln -fs $OGCAC $MNTDIR
695    else
696        mkdir -p $MNTDIR
697    fi
698    # Montar sistema de archivos.
699    mount $PART $MNTDIR &>/dev/null || \
700               mount $PART $MNTDIR -o force,remove_hiberfile &>/dev/null || \
701               ogRaiseError $OG_ERR_PARTITION "$1, $2" || return $?
702fi
703echo "$MNTDIR"
704}
705
706
707#####  PRUEBAS
708# Montar CDROM
709function ogMountCdrom ()
710{
711local DEV MNTDIR
712DEV="/dev/cdrom"            # Por defecto
713MNTDIR=$(mount | awk -v D=$DEV '{if ($1==D) {print $3}}')
714if [ -z "$MNTDIR" ]; then
715    MNTDIR=${DEV/dev/mnt}
716    mkdir -p $MNTDIR
717    mount -t iso9660 $DEV $MNTDIR || ogRaiseError $OG_ERR_PARTITION "cdrom" || return $?
718fi
719echo $MNTDIR
720}
721
722
723#/**
724#         ogReduceFs int_ndisk int_nfilesys
725#@brief   Reduce el tamaño del sistema de archivos, sin tener en cuenta el espacio libre.
726#@param   int_ndisk      nº de orden del disco
727#@param   int_nfilesys   nº de orden del sistema de archivos
728#@return  int_tamañoKB - tamaño en KB
729#@exception OG_ERR_FORMAT    Formato incorrecto.
730#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
731#@exception OG_ERR_PARTITION Partición desconocida o no accesible.
732#@warning En Windows, se borran los ficheros pagefile.sys e hiberfile.sys
733#@warning El sistema de archivos se amplía al mínimo + 10%.
734#@note    Requisitos:   *resize*
735#@version 0.1 -  Integracion para Opengnsys  -  EAC:   ReduceFileSystem() en ATA.lib
736#@author  Antonio J. Doblas Viso. Universidad de Malaga
737#@date    2008-10-27
738#@version 0.9 - Primera version para OpenGnSys.
739#@author  Ramon Gomez, ETSII Universidad de Sevilla
740#@date    2009-09-23
741#@version 0.9.2 - Añadir un 10% al tamaño mínimo requerido.
742#@author  Ramon Gomez, ETSII Universidad de Sevilla
743#@date    2010-09-27
744#@version 1.0 -  Deteccion automatica del tamaño minimo adecuado
745#@author  Antonio J. Doblas Viso. Universidad de Malaga
746#@date    2011-02-24
747#*/ ##
748function ogReduceFs ()
749{
750# Variables locales
751local PART BLKS SIZE
752
753# Si se solicita, mostrar ayuda.
754if [ "$*" == "help" ]; then
755    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
756           "$FUNCNAME 1 1"
757    return
758fi
759# Error si no se reciben 2 parámetros.
760[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
761
762# Obtener partición.
763PART="$(ogDiskToDev $1 $2)" || return $?
764
765# Redimensionar según el tipo de particion.
766case "$(ogGetFsType $1 $2)" in
767    EXT[234])
768        ogUnmount $1 $2 2>/dev/null
769        # Ext2/3/4: Tamaño de los bloques del sistema de archivos
770        BLKS=$(tune2fs -l $PART | awk '/Block size/ {print int($3/512)}')
771        # Traduce el num. en sectores de 512B a tamano en MB.
772        #SIZE=$(resize2fs -P $PART 2>/dev/null | \
773                #       awk -v B=$BLKS '/minimum size/ {print int($7*1.1*B/2048)}')
774        #resize2fs -fp $PART "${SIZE}M" &>/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
775        resize2fs -fpM $PART  &>/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
776        ;;
777    BTRFS)
778        MNTDIR=$(ogMount $1 $2)
779        # Calcular tamaño ocupado + 10%.
780        SIZE=$[ $(df -k $MNTDIR | awk '{getline;print $3}') * 110 / 100 ]
781        btrfs filesystem resize ${SIZE}k $MNTDIR
782        ;;
783    REISERFS|REISER4)
784        MNTDIR=$(ogMount $1 $2)
785        # Calcular tamaño ocupado + 10%.
786        SIZE=$[ $(df -k $MNTDIR | awk '{getline;print $3}') * 110 / 100 ]
787        ogUnmount $1 $2 2>/dev/null
788        resize_reiserfs -s${SIZE}K $PART
789        ;;
790    JFS)    ;;          # No se reduce (por el momento).
791    XFS)    ;;          # No se reduce (por el momento).
792    NTFS)
793        ogDeleteFile $1 $2 pagefile.sys
794        ogDeleteFile $1 $2 hiberfil.sys
795        ogUnmount $1 $2 2>/dev/null
796        ## NTFS: Obtiene tamaño mínimo en MB.
797        #SIZE=$(ntfsresize -fi $PART | awk '/resize at/ {print int($8*1.1)}')
798        #ntfsresize -fns "${SIZE}M" $PART >/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
799        #ntfsresize -fs "${SIZE}M" $PART <<<"y" >/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
800        SIZE=$(ogReduceFsCheck $1 $2)
801        [ "$SIZE" == 0 ] && return 1   
802        ntfsresize -fs "${SIZE}M" $PART <<<"y"  || ogRaiseError $OG_ERR_PARTITION "error reduciendo $1,$2" || return $?
803        ;;
804    EXFAT)  ;;          # No se reduce (por el momento).
805    FAT32|FAT16)  ;;    # No se reduce (probar "fatresize").
806    HFS|HFSPLUS)  ;;    # No se reduce (por el momento).
807    UFS)    ;;          # No se reduce (por el momento).
808    *)  ogRaiseError $OG_ERR_PARTITION "$1,$2"
809        return $? ;;
810esac
811ogGetFsSize $1 $2
812}
813
814
815function ogReduceFsCheck ()
816{
817#IMPORTANTE: retorna el valor en MB que podrá reducir el FS de una particion ntfs
818#valor devuelto 0, y codigo error 1. No se puede reducir, probar a reiniciar windows y chkdsk
819
820
821local  PART RC MODE SIZE SIZEDATA
822[ $# == 2 ] && MODE=STAGE1
823[ $# == 3 ] && MODE=STAGE2
824[ -z $MODE ] && return
825
826PART="$(ogDiskToDev $1 $2)" || return $?
827ogUnmount $1 $2 &>/dev/null
828
829
830case $MODE in
831        STAGE1)
832        #       echo "primera etapa $*"
833                # Mostramos el error
834                #ntfsresize -fi $PART &>/dev/null
835                ntfsresize -fi $PART | grep -A 10 -e ERROR >&2
836                RC=`echo $?`
837        #       echo "RC es" $RC
838                # if [ "$RC" -eq "1" ] # con error la salida del grep es 0
839                if [ "$RC" -eq "0" ]
840                then
841                        echo "0"
842                        return 1       
843                fi 
844                SIZEDATA=$(ntfsresize -fi $PART | awk '/resize at/ {print $8+1000}')
845        #       echo "salida" $?
846        #       echo $SIZEDATA
847                ogReduceFsCheck $1 $2 $SIZEDATA
848                return 0
849       ;;
850        STAGE2)
851        #       echo "segunda etapa $*"
852                SIZEDATA=$3
853                ntfsresize -fns "${SIZEDATA}M" $PART &>/tmp/ntfsresize.txt
854                RC=$?
855                if [ "$RC" == "0" ]
856                then 
857                        SIZE=$SIZEDATA 
858                        echo $SIZE     
859                else
860                        SIZEEXTRA=$(cat /tmp/ntfsresize.txt | awk '/Needed relocations :/ {print $0}' | awk -F"(" '{print $2}' | awk '{print $1+500}')
861                        SIZE=$(expr $SIZEDATA + $SIZEEXTRA)
862                        ogReduceFsCheck $1 $2 $SIZE
863                        return 0
864                fi
865        ;;
866        *)
867        return
868        ;;
869esac
870}
871
872
873
874#/**
875#         ogUnlock int_ndisk int_npartition
876#@see     ogUnlockPartition
877#*/ ##
878function ogUnlock ()
879{
880ogUnlockPartition "$@"
881}
882
883#/**
884#         ogUnlockPartition int_ndisk int_npartition
885#@brief   Elimina el fichero de bloqueo para una particion.
886#@param   int_ndisk      nº de orden del disco
887#@param   int_npartition nº de orden de la partición
888#@return  (nada)
889#@exception OG_ERR_FORMAT    Formato incorrecto.
890#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
891#@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 "-".
892#@version 0.9 - Primera versión para OpenGnSys.
893#@author  Ramon Gomez, ETSII Universidad de Sevilla
894#@date    2009-09-03
895#*/ ##
896function ogUnlockPartition ()
897{
898# Variables locales
899local PART LOCKFILE
900
901# Si se solicita, mostrar ayuda.
902if [ "$*" == "help" ]; then
903    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
904           "$FUNCNAME 1 1"
905    return
906fi
907# Error si no se reciben 2 parámetros.
908[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
909
910# Obtener partición.
911PART="$(ogDiskToDev $1 $2)" || return $?
912
913# Borrar archivo de bloqueo exclusivo.
914LOCKFILE="/var/lock/lock${PART//\//-}"
915rm -f $LOCKFILE
916}
917
918
919#/**
920#         ogUnmount int_ndisk int_npartition
921#@see     ogUnmountFs
922#*/ ##
923function ogUnmount ()
924{
925ogUnmountFs "$@"
926}
927
928#/**
929#         ogUnmountFs int_ndisk int_nfilesys
930#@brief   Desmonta un sistema de archivos.
931#@param   int_ndisk      nº de orden del disco
932#@param   int_nfilesys   nº de orden del sistema de archivos
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 La partición no está previamente montada o no se puede desmontar.
937#@version 0.1 -  Integracion para Opengnsys  -  EAC:  UmountPartition() en FileSystem.lib
938#@author  Antonio J. Doblas Viso. Universidad de Malaga
939#@date    2008-10-27
940#@version 0.9 - Primera version para OpenGnSys.
941#@author  Ramon Gomez, ETSII Universidad de Sevilla
942#@date    2009-09-28
943#*/ ##
944function ogUnmountFs ()
945{
946# Variables locales
947local PART MNTDIR
948
949# Si se solicita, mostrar ayuda.
950if [ "$*" == "help" ]; then
951    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" "$FUNCNAME 1 1"
952    return
953fi
954# Error si no se reciben 2 parámetros.
955[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
956
957# Obtener partición y punto de montaje.
958PART="$(ogDiskToDev $1 $2)" || return $?
959MNTDIR="$(ogGetMountPoint $1 $2)"
960
961# Si está montada, desmontarla.
962if [ -n "$MNTDIR" ]; then
963    # Error si la particion está bloqueada.
964    if ogIsLocked $1 $2; then
965        ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION $1, $2"
966        return $?
967    fi
968    # Desmontar y borrar punto de montaje.
969    umount $PART 2>/dev/null || ogEcho warning "$FUNCNAME: $MSG_DONTUNMOUNT: \"$1, $2\""
970    rmdir $MNTDIR 2>/dev/null || rm -f $MNTDIR 2>/dev/null
971else
972    ogEcho warning "$MSG_DONTMOUNT: \"$1,$2\""
973fi
974}
975
976
977#/**
978#         ogUnmountAll int_ndisk
979#@brief   Desmonta todos los sistema de archivos de un disco, excepto el caché local.
980#@param   int_ndisk      nº de orden del disco
981#@return  Nada
982#@exception OG_ERR_FORMAT    Formato incorrecto.
983#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
984#@warning No se desmonta la partición marcada como caché local.
985#@version 0.9 - Versión para OpenGnSys.
986#@author  Ramon Gomez, ETSII Universidad de Sevilla
987#@date    2009/10/07
988#*/ ##
989function ogUnmountAll ()
990{
991# Variables locales
992local DISK PART
993# Si se solicita, mostrar ayuda.
994if [ "$*" == "help" ]; then
995    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" "FUNCNAME 1"
996    return
997fi
998# Error si no se recibe 1 parámetro.
999[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1000
1001# Obtener partición y punto de montaje.
1002DISK="$(ogDiskToDev $1)" || return $?
1003for ((PART=1; PART<=$(ogGetPartitionsNumber $1); PART++)); do
1004    case "$(ogGetFsType $1 $PART)" in
1005        CACHE) ;;
1006        *)     ogUnmount $1 $PART 2>/dev/null ;;
1007    esac
1008done
1009}
1010
1011
1012# AVISO:  Componer corretcamente esta función.
1013function ogGetFreeSize () {
1014local particion unit factor valor
1015if [ $# = 0 ]
1016then
1017        echo "sintaxis: ogGetFreeSize int_disco int_partition str_SizeOutput [ kB MB GB -default GB]-]" red
1018        echo "devuelve int_size : int_data : int_free" red
1019return
1020fi
1021if [ $# -ge 2 ]
1022then
1023        particion=`ogMount $1 $2 ` #1>/dev/null 2>&1
1024        if [ -z $3 ]
1025                then
1026                        unit=kB  # s B kB MB GB TB %
1027                else
1028                        unit=$3
1029        fi
1030        case $unit in
1031                kB)
1032                        factor="1.024";
1033                        #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}'`
1034                        valor=`df | grep  $particion | awk -F" " '{size=$2*1.024; used=$3*1.024; free=$4*1.024; printf "%d", free}'`
1035                        ;;
1036                MB)
1037                        factor="1.024/1000";
1038                        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}'`
1039                ;;
1040                GB)
1041                        factor="1.024/1000000";
1042                        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}'`
1043                ;;
1044        esac
1045        #echo $valor
1046        #NumberRound $valor
1047        #valor=`NumberRound $valor`;
1048        echo $valor
1049fi
1050}
1051
Note: See TracBrowser for help on using the repository browser.