source: client/engine/Image.lib @ ebe5709

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 ebe5709 was a30ad15f, checked in by ramon <ramongomez@…>, 9 years ago

#740: Corregir erratas en revisión r4872.

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

  • Property mode set to 100755
File size: 35.5 KB
RevLine 
[715bedc]1#!/bin/bash
2#/**
3#@file    Image.lib
4#@brief   Librería o clase Image
5#@class   Image
6#@brief   Funciones para creación, restauración y clonación de imágenes de sistemas.
[e39921b]7#@version 1.1.0
[715bedc]8#@warning License: GNU GPLv3+
9#*/
10
[914d834]11
[e39921b]12#/**
[2fc81c4]13#         ogCreateImageSyntax path_device path_filename [str_tool] [str_compressionlevel]
[914d834]14#@brief   Genera una cadena de texto con la instrucción para crear un fichero imagen
[bbe1bcf]15#@param   path_device           dispositivo Linux del sistema de archivos
[2fc81c4]16#@param   path_fileneme         path absoluto del fichero imagen
[bbe1bcf]17#@param   [opcional] str_tool   herrmaienta de clonacion [partimage, partclone, ntfsclone]
18#@param   [opcional] str_compressionlevel nivel de compresion. [0 -none-, 1-lzop-, 2-gzip]
19#@return  str_command - cadena con el comando que se debe ejecutar.
20#@warning Salida nula si se producen errores.
[914d834]21#@TODO    introducir las herramientas fsarchiver, dd
22#@version 1.0 - Primeras pruebas
23#@author  Antonio J. Doblas Viso. Universidad de Málaga
24#@date    2010/02/08
[bbe1bcf]25#@version 1.0.5 - Incrustar códico de antigua función ogPartcloneSyntax
26#@author  Ramon Gomez, ETSII Universidad de Sevilla
27#@date    2012/09/14
[914d834]28#*/ ##
29function ogCreateImageSyntax()
30{
[1feb465]31local FS TOOL LEVEL DEV IMGFILE BUFFER PARAM1 PARAM2 PARAM3
[914d834]32
33# Si se solicita, mostrar ayuda.
34if [ "$*" == "help" ]; then
[bbe1bcf]35    ogHelp "$FUNCNAME" "$FUNCNAME path_device path_imagefile [str_tool] [str_compressionlevel]" \
36           "$FUNCNAME /dev/sda1 /opt/opengnsys/images/prueba.img partclone lzop" \
37           "$FUNCNAME /dev/sda1 /opt/opengnsys/images/prueba.img"
[914d834]38    return
39fi
[2fc81c4]40# Error si no se reciben entre 2 y 4 parámetros.
41[ $# -ge 2 -a $# -le 4 ] || ogRaiseError $OG_ERR_FORMAT "$*" || return $?
[914d834]42
[2fc81c4]43# Asignación de parámetros.
[1feb465]44DEV="$1"
[bbe1bcf]45IMGFILE="$2"
[914d834]46case "$#" in
[1feb465]47    2)  # Sintaxis por defecto OG DEV IMGFILE
[bbe1bcf]48        TOOL="partclone"
49        LEVEL="gzip"
50        ;;
51    4)  # Sintaxis condicionada.
52        TOOL="${3,,}"
53        LEVEL="${4,,}"
54        ;;
55esac
[914d834]56
[bbe1bcf]57case "$TOOL" in
58    ntfsclone)
[1feb465]59        PARAM1="ntfsclone --force --save-image -O - $DEV"
[bbe1bcf]60        ;;
61    partimage|default)
[1feb465]62        PARAM1="partimage -M -f3 -o -d -B gui=no -c -z0 --volume=0 save $DEV stdout"
[bbe1bcf]63        ;;
64    partclone)
[1feb465]65        FS="$(ogGetFsType $(ogDevToDisk $DEV 2>/dev/null) 2>/dev/null)"
[bbe1bcf]66        case "$FS" in
67            EXT[234]) PARAM1="partclone.extfs" ;;
68            BTRFS)    PARAM1="partclone.btrfs" ;;
69            REISERFS) PARAM1="partclone.reiserfs" ;;
70            REISER4)  PARAM1="partclone.reiser4" ;;
71            JFS)      PARAM1="partclone.jfs" ;;
72            XFS)      PARAM1="partclone.xfs" ;;
73            NTFS)     PARAM1="partclone.ntfs" ;;
[9836a86]74            EXFAT)    PARAM1="partclone.exfat" ;;
[bbe1bcf]75            FAT16|FAT32) PARAM1="partclone.fat" ;;
76            HFS|HFSPLUS) PARAM1="partclone.hfsp" ;;
[9836a86]77            UFS)      PARAM1="partclone.ufs" ;;
[bbe1bcf]78            *)        PARAM1="partclone.dd" ;;
79        esac
[9836a86]80        # Por compatibilidad, si no existe el ejecutable usar por defecto "parclone.dd".
81        which $PARAM1 &>/dev/null || PARAM1="partclone.dd"
[1feb465]82        PARAM1="$PARAM1 -d0 -F -c -s $DEV"
[46a1ff9]83        # El programa partclone.dd no tiene opción "-c".
[a30ad15f]84        [[ "$PARAM1" =~ ^partclone.dd ]] && PARAM1="${PARAM1/ -c / }"
[1feb465]85        ;;
86esac
87# Comprobar que existe mbuffer.
[9836a86]88which mbuffer &>/dev/null && PARAM2="| mbuffer -q -m 40M " || PARAM2=" "
[bbe1bcf]89
90# Nivel de compresion.
91case "$LEVEL" in
92    0|none) PARAM3=" > " ;;
93    1|lzop) PARAM3=" | lzop > " ;;
94    2|gzip) PARAM3=" | gzip -c > " ;;
95    3|bzip) PARAM3=" | bzip -c > " ;;
[914d834]96esac
[bbe1bcf]97
98# Sintaxis final.
99[ -n "$PARAM1" ] && echo "$PARAM1 $PARAM2 $PARAM3 $IMGFILE"
[914d834]100}
101
102
103#/**
[2fc81c4]104#         ogRestoreImageSyntax path_filename path_device [str_tools] [str_compressionlevel]
[914d834]105#@brief   Genera una cadena de texto con la instrucción para crear un fichero imagen
[2fc81c4]106#@param   path_device           dispositivo Linux del sistema de archivos
107#@param   path_fileneme         path absoluto del fichero imagen
108#@param   [opcional] str_tools  herrmaienta de clonacion [partimage, partclone, ntfsclone]
109#@param   [opcional] str_compressionlevel nivel de compresion. [0 -none-, 1-lzop-, 2-gzip]
[914d834]110#@return  cadena con el comando que se debe ejecutar.
111#@exception OG_ERR_FORMAT    formato incorrecto.
112#@warning En pruebas iniciales
113#@TODO    introducir las herramientas fsarchiver, dd
114#@TODO    introducir el nivel de compresion gzip
115#@version 1.0 - Primeras pruebas
116#@author  Antonio J. Doblas Viso. Universidad de Málaga
117#@date    2010/02/08
118#*/ ##
[46a1ff9]119function ogRestoreImageSyntax ()
[914d834]120{
121local TOOL COMPRESSOR LEVEL PART IMGFILE FILEHEAD INFOIMG
122
123
124# Si se solicita, mostrar ayuda.
125if [ "$*" == "help" ]; then
126    ogHelp "$FUNCNAME" "$FUNCNAME  filename partition [tool] [levelcompresor]" \
127           "$FUNCNAME  /opt/opengnsys/images/prueba.img /dev/sda1 [partclone] [lzop]"
128    return
129fi
130
[2fc81c4]131# Error si no se reciben entre 2 y 4 parámetros.
132[ $# -ge 2 -a $# -le 4 ] || ogRaiseError $OG_ERR_FORMAT "$*" || return $?
[914d834]133
134# controlamos que el parametro 1 (imagen) es tipo file.
135[ -f $1 ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
136
137# Si 2 parametros (file-origen-, device-destino-) = ogGetImageFull($1)
138if [ "$#" -eq 2 ]; then
139        IMGFILE=$1
140        PART=$2
141        INFOIMG=$(ogGetImageInfo $IMGFILE) || ogRaiseError $OG_ERR_NOTFOUND "No Image $1" || return $?
142        TOOL=`echo $INFOIMG | cut -f1 -d:`
143        COMPRESSOR=`echo $INFOIMG | cut -f2 -d:`
144        ogRestoreImageSyntax $IMGFILE $PART $TOOL $COMPRESSOR
145fi
146
147
148# Si cuatro parametros genera sintaxis
149if [ "$#" -eq 4 ]; then
150        IMGFILE=$1
151        PART=$2
152        # comprobamos parametro herramienta compresion.
153        TOOL=$(echo $3 | tr [A-Z] [a-z])       
154        #ogCheckProgram $TOOL
155        #comprobar parámetro compresor.
156        LEVEL=$(echo $4 | tr [A-Z] [a-z])
157        #ogCheckProgram $LEVEL
158       
159        case "$LEVEL" in
160        "0"|"none")
161                COMPRESSOR=" "
162        ;;
163        "1"|"lzop" | "LZOP")
164                COMPRESSOR=" lzop -dc "
165        ;;
166        "2"|"gzip" | "GZIP")
167                COMPRESSOR=" gzip -dc "
168        ;;
169        "3"|"bzip" | "BZIP" )
170                COMPRESSOR=" bzip -dc "
171        ;;
172        *)
173                ogRaiseError $OG_ERR_NOTFOUND "Compressor no valid $TOOL" || return $?
174        ;;
175        esac
176    #comprobar mbuffer
177        which mbuffer > /dev/null && MBUFFER="| mbuffer -q -m 40M " || MBUFFER=" "
178
179        case "$TOOL" in
180                "ntfsclone" | "NTFSCLONE")
181                        TOOL="| ntfsclone --restore-image --overwrite $PART -"
182                ;;
183                "partimage"| "PARTIMAGE")
184                        TOOL="| partimage -f3 -B gui=no restore $PART stdin"
185                ;;
186                "partclone" | "PARTCLONE")
187                    # -C para que no compruebe tamaños
[0084b42]188                        TOOL="| partclone.restore -d0 -C -I -o $PART"
[914d834]189                ;;
[46a1ff9]190                partclone.dd)
[1feb465]191                        TOOL="| pv | dd conv=sync,noerror bs=1M of=$PART"
192                ;;
[914d834]193                *)
194                ogRaiseError $OG_ERR_NOTFOUND "Tools imaging no valid $TOOL" || return $?
195        ;;
196        esac
197
198        echo "$COMPRESSOR $IMGFILE $MBUFFER $TOOL"
199fi
200
201}
202
203
204
[715bedc]205
206#/**
[1c9ef24]207#         ogCreateDiskImage int_ndisk str_repo path_image [str_tools] [str_compressionlevel]
208#@brief   Crea una imagen (copia de seguridad) de un disco completo.
209#@param   int_ndisk      nº de orden del disco
210#@param   str_repo       repositorio de imágenes (remoto o caché local)
211#@param   path_image     camino de la imagen (sin extensión)
212#@return  (nada, por determinar)
213#@note    repo = { REPO, CACHE }
214#@note    Esta primera versión crea imágenes con dd comprimidas con gzip.
215#@exception OG_ERR_FORMAT    formato incorrecto.
216#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
217#@exception OG_ERR_LOCKED    particion bloqueada por otra operación.
218#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
219#@warning En pruebas iniciales
220#@todo    Gestión de bloqueos de disco
221#@todo    Comprobar si debe desmontarse la caché local
222#@todo    Comprobar que no se crea la imagen en el propio disco
223#@version 1.1.0 -  Primera versión para OpenGnsys con herramientas prefijadas.
224#@author  Ramon Gomez, ETSII Universidad de Sevilla
225#@Date    2016/04/08
226#*/ ##
227function ogCreateDiskImage ()
228{
229# Variables locales
230local DISK PROGRAM IMGDIR IMGFILE IMGTYPE ERRCODE
231
232# Si se solicita, mostrar ayuda.
233if [ "$*" == "help" ]; then
234    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk path_dir str_image" \
235           "$FUNCNAME 1 REPO /disk1"
236    return
237fi
238# Error si no se reciben entre 3 y 5 parámetros.
239[ $# -ge 3 -a $# -le 5 ] || ogRaiseError $OG_ERR_FORMAT "$*" || return $?
240
241# Comprobar que no está bloqueada ni la partición, ni la imagen.
242DISK="$(ogDiskToDev $1)" || return $?
[a30ad15f]243if ogIsDiskLocked $1; then
[1c9ef24]244    ogRaiseError $OG_ERR_LOCKED "$MSG_LOCKED $1"
245    return $?
246fi
247
248IMGTYPE="dsk"                   # Extensión genérica de imágenes de disco.
249IMGDIR=$(ogGetParentPath "$2" "$3")
250[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $?
251
252IMGFILE="$IMGDIR/$(basename "$3").$IMGTYPE"
253if ogIsImageLocked "$IMGFILE"; then
254    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $3, $4"
255    return $?
256fi
257# Generar la instruccion a ejecutar antes de aplicar los bloqueos.
[46a1ff9]258PROGRAM=$(ogCreateImageSyntax $DISK $IMGFILE)
[1c9ef24]259# Desmontar todos los sistemas de archivos del disco, bloquear partición e imagen.
260ogUnmountAll $1 2>/dev/null
261### Pendiente: bloquear disco
262ogLockDisk $1 || return $?
263ogLockImage "$2" "$3.$IMGTYPE" || return $?
264
265# Crear Imagen.
266trap "ogUnlockDisk $1; ogUnlockImage "$3" "$4.$IMGTYPE"; rm -f $IMGFILE" 1 2 3 6 9
267eval $PROGRAM
268
269# Controlar salida de error y desbloquear partición.
270ERRCODE=$?
271if [ $ERRCODE != 0 ]; then
272    ogRaiseError $OG_ERR_IMAGE "$1 $2 $IMGFILE"
273    rm -f "$IMGFILE"
274fi
275# Desbloquear partición e imagen.
276ogUnlockDisk $1
277ogUnlockImage "$2" "$3.$IMGTYPE"
278return $ERRCODE
279}
280
281
282
283#/**
[2fc81c4]284#         ogCreateImage int_ndisk int_npartition str_repo path_image [str_tools] [str_compressionlevel]
[715bedc]285#@brief   Crea una imagen a partir de una partición.
[42669ebf]286#@param   int_ndisk      nº de orden del disco
287#@param   int_npartition nº de orden de la partición
288#@param   str_repo       repositorio de imágenes (remoto o caché local)
289#@param   path_image     camino de la imagen (sin extensión)
[2fc81c4]290#@param   [opcional] str_tools  herrmaienta de clonacion [partimage, partclone, ntfsclone]
291#@param   [opcional] str_compressionlevel nivel de compresion. [0 -none-, 1-lzop-, 2-gzip]
[715bedc]292#@return  (nada, por determinar)
[ebf06c7]293#@note    repo = { REPO, CACHE }
[cfeabbf]294#@exception OG_ERR_FORMAT    formato incorrecto.
295#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
296#@exception OG_ERR_PARTITION partición no accesible o no soportada.
297#@exception OG_ERR_LOCKED    particion bloqueada por otra operación.
298#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
[3458879]299#@todo    Comprobaciones, control de errores, definir parámetros, etc.
[985bef0]300#@version 0.1 -  Integracion para Opengnsys  -  HIDRA:CrearImagen{EXT3, NTFS}.sh;  EAC: CreateImageFromPartition () en Deploy.lib
[bbe1bcf]301#@author  Ramon Gomez, ETSII Universidad de Sevilla
[985bef0]302#@Date    2008/05/13
303#@author  Antonio J. Doblas Viso. Universidad de Malaga
304#@date    2008/10/27
[0fbc05e]305#@version 0.9 - Versión en pruebas para OpenGnSys
[715bedc]306#@author  Ramon Gomez, ETSII Universidad de Sevilla
[cfeabbf]307#@date    2009/10/07
[bbe1bcf]308#@version 1.0 - Llama a función ogCreateImageSyntax para generar la llamada al comando.
309#@author  Antonio J. Doblas Viso. Universidad de Málaga
310#@date    2010/02/08
[1e7eaab]311#*/ ##
[42669ebf]312function ogCreateImage ()
313{
[59f9ad2]314# Variables locales
[08b941f]315local PART PROGRAM IMGDIR IMGFILE IMGTYPE ERRCODE
[59f9ad2]316
[42669ebf]317# Si se solicita, mostrar ayuda.
[59f9ad2]318if [ "$*" == "help" ]; then
319    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart path_dir str_image" \
[3543b3e]320           "$FUNCNAME 1 1 REPO /aula1/winxp"
[59f9ad2]321    return
322fi
[2fc81c4]323# Error si no se reciben entre 4 y 6 parámetros.
324[ $# -ge 4 -a $# -le 6 ] || ogRaiseError $OG_ERR_FORMAT "$*" || return $?
[59f9ad2]325
[08b941f]326# Comprobar que no está bloqueada ni la partición, ni la imagen.
[715bedc]327PART="$(ogDiskToDev $1 $2)" || return $?
[a79dd508]328if ogIsLocked $1 $2; then
[e39921b]329    ogRaiseError $OG_ERR_LOCKED "$MSG_LOCKED $1, $2"
[a79dd508]330    return $?
331fi
[a73649d]332
[914d834]333IMGTYPE="img"                   # Extensión genérica de imágenes.
[cfeabbf]334IMGDIR=$(ogGetParentPath "$3" "$4")
335[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$3 $(dirname $4)" || return $?
[a73649d]336
[08b941f]337IMGFILE="$IMGDIR/$(basename "$4").$IMGTYPE"
338if ogIsImageLocked "$IMGFILE"; then
339    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $3, $4"
340    return $?
341fi
[bbe1bcf]342# Generar la instruccion a ejecutar antes de aplicar los bloqueos.
343PROGRAM=$(ogCreateImageSyntax $PART $IMGFILE $5 $6)
[08b941f]344# Desmontar partición, bloquear partición e imagen.
[cfeabbf]345ogUnmount $1 $2 2>/dev/null
[a79dd508]346ogLock $1 $2 || return $?
[08b941f]347ogLockImage "$3" "$4.$IMGTYPE" || return $?
[715bedc]348
[08b941f]349# Crear Imagen.
350trap "ogUnlock $1 $2; ogUnlockImage "$3" "$4.$IMGTYPE"; rm -f $IMGFILE" 1 2 3 6 9
[914d834]351eval $PROGRAM
[08b941f]352
[42669ebf]353# Controlar salida de error y desbloquear partición.
[cfeabbf]354ERRCODE=$?
[f5432db7]355if [ $ERRCODE != 0 ]; then
[cfeabbf]356    ogRaiseError $OG_ERR_IMAGE "$1 $2 $IMGFILE"
[f5432db7]357    rm -f "$IMGFILE"
[cfeabbf]358fi
[08b941f]359# Desbloquear partición e imagen.
[715bedc]360ogUnlock $1 $2
[08b941f]361ogUnlockImage "$3" "$4.$IMGTYPE"
[cfeabbf]362return $ERRCODE
[715bedc]363}
364
[b094c59]365
[a25cc03]366#/**
367#         ogCreateMbrImage int_ndisk str_repo path_image
368#@brief   Crea una imagen a partir del sector de arranque de un disco.
369#@param   int_ndisk    nº de orden del disco
370#@param   str_repo     repositorio de imágenes (remoto o caché local)
371#@param   path_image   camino de la imagen (sin extensión)
372#@return  (nada, por determinar)
373#@note    repo = { REPO, CACHE }
374#@exception OG_ERR_FORMAT    formato incorrecto.
375#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
376#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
377#@version 0.9 - Versión en pruebas para OpenGNSys
378#@author  Ramon Gomez, ETSII Universidad de Sevilla
379#@date    2010/01/12
380#@version 1.0 - Adaptación a OpenGnSys 1.0
381#@author  Ramon Gomez, ETSII Universidad de Sevilla
382#@date    2011/03/10
383#*/ ##
384function ogCreateMbrImage ()
385{
386# Variables locales
387local DISK IMGDIR IMGFILE
388# Si se solicita, mostrar ayuda.
389if [ "$*" == "help" ]; then
390    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk path_dir str_image" \
391           "$FUNCNAME 1 REPO /aula1/mbr"
392    return
393fi
394# Error si no se reciben 3 parámetros.
[a73649d]395[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]396
397DISK=$(ogDiskToDev "$1") || return $?
398IMGDIR=$(ogGetParentPath "$2" "$3")
399[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $?
400IMGFILE="$IMGDIR/$(basename "$3").mbr"
401
402# Crear imagen del MBR.
403dd if="$DISK" of="$IMGFILE" bs=512 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
404}
405
406
407#/**
[b52e658]408#         ogCreateBootLoaderImage int_ndisk str_repo path_image
409#@brief   Crea una imagen del boot loader a partir del sector de arranque de un disco.
410#@param   int_ndisk    nº de orden del disco
411#@param   str_repo     repositorio de imágenes (remoto o caché local)
412#@param   path_image   camino de la imagen (sin extensión)
413#@return  (nada, por determinar)
414#@note    repo = { REPO, CACHE }
415#@exception OG_ERR_FORMAT    formato incorrecto.
416#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
417#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
418#@version 1.0 - Adaptacion de ogCreateMbrImage para guardar solo el Boot Loader
419#@author  Juan Carlos Xifre, SICUZ Universidad de Zaragoza
420#@date    2011/03/21
421#*/ ##
422function ogCreateBootLoaderImage ()
423{
424# Variables locales
425local DISK IMGDIR IMGFILE
426# Si se solicita, mostrar ayuda.
427if [ "$*" == "help" ]; then
428    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk path_dir str_image" \
429           "$FUNCNAME 1 REPO /aula1/mbr"
430    return
431fi
432# Error si no se reciben 3 parámetros.
[a73649d]433[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[b52e658]434
435DISK=$(ogDiskToDev "$1") || return $?
436IMGDIR=$(ogGetParentPath "$2" "$3")
437[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $?
438IMGFILE="$IMGDIR/$(basename "$3").mbr"
439
440# Crear imagen del Boot Loader dentro del MBR.
441dd if="$DISK" of="$IMGFILE" bs=446 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
442}
443
[d3dc88d]444#/**
445#         ogGetSizeParameters int_num_disk  int_num_part str_repo [monolit|sync|diff]
446#@brief   Devuelve el tamaño de los datos de un sistema de ficheros, el espacio necesario para la imagen y si cabe en el repositorio elegido.
447#@param   int_disk     numero de disco
448#@param   int_part     numero de particion
449#@param   str_repo     repositorio de imágenes   { REPO, CACHE }
450#@param   str_imageType Tipo de imagen: monolit (por defecto), sync o diff. (parametro opcional)
451#@return  SIZEDATA SIZEREQUIRED ISENOUGHSPACE
452#@note    si str_imageType= diff necesario /tmp/ogimg.info, que es creado por ogCreateInfoImage.
453#@exception OG_ERR_FORMAT    formato incorrecto.
454#@author  Irina Gomez, ETSII Universidad de Sevilla
455#@date    2014/10/24
456#*/ ##
457function ogGetSizeParameters ()
458{
459local MNTDIR SIZEDATA KERNELVERSION SIZEREQUIRED FACTORGZIP FACTORLZOP SIZEFREE
460# Si se solicita, mostrar ayuda.
461if [ "$*" == "help" ]; then
462    ogHelp "$FUNCNAME" "$FUNCNAME num_disk num_part str_repo [monolic|sync|diff]" \
463           "if $FUNCNAME 1 2 REPO sync ; then ...; fi" \
464           "if $FUNCNAME 1 6 CACHE ; then ...; fi"
465    return
466fi
467# Error si no se reciben 1 o 2 parámetros.
468[ $# -lt 3 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion REPO|CACHE [monolitic|sync]" ; echo $?)
469
470MNTDIR=$(ogMount $1 $2)
471if [ "$MNTDIR" == "" ]; then
472    ogRaiseError $OG_ERR_PARTITION "$1 $2"
473    return $?
474fi
475
476# Datos contenidos en la particion o en la lista de archivos de contiene la diferencial.
477if [ "_${4^^}_" == "_DIFF_" ]; then
478        [ -r /tmp/ogimg.info ] || return $(ogRaiseError session $OG_ERR_NOTFOUND "/tmp/ogimg.info"; echo $?)
479        cd $MNTDIR
480        SIZEDATA=$(grep -v "\/$" /tmp/ogimg.info | tr '\n' '\0'| du -x -c --files0-from=- 2>/dev/null|tail -n1 |cut -f1)
481else
482        SIZEDATA=$(df -k | grep $MNTDIR | awk '{print $3}')
483fi
484
485#Aplicar factor de compresion
486if [ "_${4^^}_" == "_SYNC_" -o "_${4^^}_" == "_DIFF_" ]; then
487       
488        # Sistema de fichero de la imagen según kernel, menor que 3.7 EXT4. comparamos revision
489        KERNELVERSION=$(uname -r| awk '{printf("%d",$1);sub(/[0-9]*\./,"",$1);printf(".%02d",$1)}')
490        [ $KERNELVERSION \< 3.07 ] &&  IMGFS="EXT4" || IMGFS=${IMGFS:-"BTRFS"}
491        FACTORSYNC=${FACTORSYNC:-"120"}
492        # Si IMGFS="BTRFS" la compresion es mayor.
[81ae95c]493        [ $IMGFS == "BTRFS" ] && let FACTORSYNC=$FACTORSYNC-20
[d3dc88d]494
495        let SIZEREQUIRED=$SIZEDATA*$FACTORSYNC/100
496        # El tamaño mínimo del sistema de ficheros btrfs es 250M, ponemos 300
497        [ $SIZEREQUIRED -lt 300000 ] && SIZEREQUIRED=300000
498       
499else
500        FACTORGZIP=55/100
501        FACTORLZOP=65/100
502        let SIZEREQUIRED=$SIZEDATA*$FACTORLZOP
503fi
504
505#Comprobar espacio libre en el contenedor.
506[ "${3^^}" == "CACHE" ] && SIZEFREE=$(ogGetFreeSize `ogFindCache`)
507[ "${3^^}" == "REPO" ] && SIZEFREE=$(df -k | grep $OGIMG | awk '{print $4}')
508
509[ "$SIZEREQUIRED" -lt "$SIZEFREE" ] && ISENOUGHSPACE=TRUE  ||  ISENOUGHSPACE=FALSE
510
511echo $SIZEDATA $SIZEREQUIRED $ISENOUGHSPACE
512
513
514}
[cbbb046]515
[b52e658]516#/**
[a25cc03]517#         ogIsImageLocked [str_repo] path_image
518#@brief   Comprueba si una imagen está bloqueada para uso exclusivo.
519#@param   str_repo     repositorio de imágenes (opcional)
520#@param   path_image   camino de la imagen (sin extensión)
[7685100]521#@return  Código de salida: 0 - bloqueado, 1 - sin bloquear o error.
[a25cc03]522#@note    repo = { REPO, CACHE }
523#@exception OG_ERR_FORMAT    formato incorrecto.
524#@version 1.0 - Adaptación a OpenGnSys 1.0
525#@author  Ramon Gomez, ETSII Universidad de Sevilla
526#@date    2011/03/10
[7685100]527#@version 1.0.1 - Devolver falso en caso de error.
528#@author  Ramon Gomez, ETSII Universidad de Sevilla
529#@date    2011-05-18
[a25cc03]530#*/ ##
531function ogIsImageLocked ()
532{
533# Si se solicita, mostrar ayuda.
534if [ "$*" == "help" ]; then
535    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
536           "if $FUNCNAME /opt/opengnsys/images/aula1/winxp.img; then ...; fi" \
537           "if $FUNCNAME REPO /aula1/winxp.img; then ...; fi"
538    return
539fi
540# Error si no se reciben 1 o 2 parámetros.
[7685100]541[ $# -lt 1 -o $# -gt 2 ] && return 1
[914d834]542
[a25cc03]543# Comprobar si existe el fichero de bloqueo.
544test -n "$(ogGetPath $@.lock)"
545}
[914d834]546
547
[a25cc03]548#/**
549#         ogLockImage [str_repo] path_image
550#@brief   Bloquea una imagen para uso exclusivo.
551#@param   str_repo     repositorio de imágenes (opcional)
552#@param   path_image   camino de la imagen (sin extensión)
553#@return  Nada.
554#@note    Se genera un fichero con extensión .lock
555#@note    repo = { REPO, CACHE }
556#@exception OG_ERR_FORMAT    formato incorrecto.
557#@version 1.0 - Adaptación a OpenGnSys 1.0
558#@author  Ramon Gomez, ETSII Universidad de Sevilla
559#@date    2011/03/10
560#*/ ##
561function ogLockImage ()
562{
563# Variables locales
564local IMGDIR
[914d834]565
[a25cc03]566# Si se solicita, mostrar ayuda.
567if [ "$*" == "help" ]; then
568    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
569           "$FUNCNAME /opt/opengnsys/images/aula1/winxp.img" \
570           "$FUNCNAME REPO /aula1/winxp.img"
571    return
572fi
573# Error si no se reciben 1 o 2 parámetros.
[a73649d]574[ $# == 1 -o $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]575# Comprobar que existe directorio de imagen
576IMGDIR=$(ogGetParentPath $@) || return $?
577# Crear fichero de bloqueo.
[a73649d]578touch $IMGDIR/$(basename "${!#}").lock 2>/dev/null || ogRaiseError $OG_ERR_NOTWRITE "$*" || return $?
[a25cc03]579}
[914d834]580
581
582#/**
[e39921b]583#         ogRestoreDiskImage str_repo path_image int_npartition
584#@brief   Restaura (recupera) una imagen de un disco completo.
585#@param   str_repo       repositorio de imágenes o caché local
586#@param   path_image     camino de la imagen
587#@param   int_ndisk      nº de orden del disco
588#@return  (por determinar)
589#@warning Primera versión en pruebas
590#@todo    Gestionar bloqueos de disco
591#@todo    Comprobar que no se intenta restaurar de la caché sobre el mismo disco
592#@exception OG_ERR_FORMAT    formato incorrecto.
593#@exception OG_ERR_NOTFOUND  fichero de imagen o partición no detectados.
594#@exception OG_ERR_LOCKED    partición bloqueada por otra operación.
595#@exception OG_ERR_IMAGE     error al restaurar la imagen del sistema.
596#@exception OG_ERR_IMGSIZEPARTITION  Tamaño de la particion es menor al tamaño de la imagen.
597#@version 1.1.0 - Primera versión para OpenGnsys.
598#@author Ramon Gomez, ETSII Universidad de Sevilla
[1c9ef24]599#@Date    2016/04/08
[e39921b]600#*/ ##
601function ogRestoreDiskImage ()
602{
603# Variables locales
604local DISK DISKSIZE IMGFILE IMGTYPE IMGSIZE PROGRAM ERRCODE
605
606# Si se solicita, mostrar ayuda.
607if [ "$*" == "help" ]; then
608    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \
609           "$FUNCNAME REPO /aula1/winxp 1"
610    return
611fi
612# Error si no se reciben 4 parámetros.
613[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
614# Procesar parámetros.
615DISK="$(ogDiskToDev $3)" || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
616IMGTYPE="dsk"
617IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE")
618[ -r "$IMGFILE" ] || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
619
620# comprobamos consistencia de la imagen
[1c9ef24]621ogGetImageInfo $IMGFILE >/dev/null  || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
[e39921b]622# Error si la imagen no cabe en la particion.
623#IMGSIZE=$(ogGetImageSize "$1" "$2") || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
624#DISKSIZE=$(ogGetDiskSize $3)
625#if [ $IMGSIZE -gt $DISKSIZE ]; then
626#    ogRaiseError $OG_ERR_IMGSIZEPARTITION "$DISKSIZE < $IMGSIZE"
627#    return $?
628#fi
629# Comprobar el bloqueo de la imagen y de la partición.
630if ogIsImageLocked "$IMGFILE"; then
631    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $1, $2.$IMGTYPE"
632    return $?
[1feb465]633fi
[e39921b]634# Solicitamos la generación de la instruccion a ejecutar
[1feb465]635PROGRAM=$(ogRestoreImageSyntax $IMGFILE $DISK)
[e39921b]636
637# Bloquear el disco
[1c9ef24]638ogLockDisk $3 || return $?
639trap "ogUnlockDisk $3" 1 2 3 6 9
[e39921b]640
641# Ejecutar restauración según el tipo de imagen.
642eval $PROGRAM
643
644ERRCODE=$?
645if [ $ERRCODE != 0 ]; then
646    ogRaiseError $OG_ERR_IMAGE "$IMGFILE, $3, $4"
647fi
[1c9ef24]648ogUnlockDisk $3 $4
[e39921b]649return $ERRCODE
650}
651
652
653#/**
[914d834]654#         ogRestoreImage str_repo path_image int_ndisk int_npartition
655#@brief   Restaura una imagen de sistema de archivos en una partición.
656#@param   str_repo       repositorio de imágenes o caché local
657#@param   path_image     camino de la imagen
658#@param   int_ndisk      nº de orden del disco
659#@param   int_npartition nº de orden de la partición
660#@return  (por determinar)
[8e83677]661#@exception OG_ERR_FORMAT   1 formato incorrecto.
662#@exception OG_ERR_NOTFOUND  2 fichero de imagen o partición no detectados.
663#@exception OG_ERR_PARTITION 3  # Error en partición de disco.
664#@exception OG_ERR_LOCKED    4 partición bloqueada por otra operación.
665#@exception OG_ERR_IMAGE    5 error al restaurar la imagen del sistema.
666#@exception OG_ERR_IMGSIZEPARTITION  30 Tamaño de la particion es menor al tamaño de la imagen.
[914d834]667#@todo    Comprobar incongruencias partición-imagen, control de errores, definir parámetros, caché/repositorio, etc.
668#@version 0.1 -  Integracion para Opengnsys  - HIDRA:RestaurarImagen{EXT3, NTFS}.sh;  EAC: RestorePartitionFromImage() en Deploy.lib
669#@author Ramon Gomez, ETSII Universidad de Sevilla
670#@Date    2008/05/13
671#@author  Antonio J. Doblas Viso. Universidad de Malaga
672#@date    2008/10/27
673#@version 0.9 - Primera version muy en pruebas para OpenGnSys
674#@author  Ramon Gomez, ETSII Universidad de Sevilla
675#@date    2009/09/10
[8e83677]676#@version 1.0 - generacion sintaxis de restauracion
677#@author  Antonio J. Doblas Viso, Universidad de Malaga
678#@date    2011/02/01
679#@version 1.0.1 - Control errores, tamaño particion, fichero-imagen
680#@author  Antonio J. Doblas Viso, Universidad de Malaga
681#@date    2011/05/11
[914d834]682#*/ ##
683function ogRestoreImage ()
684{
685# Variables locales
[cbbb046]686local PART PARTSIZE IMGFILE IMGTYPE IMGSIZE FSTYPE PROGRAM ERRCODE
[914d834]687
688# Si se solicita, mostrar ayuda.
689if [ "$*" == "help" ]; then
690    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk int_npart" \
691           "$FUNCNAME REPO /aula1/winxp 1 1"
692    return
693fi
694# Error si no se reciben 4 parámetros.
[1f03f6e]695[ $# == 4 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[914d834]696# Procesar parámetros.
[8e83677]697PART="$(ogDiskToDev $3 $4)" || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
[914d834]698#IMGTYPE=$(ogGetImageType "$1" "$2")
699IMGTYPE=img
[8e83677]700IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE")
701[ -r "$IMGFILE" ] || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
702# comprobamos consistencia de la imagen
703ogGetImageInfo $IMGFILE >/dev/null  || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
704
[914d834]705# Error si la imagen no cabe en la particion.
[8e83677]706IMGSIZE=$(ogGetImageSize "$1" "$2") || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
[be3b96a]707#TODO:
[8e83677]708#Si la particion no esta formateado o tiene problemas formateamos
709ogMount $3 $4 || ogFormat $3 $4
[f8b1b41]710PARTSIZE=$(ogGetPartitionSize $3 $4)
[914d834]711if [ $IMGSIZE -gt $PARTSIZE ]; then
[8e83677]712    ogRaiseError $OG_ERR_IMGSIZEPARTITION "  $PARTSIZE < $IMGSIZE"
[914d834]713    return $?
714fi
715# Comprobar el bloqueo de la imagen y de la partición.
716if ogIsImageLocked "$IMGFILE"; then
717    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $1, $2.$IMGTYPE"
718    return $?
719fi
720if ogIsLocked $3 $4; then
721    ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION $3, $4"
722    return $?
723fi
[2fc81c4]724
725# Solicitamos la generación de la instruccion a ejecutar
726# Atención: no se comprueba el tipo de sistema de archivos.
727# Atención: no se comprueba incongruencia entre partición e imagen.
728PROGRAM=`ogRestoreImageSyntax  $IMGFILE $PART`
729
[914d834]730# Desmontar y bloquear partición.
[8e83677]731ogUnmount $3 $4 2>/dev/null || return $(ogRaiseError $OG_ERR_PARTITION " $3 $4"; echo $?)
[a73649d]732ogLock $3 $4 || return $?
[914d834]733trap "ogUnlock $3 $4" 1 2 3 6 9
734
[2fc81c4]735# Ejecutar restauración según el tipo de imagen.
[914d834]736eval $PROGRAM
737
738ERRCODE=$?
739if [ $ERRCODE != 0 ]; then
740    ogRaiseError $OG_ERR_IMAGE "$IMGFILE, $3, $4"
741fi
742ogUnlock $3 $4
743return $ERRCODE
744}
745
746
747#/**
[a25cc03]748#         ogRestoreMbrImage str_repo path_image int_ndisk
749#@brief   Restaura la imagen del sector de arranque de un disco.
750#@param   str_repo     repositorio de imágenes o caché local
751#@param   path_image   camino de la imagen
752#@param   int_ndisk    nº de orden del disco
753#@return  (por determinar)
754#@exception OG_ERR_FORMAT   formato incorrecto.
755#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
756#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
757#@version 0.9 - Primera versión en pruebas.
758#@author  Ramon Gomez, ETSII Universidad de Sevilla
759#@date    2010/01/12
760#@version 1.0 - Adaptación a OpenGnSys 1.0
761#@author  Ramon Gomez, ETSII Universidad de Sevilla
762#@date    2011/03/10
763#*/ ##
764function ogRestoreMbrImage ()
765{
766# Variables locales
767local DISK IMGFILE
768# Si se solicita, mostrar ayuda.
769if [ "$*" == "help" ]; then
770    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \
771           "$FUNCNAME REPO /aula1/mbr 1"
772    return
773fi
774# Error si no se reciben 3 parámetros.
[a73649d]775[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]776# Procesar parámetros.
777DISK=$(ogDiskToDev "$3") || return $?
778IMGFILE=$(ogGetPath "$1" "$2.mbr") || return $?
[8e65e89]779[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[a25cc03]780
781# Restaurar imagen del MBR.
782dd if="$IMGFILE" of="$DISK" bs=512 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
783}
784
785
786#/**
[b52e658]787#         ogRestoreBootLoaderImage str_repo path_image int_ndisk
788#@brief   Restaura la imagen del boot loader del sector de arranque de un disco.
789#@param   str_repo     repositorio de imágenes o caché local
790#@param   path_image   camino de la imagen
791#@param   int_ndisk    nº de orden del disco
792#@return  (por determinar)
793#@exception OG_ERR_FORMAT   formato incorrecto.
794#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
795#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
796#@version 1.0 - Adaptacion de ogRestoreMbrImage para restaurar solo el Boot Loader
797#@author  Juan Carlos Xifre, SICUZ Universidad de Zaragoza
798#@date    2011/03/21
799#*/ ##
800function ogRestoreBootLoaderImage ()
801{
802# Variables locales
803local DISK IMGFILE
804# Si se solicita, mostrar ayuda.
805if [ "$*" == "help" ]; then
806    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \
807           "$FUNCNAME REPO /aula1/mbr 1"
808    return
809fi
810# Error si no se reciben 3 parámetros.
[a73649d]811[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[b52e658]812# Procesar parámetros.
813DISK=$(ogDiskToDev "$3") || return $?
814IMGFILE=$(ogGetPath "$1" "$2.mbr") || return $?
[8e65e89]815[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[b52e658]816
817# Restaurar imagen del MBR.
818dd if="$IMGFILE" of="$DISK" bs=446 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
819}
820
821#/**
[a25cc03]822#         ogUnlockImage [str_repo] path_image
823#@brief   Desbloquea una imagen con uso exclusivo.
824#@param   str_repo     repositorio de imágenes (opcional)
825#@param   path_image   camino de la imagen (sin extensión)
826#@return  Nada.
827#@note    repo = { REPO, CACHE }
828#@note    Se elimina el fichero de bloqueo con extensión .lock
829#@exception OG_ERR_FORMAT    formato incorrecto.
830#@version 1.0 - Adaptación a OpenGnSys 1.0
831#@author  Ramon Gomez, ETSII Universidad de Sevilla
832#@date    2011/03/10
833#*/ ##
834function ogUnlockImage ()
835{
836# Si se solicita, mostrar ayuda.
837if [ "$*" == "help" ]; then
838    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
839           "$FUNCNAME /opt/opengnsys/images/aula1/winxp.img" \
840           "$FUNCNAME REPO /aula1/winxp.img"
841    return
842fi
843# Error si no se reciben 1 o 2 parámetros.
[a73649d]844[ $# == 1 -o $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]845
846# Borrar fichero de bloqueo para la imagen.
847rm -f $(ogGetPath $@.lock)
848}
849
850
851#/**
[914d834]852#         ogGetImageInfo filename
853#@brief   muestra información sobre la imagen monolitica.
854#@param 1   filename           path absoluto del fichero imagen
855#@return  cadena compuesta por clonacion:compresor:sistemaarchivos:tamañoKB
856#@exception OG_ERR_FORMAT    formato incorrecto.
857#@exception OG_ERR_NOTFOUND   fichero no encontrado.
858#@exception OG_ERR_IMAGE        "Image format is not valid $IMGFILE"
859#@warning En pruebas iniciales
860#@TODO    Definir sintaxis de salida (herramienta y compresor en minuscula)
861#@TODO    Arreglar loop para ntfsclone
862#@TODO    insertar parametros entrada tipo OG
863#@version 1.0 - Primeras pruebas
864#@author  Antonio J. Doblas Viso. Universidad de Málaga
865#@date    2010/02/08
866#*/ ##
867
[cbbb046]868function ogGetImageInfo ()
869{
[914d834]870# Si se solicita, mostrar ayuda.
871if [ "$*" == "help" ]; then
872    ogHelp "$FUNCNAME" "$FUNCNAME  filename " \
873           "$FUNCNAME  /opt/opengnsys/images/prueba.img "
874    return
875fi
876
877# Error si no se reciben 1 parámetros.
878[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
879
880#comprobando que el parametro uno es un file.
881[ -f $1 ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
882
[51953ae]883local TOOLS COMPRESSOR IMGFILE FILEHEAD FS FSPLUS SIZE SIZEFACTOR PARTIMAGEINFO PARTCLONEINFO NTFSCLONEINFO IMGDETECT
[914d834]884IMGDETECT="FALSE"
885
886IMGFILE=$1
887FILEHEAD=/tmp/`basename $IMGFILE`.infohead
888COMPRESSOR=`file $IMGFILE | awk '{print $2}'`
889ogCheckStringInGroup "$COMPRESSOR" "gzip lzop" || ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
890$($COMPRESSOR -dc $IMGFILE 2>/dev/null | head > $FILEHEAD) || ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
891
892## buscando Primera opción.
893if [ "$IMGDETECT" == "FALSE" ]
894then
[8e9669e]895        PARTCLONEINFO=$(LC_ALL=C partclone.info $FILEHEAD 2>&1)
[914d834]896        if `echo $PARTCLONEINFO | grep size > /dev/null`
897        then
898                TOOLS=PARTCLONE
899                FS=$(echo $PARTCLONEINFO | awk '{gsub(/\: /,"\n"); print toupper($8);}')
[d2f8c5a]900                if [[ "$FS" == "HFS" || "$FS" == "HFSPLUS" || "$FS" == "FAT32" ]]; then
[1cbf9e0]901                        FSPLUS=$(echo $PARTCLONEINFO | awk '{gsub(/\: /,"\n"); print toupper($9);}')
902                        echo $PARTCLONEINFO | grep GB > /dev/null && SIZEFACTOR=1000000 || SIZEFACTOR=1024
[1131208]903                        if [ "$FSPLUS" == "PLUS" ]; then
[1cbf9e0]904                                FS=$FS$FSPLUS
905                                SIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{printf "%d\n", $17*FACTOR;}')
906                        else
907                                SIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{printf "%d\n", $16*FACTOR;}')
908                        fi
909                else
910                        echo $PARTCLONEINFO | grep GB > /dev/null && SIZEFACTOR=1000000 || SIZEFACTOR=1024
911                        SIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{gsub(/\: /,"\n"); printf "%d\n", $11*FACTOR;}')
912                fi
[914d834]913                IMGDETECT="TRUE"
914        fi
915fi
916#buscando segunda opcion.
917if [ "$IMGDETECT" == "FALSE" -a ! -f /dev/loop2  ]
918then
919        cat $FILEHEAD | grep -w ntfsclone-image > /dev/null && NTFSCLONEINFO=$(cat $FILEHEAD | ntfsclone --restore --overwrite /dev/loop2 - 2>&1)
920        if `echo $NTFSCLONEINFO | grep ntfsclone > /dev/null` 
921        then
922                TOOLS=NTFSCLONE
923                SIZE=$(echo $NTFSCLONEINFO | awk '{gsub(/\(|\)|\./,""); printf "%d\n",$17/1000;}')
924                FS=NTFS
925                IMGDETECT="TRUE"
926        fi
927fi
928## buscando Tercer opción.
929if [ "$IMGDETECT" == "FALSE" ]
930then
931        PARTIMAGEINFO=$(partimage -B gui=no imginfo "$FILEHEAD" 2>&1)
932        if `echo $PARTIMAGEINFO | grep Partition > /dev/null`
933        then   
934                TOOLS=PARTIMAGE
935                FS=$(echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $17;}' | awk '{sub(/\.\.+/," "); print toupper($2)}')
936                SIZE=$( echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $36;}' | awk '{sub(/\.\.+/," "); printf "%d\n",$2*1024*1024;}')
937                IMGDETECT="TRUE"
[1feb465]938        fi
939        if file $FILEHEAD 2> /dev/null | grep -q "boot sector"; then
[a30ad15f]940                TOOLS="partclone.dd"
[1feb465]941                FS=
942                SIZE=
943                IMGDETECT="TRUE"
944        fi
[914d834]945fi
946#comprobamos valores #Chequeamos los valores devueltos.
947if [ -z "$TOOLS" -o -z "$COMPRESSOR" -o "$IMGDETECT" == "FALSE" ]
948then
949        ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
950else
951        COMPRESSOR=$(echo $COMPRESSOR | tr [a-z] [A-Z])
952        echo $TOOLS:$COMPRESSOR:$FS:$SIZE
953fi
954}
955
956function ogGetImageProgram ()
957{
958local IMGFILE
959IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
[8e65e89]960[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]961ogGetImageInfo $IMGFILE | awk -F: '{print $1}'
962
963}
964
965function ogGetImageCompressor ()
966{
967local IMGFILE
968IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
[8e65e89]969[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]970ogGetImageInfo $IMGFILE | awk -F: '{print $2}'
971}
972
973function ogGetImageType ()
974{
975local IMGFILE
976IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
[8e65e89]977[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]978#partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
979#        awk '/^Filesystem/ {sub(/\.\.+/," "); sub(/fs$/,""); print toupper($2);}'
980ogGetImageInfo $IMGFILE | awk -F: '{print $3}'
981
982}
983
984function ogGetImageSize ()
985{
986# Variables locales
987local IMGFILE
988
989# Si se solicita, mostrar ayuda.
990if [ "$*" == "help" ]; then
[8e83677]991    ogHelp "$FUNCNAME" "$FUNCNAME REPO|CACHE /str_image" \
992           "$FUNCNAME REPO /aula1/winxp  ==>  5642158"
[914d834]993    return
994fi
[a73649d]995# Error si no se reciben 2 parámetros.
996[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[914d834]997# Error si el fichero de imagen no es accesible.
998IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
[8e65e89]999[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]1000
1001# Devuelve el tamaño de la imagen en KB.
1002#partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
1003#        awk '/Partition size/ {sub(/\.\.+/," "); printf "%d\n",$3*1024*1024;}'
1004ogGetImageInfo $IMGFILE | awk -F: '{print $4}'
1005}
1006
Note: See TracBrowser for help on using the repository browser.