source: client/engine/FileSystem.lib @ 3c2933e

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 3c2933e was 2fba27f, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.3: Función ogGetFsType detecta correctamente tipo LINUX-SWAP (cerrar #92).

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

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