source: client/engine/FileSystem.lib @ 6903f32

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 6903f32 was 6e390b1, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.4, #531: Retoques en ayudas y en código para Doxygen.

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

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