source: client/engine/FileSystem.lib @ 1cbf9e0

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 1cbf9e0 was 1cbf9e0, checked in by albertogp <albertogp@…>, 11 years ago

#541
Integrando cambios en version 1.0
Cambios en ficheros Cache.lib, Disk.lib, FileSystem?.lib, Image.lib

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

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