source: client/engine/FileSystem.lib @ 4e1dc53

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

Versión 1.0.4, #531: Eliminar funciones duplicadas de FileSystem.lib.

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

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