source: client/engine/FileSystem.lib @ 47e0819

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 47e0819 was 3ffa256, checked in by ramon <ramongomez@…>, 13 years ago

#397 #551: Evitar que la función ogMoount entre en bucle y eliminar avisos en formulario de nueva aula.

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

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