source: client/engine/FileSystem.lib @ 452ade2

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 452ade2 was 452ade2, checked in by ramon <ramongomez@…>, 13 years ago

#142: Preparar soporte para sistemas de archivos ZFS, montar BTRFS, UFS y ZFS y extender BTRFS.

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