source: client/engine/FileSystem.lib @ 039e025

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

#602: Función ogExtendFs comprueba correctamente que el sistema de ficheros se ha desmontado antes de extenderlo.

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

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