source: client/engine/FileSystem.lib @ e79df1d

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

Versión 1.0.5: Cambios en librería FileSystem:

  • Función ogGetFsType usa blkid en vez de mount, evitando mensajes en la consola local del cliente.
  • Función ogCheckFs soporta sistemas de ficheros Btrfs.

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

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