source: client/engine/FileSystem.lib @ 1616b6e

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 1616b6e was 1616b6e, checked in by ramon <ramongomez@…>, 14 years ago

Versión 1.0.2: función ogCheckFs solo devuelve errores de ejecución e ignora los códigos de salida de comprobación de sistema de archivos; función ogFormatFs inicia partición de swap.

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

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