source: client/engine/Image.lib @ 46b6de6

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 46b6de6 was 0d4cef22, checked in by irina <irinagomez@…>, 7 years ago

#770 Al crear imagen: Se aumenta el tamaño estimado de las sincronizadas. Se espera antes de chequear si ha ido bien.

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

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