source: client/engine/FileSystem.lib @ 6539ab9

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 6539ab9 was 8971dc86, checked in by ramon <ramongomez@…>, 14 years ago

Version 1.0:

  • Corregir mensaje de error en función ogSetPartitionId.
  • Función ogGetFsType devuelve Ext3 como tipo por defecto para partición de tipo Linux, corrige errores de detección en funciones ogListPartitions, ogFormatFs, ogCheckFs, etc. (cerrar #355).

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

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