source: client/engine/Image.lib @ 7e8132af

Last change on this file since 7e8132af was ad61ab7, checked in by OpenGnSys Support Team <soporte-og@…>, 5 years ago

#1004 Add new fields to imagenes table

Extend database to store new fields that contain information about "clonator",
"compressor", "filesystem" and "datasize".

This patch also creates a /tmp/image.info file that is consumed by ogClient.

  • Property mode set to 100755
File size: 42.8 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
[ef5025f]237    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk str_repo path_image" \
[1c9ef24]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
[ef5025f]327    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart str_repo path_image" \
328           "$FUNCNAME 1 1 REPO /aula1/win7"
[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
[ad61ab7]365    cp -f $IMGFILE.info /tmp/image.info
[3b43d89]366else
[cfeabbf]367    ogRaiseError $OG_ERR_IMAGE "$1 $2 $IMGFILE"
[f5432db7]368    rm -f "$IMGFILE"
[cfeabbf]369fi
[08b941f]370# Desbloquear partición e imagen.
[715bedc]371ogUnlock $1 $2
[08b941f]372ogUnlockImage "$3" "$4.$IMGTYPE"
[cfeabbf]373return $ERRCODE
[715bedc]374}
375
[b094c59]376
[a25cc03]377#/**
378#         ogCreateMbrImage int_ndisk str_repo path_image
379#@brief   Crea una imagen a partir del sector de arranque de un disco.
380#@param   int_ndisk    nº de orden del disco
381#@param   str_repo     repositorio de imágenes (remoto o caché local)
382#@param   path_image   camino de la imagen (sin extensión)
383#@return  (nada, por determinar)
384#@note    repo = { REPO, CACHE }
385#@exception OG_ERR_FORMAT    formato incorrecto.
386#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
387#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
388#@version 0.9 - Versión en pruebas para OpenGNSys
389#@author  Ramon Gomez, ETSII Universidad de Sevilla
390#@date    2010/01/12
391#@version 1.0 - Adaptación a OpenGnSys 1.0
392#@author  Ramon Gomez, ETSII Universidad de Sevilla
393#@date    2011/03/10
394#*/ ##
395function ogCreateMbrImage ()
396{
397# Variables locales
398local DISK IMGDIR IMGFILE
399# Si se solicita, mostrar ayuda.
400if [ "$*" == "help" ]; then
[ef5025f]401    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk str_repo path_image" \
[a25cc03]402           "$FUNCNAME 1 REPO /aula1/mbr"
403    return
404fi
405# Error si no se reciben 3 parámetros.
[a73649d]406[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]407
408DISK=$(ogDiskToDev "$1") || return $?
409IMGDIR=$(ogGetParentPath "$2" "$3")
410[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $?
411IMGFILE="$IMGDIR/$(basename "$3").mbr"
412
413# Crear imagen del MBR.
414dd if="$DISK" of="$IMGFILE" bs=512 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
415}
416
417
418#/**
[b52e658]419#         ogCreateBootLoaderImage int_ndisk str_repo path_image
420#@brief   Crea una imagen del boot loader a partir del sector de arranque de un disco.
421#@param   int_ndisk    nº de orden del disco
422#@param   str_repo     repositorio de imágenes (remoto o caché local)
423#@param   path_image   camino de la imagen (sin extensión)
424#@return  (nada, por determinar)
425#@note    repo = { REPO, CACHE }
426#@exception OG_ERR_FORMAT    formato incorrecto.
427#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
428#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
429#@version 1.0 - Adaptacion de ogCreateMbrImage para guardar solo el Boot Loader
430#@author  Juan Carlos Xifre, SICUZ Universidad de Zaragoza
431#@date    2011/03/21
432#*/ ##
433function ogCreateBootLoaderImage ()
434{
435# Variables locales
436local DISK IMGDIR IMGFILE
437# Si se solicita, mostrar ayuda.
438if [ "$*" == "help" ]; then
[ef5025f]439    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk str_repo path_image" \
[b52e658]440           "$FUNCNAME 1 REPO /aula1/mbr"
441    return
442fi
443# Error si no se reciben 3 parámetros.
[a73649d]444[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[b52e658]445
446DISK=$(ogDiskToDev "$1") || return $?
447IMGDIR=$(ogGetParentPath "$2" "$3")
448[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $?
449IMGFILE="$IMGDIR/$(basename "$3").mbr"
450
451# Crear imagen del Boot Loader dentro del MBR.
452dd if="$DISK" of="$IMGFILE" bs=446 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
453}
454
[d3dc88d]455#/**
456#         ogGetSizeParameters int_num_disk  int_num_part str_repo [monolit|sync|diff]
457#@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.
458#@param   int_disk     numero de disco
459#@param   int_part     numero de particion
460#@param   str_repo     repositorio de imágenes   { REPO, CACHE }
[31d4f1a5]461#@param   str_imageName Nombre de la imagen
[d3dc88d]462#@param   str_imageType Tipo de imagen: monolit (por defecto), sync o diff. (parametro opcional)
[e784187]463#@return  SIZEDATA SIZEREQUIRED SIZEFREE ISENOUGHSPACE
[d3dc88d]464#@note    si str_imageType= diff necesario /tmp/ogimg.info, que es creado por ogCreateInfoImage.
[31d4f1a5]465#@note    para el tamaño de la imagen no sigue enlaces simbólicos.
[d3dc88d]466#@exception OG_ERR_FORMAT    formato incorrecto.
467#@author  Irina Gomez, ETSII Universidad de Sevilla
468#@date    2014/10/24
[e784187]469#@version 1.1.0 - En la salida se incluye el espacio disponible en el repositorio (ticket #771)
470#@author  Irina Gomez - ETSII Universidad de Sevilla
471#@date    2017-03-28
[31d4f1a5]472#@version 1.1.0 - Si la imagen ya existe en el REPO se suma su tamaño al espacio libre
473#@author  Irina Gomez - ETSII Universidad de Sevilla
474#@date    2017-11-08
[d3dc88d]475#*/ ##
476function ogGetSizeParameters ()
477{
[f269659]478local REPO MNTDIR SIZEDATA KERNELVERSION SIZEREQUIRED FACTORGZIP FACTORLZOP FACTORSYNC SIZEFREE
479local IMGTYPE IMGDIR IMGFILE IMGEXT IMGSIZE
480
[d3dc88d]481# Si se solicita, mostrar ayuda.
482if [ "$*" == "help" ]; then
[ef5025f]483    ogHelp "$FUNCNAME" "$FUNCNAME num_disk num_part str_repo path_imgname [monolit|sync|diff]" \
[31d4f1a5]484           "if $FUNCNAME 1 2 REPO Windows10 sync ; then ...; fi" \
485           "if $FUNCNAME 1 6 Ubuntu16 CACHE ; then ...; fi"
[d3dc88d]486    return
487fi
488# Error si no se reciben 1 o 2 parámetros.
[31d4f1a5]489[ $# -lt 4 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion REPO|CACHE imgname [monolit|sync|diff]" ; echo $?)
490
491# Recogemos parametros
492REPO=${3^^}
493IMGTYPE="_${5^^}_"
[d3dc88d]494
495MNTDIR=$(ogMount $1 $2)
496if [ "$MNTDIR" == "" ]; then
497    ogRaiseError $OG_ERR_PARTITION "$1 $2"
498    return $?
499fi
500
501# Datos contenidos en la particion o en la lista de archivos de contiene la diferencial.
[f269659]502if [ "$IMGTYPE" == "_DIFF_" ]; then
[d3dc88d]503        [ -r /tmp/ogimg.info ] || return $(ogRaiseError session $OG_ERR_NOTFOUND "/tmp/ogimg.info"; echo $?)
504        cd $MNTDIR
505        SIZEDATA=$(grep -v "\/$" /tmp/ogimg.info | tr '\n' '\0'| du -x -c --files0-from=- 2>/dev/null|tail -n1 |cut -f1)
[0d4cef22]506        cd /
[d3dc88d]507else
[dbcb3ed]508        SIZEDATA=$(df -k | grep $MNTDIR\$ | awk '{print $3}')
[d3dc88d]509fi
510
511#Aplicar factor de compresion
[f269659]512if [ "$IMGTYPE" == "_SYNC_" -o "$IMGTYPE" == "_DIFF_" ]; then
[d3dc88d]513       
514        # Sistema de fichero de la imagen según kernel, menor que 3.7 EXT4. comparamos revision
515        KERNELVERSION=$(uname -r| awk '{printf("%d",$1);sub(/[0-9]*\./,"",$1);printf(".%02d",$1)}')
516        [ $KERNELVERSION \< 3.07 ] &&  IMGFS="EXT4" || IMGFS=${IMGFS:-"BTRFS"}
[0d4cef22]517        FACTORSYNC=${FACTORSYNC:-"130"}
[d3dc88d]518        # Si IMGFS="BTRFS" la compresion es mayor.
[81ae95c]519        [ $IMGFS == "BTRFS" ] && let FACTORSYNC=$FACTORSYNC-20
[d3dc88d]520
521        let SIZEREQUIRED=$SIZEDATA*$FACTORSYNC/100
522        # El tamaño mínimo del sistema de ficheros btrfs es 250M, ponemos 300
523        [ $SIZEREQUIRED -lt 300000 ] && SIZEREQUIRED=300000
524       
525else
526        FACTORGZIP=55/100
527        FACTORLZOP=65/100
528        let SIZEREQUIRED=$SIZEDATA*$FACTORLZOP
529fi
530
531#Comprobar espacio libre en el contenedor.
[31d4f1a5]532[ "$REPO" == "CACHE" ] && SIZEFREE=$(ogGetFreeSize `ogFindCache`)
533[ "$REPO" == "REPO" ] && SIZEFREE=$(df -k | grep $OGIMG | awk '{print $4}')
534
535# Comprobamos si existe una imagen con el mismo nombre en $REPO
536# En sincronizadas restamos tamaño de la imagen y en monoloticas de la .ant
537case "${IMGTYPE}" in
538    _DIFF_) IMGEXT="img.diff"
539            ;;
540    _SYNC_) IMGEXT="img"
541            ;;
542    *)      IMGEXT="img.ant"
543            ;;
544esac
545
546IMGDIR=$(ogGetParentPath "$REPO" "/$4")
547IMGFILE=$(ogGetPath "$IMGDIR/$(basename "/$4").$IMGEXT")
548if [ -z "$IMGFILE" ]; then
549    IMGSIZE=0
550else
551    IMGSIZE=$(ls -s "$IMGFILE" | cut -f1 -d" ")
552fi
553
554let SIZEFREE=$SIZEFREE+$IMGSIZE
[d3dc88d]555
556[ "$SIZEREQUIRED" -lt "$SIZEFREE" ] && ISENOUGHSPACE=TRUE  ||  ISENOUGHSPACE=FALSE
557
[e784187]558echo $SIZEDATA $SIZEREQUIRED $SIZEFREE $ISENOUGHSPACE
[d3dc88d]559
560}
[cbbb046]561
[b52e658]562#/**
[a25cc03]563#         ogIsImageLocked [str_repo] path_image
564#@brief   Comprueba si una imagen está bloqueada para uso exclusivo.
565#@param   str_repo     repositorio de imágenes (opcional)
566#@param   path_image   camino de la imagen (sin extensión)
[7685100]567#@return  Código de salida: 0 - bloqueado, 1 - sin bloquear o error.
[a25cc03]568#@note    repo = { REPO, CACHE }
569#@exception OG_ERR_FORMAT    formato incorrecto.
570#@version 1.0 - Adaptación a OpenGnSys 1.0
571#@author  Ramon Gomez, ETSII Universidad de Sevilla
572#@date    2011/03/10
[7685100]573#@version 1.0.1 - Devolver falso en caso de error.
574#@author  Ramon Gomez, ETSII Universidad de Sevilla
575#@date    2011-05-18
[a25cc03]576#*/ ##
577function ogIsImageLocked ()
578{
579# Si se solicita, mostrar ayuda.
580if [ "$*" == "help" ]; then
581    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
[ef5025f]582           "if $FUNCNAME /opt/opengnsys/images/aula1/win7.img; then ...; fi" \
583           "if $FUNCNAME REPO /aula1/win7.img; then ...; fi"
[a25cc03]584    return
585fi
586# Error si no se reciben 1 o 2 parámetros.
[7685100]587[ $# -lt 1 -o $# -gt 2 ] && return 1
[914d834]588
[a25cc03]589# Comprobar si existe el fichero de bloqueo.
590test -n "$(ogGetPath $@.lock)"
591}
[914d834]592
593
[a25cc03]594#/**
595#         ogLockImage [str_repo] path_image
596#@brief   Bloquea una imagen para uso exclusivo.
597#@param   str_repo     repositorio de imágenes (opcional)
598#@param   path_image   camino de la imagen (sin extensión)
599#@return  Nada.
600#@note    Se genera un fichero con extensión .lock
601#@note    repo = { REPO, CACHE }
602#@exception OG_ERR_FORMAT    formato incorrecto.
603#@version 1.0 - Adaptación a OpenGnSys 1.0
604#@author  Ramon Gomez, ETSII Universidad de Sevilla
605#@date    2011/03/10
606#*/ ##
607function ogLockImage ()
608{
609# Variables locales
610local IMGDIR
[914d834]611
[a25cc03]612# Si se solicita, mostrar ayuda.
613if [ "$*" == "help" ]; then
614    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
[ef5025f]615           "$FUNCNAME /opt/opengnsys/images/aula1/win7.img" \
616           "$FUNCNAME REPO /aula1/win7.img"
[a25cc03]617    return
618fi
619# Error si no se reciben 1 o 2 parámetros.
[a73649d]620[ $# == 1 -o $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]621# Comprobar que existe directorio de imagen
622IMGDIR=$(ogGetParentPath $@) || return $?
623# Crear fichero de bloqueo.
[a73649d]624touch $IMGDIR/$(basename "${!#}").lock 2>/dev/null || ogRaiseError $OG_ERR_NOTWRITE "$*" || return $?
[a25cc03]625}
[914d834]626
627
628#/**
[e39921b]629#         ogRestoreDiskImage str_repo path_image int_npartition
630#@brief   Restaura (recupera) una imagen de un disco completo.
631#@param   str_repo       repositorio de imágenes o caché local
632#@param   path_image     camino de la imagen
633#@param   int_ndisk      nº de orden del disco
634#@return  (por determinar)
635#@warning Primera versión en pruebas
636#@todo    Gestionar bloqueos de disco
637#@todo    Comprobar que no se intenta restaurar de la caché sobre el mismo disco
638#@exception OG_ERR_FORMAT    formato incorrecto.
639#@exception OG_ERR_NOTFOUND  fichero de imagen o partición no detectados.
640#@exception OG_ERR_LOCKED    partición bloqueada por otra operación.
641#@exception OG_ERR_IMAGE     error al restaurar la imagen del sistema.
642#@exception OG_ERR_IMGSIZEPARTITION  Tamaño de la particion es menor al tamaño de la imagen.
643#@version 1.1.0 - Primera versión para OpenGnsys.
644#@author Ramon Gomez, ETSII Universidad de Sevilla
[1c9ef24]645#@Date    2016/04/08
[e39921b]646#*/ ##
647function ogRestoreDiskImage ()
648{
649# Variables locales
650local DISK DISKSIZE IMGFILE IMGTYPE IMGSIZE PROGRAM ERRCODE
651
652# Si se solicita, mostrar ayuda.
653if [ "$*" == "help" ]; then
[ef5025f]654    ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image int_ndisk" \
655           "$FUNCNAME REPO /aula1/win7 1"
[e39921b]656    return
657fi
658# Error si no se reciben 4 parámetros.
659[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
660# Procesar parámetros.
661DISK="$(ogDiskToDev $3)" || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
662IMGTYPE="dsk"
663IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE")
664[ -r "$IMGFILE" ] || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
665
666# comprobamos consistencia de la imagen
[1c9ef24]667ogGetImageInfo $IMGFILE >/dev/null  || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
[9c811246]668
669#/* (Comienzo comentario Doxygen)
[e39921b]670# Error si la imagen no cabe en la particion.
671#IMGSIZE=$(ogGetImageSize "$1" "$2") || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
672#DISKSIZE=$(ogGetDiskSize $3)
673#if [ $IMGSIZE -gt $DISKSIZE ]; then
674#    ogRaiseError $OG_ERR_IMGSIZEPARTITION "$DISKSIZE < $IMGSIZE"
675#    return $?
676#fi
[9c811246]677#*/ (Fin comentario Doxygen)
678
[e39921b]679# Comprobar el bloqueo de la imagen y de la partición.
680if ogIsImageLocked "$IMGFILE"; then
681    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $1, $2.$IMGTYPE"
682    return $?
[1feb465]683fi
[c680f93]684if ogIsDiskLocked $3; then
685    ogRaiseError $OG_ERR_LOCKED "$MSG_DISK $3"
686    return $?
687fi
[e39921b]688# Solicitamos la generación de la instruccion a ejecutar
[1feb465]689PROGRAM=$(ogRestoreImageSyntax $IMGFILE $DISK)
[e39921b]690
691# Bloquear el disco
[1c9ef24]692ogLockDisk $3 || return $?
693trap "ogUnlockDisk $3" 1 2 3 6 9
[e39921b]694
695# Ejecutar restauración según el tipo de imagen.
696eval $PROGRAM
697
698ERRCODE=$?
699if [ $ERRCODE != 0 ]; then
700    ogRaiseError $OG_ERR_IMAGE "$IMGFILE, $3, $4"
701fi
[1c9ef24]702ogUnlockDisk $3 $4
[e39921b]703return $ERRCODE
704}
705
706
707#/**
[914d834]708#         ogRestoreImage str_repo path_image int_ndisk int_npartition
709#@brief   Restaura una imagen de sistema de archivos en una partición.
710#@param   str_repo       repositorio de imágenes o caché local
711#@param   path_image     camino de la imagen
712#@param   int_ndisk      nº de orden del disco
713#@param   int_npartition nº de orden de la partición
714#@return  (por determinar)
[8e83677]715#@exception OG_ERR_FORMAT   1 formato incorrecto.
716#@exception OG_ERR_NOTFOUND  2 fichero de imagen o partición no detectados.
717#@exception OG_ERR_PARTITION 3  # Error en partición de disco.
718#@exception OG_ERR_LOCKED    4 partición bloqueada por otra operación.
719#@exception OG_ERR_IMAGE    5 error al restaurar la imagen del sistema.
720#@exception OG_ERR_IMGSIZEPARTITION  30 Tamaño de la particion es menor al tamaño de la imagen.
[914d834]721#@todo    Comprobar incongruencias partición-imagen, control de errores, definir parámetros, caché/repositorio, etc.
722#@version 0.1 -  Integracion para Opengnsys  - HIDRA:RestaurarImagen{EXT3, NTFS}.sh;  EAC: RestorePartitionFromImage() en Deploy.lib
723#@author Ramon Gomez, ETSII Universidad de Sevilla
724#@Date    2008/05/13
725#@author  Antonio J. Doblas Viso. Universidad de Malaga
726#@date    2008/10/27
727#@version 0.9 - Primera version muy en pruebas para OpenGnSys
728#@author  Ramon Gomez, ETSII Universidad de Sevilla
729#@date    2009/09/10
[8e83677]730#@version 1.0 - generacion sintaxis de restauracion
731#@author  Antonio J. Doblas Viso, Universidad de Malaga
732#@date    2011/02/01
733#@version 1.0.1 - Control errores, tamaño particion, fichero-imagen
734#@author  Antonio J. Doblas Viso, Universidad de Malaga
735#@date    2011/05/11
[914d834]736#*/ ##
737function ogRestoreImage ()
738{
739# Variables locales
[cbbb046]740local PART PARTSIZE IMGFILE IMGTYPE IMGSIZE FSTYPE PROGRAM ERRCODE
[914d834]741
742# Si se solicita, mostrar ayuda.
743if [ "$*" == "help" ]; then
[ef5025f]744    ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image int_ndisk int_npart" \
745           "$FUNCNAME REPO /aula1/win7 1 1"
[914d834]746    return
747fi
748# Error si no se reciben 4 parámetros.
[1f03f6e]749[ $# == 4 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[914d834]750# Procesar parámetros.
[8e83677]751PART="$(ogDiskToDev $3 $4)" || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
[914d834]752#IMGTYPE=$(ogGetImageType "$1" "$2")
753IMGTYPE=img
[8e83677]754IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE")
755[ -r "$IMGFILE" ] || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?)
756# comprobamos consistencia de la imagen
757ogGetImageInfo $IMGFILE >/dev/null  || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
758
[914d834]759# Error si la imagen no cabe en la particion.
[8e83677]760IMGSIZE=$(ogGetImageSize "$1" "$2") || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?)
[be3b96a]761#TODO:
[8e83677]762#Si la particion no esta formateado o tiene problemas formateamos
763ogMount $3 $4 || ogFormat $3 $4
[f8b1b41]764PARTSIZE=$(ogGetPartitionSize $3 $4)
[914d834]765if [ $IMGSIZE -gt $PARTSIZE ]; then
[8e83677]766    ogRaiseError $OG_ERR_IMGSIZEPARTITION "  $PARTSIZE < $IMGSIZE"
[914d834]767    return $?
768fi
769# Comprobar el bloqueo de la imagen y de la partición.
770if ogIsImageLocked "$IMGFILE"; then
771    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $1, $2.$IMGTYPE"
772    return $?
773fi
774if ogIsLocked $3 $4; then
775    ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION $3, $4"
776    return $?
777fi
[2fc81c4]778
779# Solicitamos la generación de la instruccion a ejecutar
780# Atención: no se comprueba el tipo de sistema de archivos.
781# Atención: no se comprueba incongruencia entre partición e imagen.
782PROGRAM=`ogRestoreImageSyntax  $IMGFILE $PART`
783
[914d834]784# Desmontar y bloquear partición.
[8e83677]785ogUnmount $3 $4 2>/dev/null || return $(ogRaiseError $OG_ERR_PARTITION " $3 $4"; echo $?)
[a73649d]786ogLock $3 $4 || return $?
[914d834]787trap "ogUnlock $3 $4" 1 2 3 6 9
788
[2fc81c4]789# Ejecutar restauración según el tipo de imagen.
[914d834]790eval $PROGRAM
791
792ERRCODE=$?
793if [ $ERRCODE != 0 ]; then
794    ogRaiseError $OG_ERR_IMAGE "$IMGFILE, $3, $4"
795fi
796ogUnlock $3 $4
797return $ERRCODE
798}
799
800
801#/**
[a25cc03]802#         ogRestoreMbrImage str_repo path_image int_ndisk
803#@brief   Restaura la imagen del sector de arranque de un disco.
804#@param   str_repo     repositorio de imágenes o caché local
805#@param   path_image   camino de la imagen
806#@param   int_ndisk    nº de orden del disco
807#@return  (por determinar)
808#@exception OG_ERR_FORMAT   formato incorrecto.
809#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
810#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
811#@version 0.9 - Primera versión en pruebas.
812#@author  Ramon Gomez, ETSII Universidad de Sevilla
813#@date    2010/01/12
814#@version 1.0 - Adaptación a OpenGnSys 1.0
815#@author  Ramon Gomez, ETSII Universidad de Sevilla
816#@date    2011/03/10
817#*/ ##
818function ogRestoreMbrImage ()
819{
820# Variables locales
821local DISK IMGFILE
822# Si se solicita, mostrar ayuda.
823if [ "$*" == "help" ]; then
[ef5025f]824    ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image int_ndisk" \
[a25cc03]825           "$FUNCNAME REPO /aula1/mbr 1"
826    return
827fi
828# Error si no se reciben 3 parámetros.
[a73649d]829[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]830# Procesar parámetros.
831DISK=$(ogDiskToDev "$3") || return $?
[305c256]832IMGFILE=$(ogGetPath "$1" "$2.mbr")
[8e65e89]833[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[a25cc03]834
835# Restaurar imagen del MBR.
836dd if="$IMGFILE" of="$DISK" bs=512 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
837}
838
839
840#/**
[b52e658]841#         ogRestoreBootLoaderImage str_repo path_image int_ndisk
842#@brief   Restaura la imagen del boot loader del sector de arranque de un disco.
843#@param   str_repo     repositorio de imágenes o caché local
844#@param   path_image   camino de la imagen
845#@param   int_ndisk    nº de orden del disco
846#@return  (por determinar)
847#@exception OG_ERR_FORMAT   formato incorrecto.
848#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
849#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
850#@version 1.0 - Adaptacion de ogRestoreMbrImage para restaurar solo el Boot Loader
851#@author  Juan Carlos Xifre, SICUZ Universidad de Zaragoza
852#@date    2011/03/21
853#*/ ##
854function ogRestoreBootLoaderImage ()
855{
856# Variables locales
857local DISK IMGFILE
858# Si se solicita, mostrar ayuda.
859if [ "$*" == "help" ]; then
[ef5025f]860    ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image int_ndisk" \
[b52e658]861           "$FUNCNAME REPO /aula1/mbr 1"
862    return
863fi
864# Error si no se reciben 3 parámetros.
[a73649d]865[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[b52e658]866# Procesar parámetros.
867DISK=$(ogDiskToDev "$3") || return $?
[305c256]868IMGFILE=$(ogGetPath "$1" "$2.mbr")
[8e65e89]869[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[b52e658]870
871# Restaurar imagen del MBR.
872dd if="$IMGFILE" of="$DISK" bs=446 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
873}
874
875#/**
[a25cc03]876#         ogUnlockImage [str_repo] path_image
877#@brief   Desbloquea una imagen con uso exclusivo.
878#@param   str_repo     repositorio de imágenes (opcional)
879#@param   path_image   camino de la imagen (sin extensión)
880#@return  Nada.
881#@note    repo = { REPO, CACHE }
882#@note    Se elimina el fichero de bloqueo con extensión .lock
883#@exception OG_ERR_FORMAT    formato incorrecto.
884#@version 1.0 - Adaptación a OpenGnSys 1.0
885#@author  Ramon Gomez, ETSII Universidad de Sevilla
886#@date    2011/03/10
887#*/ ##
888function ogUnlockImage ()
889{
890# Si se solicita, mostrar ayuda.
891if [ "$*" == "help" ]; then
892    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
[ef5025f]893           "$FUNCNAME /opt/opengnsys/images/aula1/win7.img" \
894           "$FUNCNAME REPO /aula1/win7.img"
[a25cc03]895    return
896fi
897# Error si no se reciben 1 o 2 parámetros.
[a73649d]898[ $# == 1 -o $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[a25cc03]899
900# Borrar fichero de bloqueo para la imagen.
901rm -f $(ogGetPath $@.lock)
902}
903
904
905#/**
[914d834]906#         ogGetImageInfo filename
907#@brief   muestra información sobre la imagen monolitica.
908#@param 1   filename           path absoluto del fichero imagen
909#@return  cadena compuesta por clonacion:compresor:sistemaarchivos:tamañoKB
910#@exception OG_ERR_FORMAT    formato incorrecto.
911#@exception OG_ERR_NOTFOUND   fichero no encontrado.
912#@exception OG_ERR_IMAGE        "Image format is not valid $IMGFILE"
913#@warning En pruebas iniciales
914#@TODO    Definir sintaxis de salida (herramienta y compresor en minuscula)
915#@TODO    Arreglar loop para ntfsclone
916#@TODO    insertar parametros entrada tipo OG
917#@version 1.0 - Primeras pruebas
918#@author  Antonio J. Doblas Viso. Universidad de Málaga
919#@date    2010/02/08
920#*/ ##
921
[cbbb046]922function ogGetImageInfo ()
923{
[914d834]924# Si se solicita, mostrar ayuda.
925if [ "$*" == "help" ]; then
[ef5025f]926    ogHelp "$FUNCNAME" "$FUNCNAME path_filename" \
927           "$FUNCNAME /opt/opengnsys/images/prueba.img  ==>  PARTCLONE:LZOP:NTFS:5642158"
[914d834]928    return
929fi
930
[ef5025f]931# Error si no se recibe 1 parámetro.
[914d834]932[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
933
934#comprobando que el parametro uno es un file.
935[ -f $1 ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
936
[51953ae]937local TOOLS COMPRESSOR IMGFILE FILEHEAD FS FSPLUS SIZE SIZEFACTOR PARTIMAGEINFO PARTCLONEINFO NTFSCLONEINFO IMGDETECT
[914d834]938IMGDETECT="FALSE"
939
940IMGFILE=$1
941FILEHEAD=/tmp/`basename $IMGFILE`.infohead
942COMPRESSOR=`file $IMGFILE | awk '{print $2}'`
943ogCheckStringInGroup "$COMPRESSOR" "gzip lzop" || ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
944$($COMPRESSOR -dc $IMGFILE 2>/dev/null | head > $FILEHEAD) || ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
945
946## buscando Primera opción.
947if [ "$IMGDETECT" == "FALSE" ]
948then
[8e9669e]949        PARTCLONEINFO=$(LC_ALL=C partclone.info $FILEHEAD 2>&1)
[914d834]950        if `echo $PARTCLONEINFO | grep size > /dev/null`
951        then
952                TOOLS=PARTCLONE
953                FS=$(echo $PARTCLONEINFO | awk '{gsub(/\: /,"\n"); print toupper($8);}')
[d2f8c5a]954                if [[ "$FS" == "HFS" || "$FS" == "HFSPLUS" || "$FS" == "FAT32" ]]; then
[1cbf9e0]955                        FSPLUS=$(echo $PARTCLONEINFO | awk '{gsub(/\: /,"\n"); print toupper($9);}')
956                        echo $PARTCLONEINFO | grep GB > /dev/null && SIZEFACTOR=1000000 || SIZEFACTOR=1024
[1131208]957                        if [ "$FSPLUS" == "PLUS" ]; then
[1cbf9e0]958                                FS=$FS$FSPLUS
959                                SIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{printf "%d\n", $17*FACTOR;}')
960                        else
961                                SIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{printf "%d\n", $16*FACTOR;}')
962                        fi
963                else
964                        echo $PARTCLONEINFO | grep GB > /dev/null && SIZEFACTOR=1000000 || SIZEFACTOR=1024
965                        SIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{gsub(/\: /,"\n"); printf "%d\n", $11*FACTOR;}')
966                fi
[914d834]967                IMGDETECT="TRUE"
968        fi
969fi
970#buscando segunda opcion.
971if [ "$IMGDETECT" == "FALSE" -a ! -f /dev/loop2  ]
972then
973        cat $FILEHEAD | grep -w ntfsclone-image > /dev/null && NTFSCLONEINFO=$(cat $FILEHEAD | ntfsclone --restore --overwrite /dev/loop2 - 2>&1)
974        if `echo $NTFSCLONEINFO | grep ntfsclone > /dev/null` 
975        then
976                TOOLS=NTFSCLONE
977                SIZE=$(echo $NTFSCLONEINFO | awk '{gsub(/\(|\)|\./,""); printf "%d\n",$17/1000;}')
978                FS=NTFS
979                IMGDETECT="TRUE"
980        fi
981fi
982## buscando Tercer opción.
983if [ "$IMGDETECT" == "FALSE" ]
984then
985        PARTIMAGEINFO=$(partimage -B gui=no imginfo "$FILEHEAD" 2>&1)
986        if `echo $PARTIMAGEINFO | grep Partition > /dev/null`
987        then   
988                TOOLS=PARTIMAGE
989                FS=$(echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $17;}' | awk '{sub(/\.\.+/," "); print toupper($2)}')
990                SIZE=$( echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $36;}' | awk '{sub(/\.\.+/," "); printf "%d\n",$2*1024*1024;}')
991                IMGDETECT="TRUE"
[1feb465]992        fi
993        if file $FILEHEAD 2> /dev/null | grep -q "boot sector"; then
[a30ad15f]994                TOOLS="partclone.dd"
[1feb465]995                FS=
996                SIZE=
997                IMGDETECT="TRUE"
998        fi
[914d834]999fi
1000#comprobamos valores #Chequeamos los valores devueltos.
1001if [ -z "$TOOLS" -o -z "$COMPRESSOR" -o "$IMGDETECT" == "FALSE" ]
1002then
1003        ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
1004else
1005        COMPRESSOR=$(echo $COMPRESSOR | tr [a-z] [A-Z])
1006        echo $TOOLS:$COMPRESSOR:$FS:$SIZE
1007fi
1008}
1009
[9c811246]1010#/**
1011#         ogGetImageProgram str_REPO str_imagen
1012#@brief   muestra información sobre la imagen monolitica.
1013#@see     ogGetImageInfo
1014#@param 1   REPO o CACHE       contenedor de la imagen
1015#@param 2   filename           nombre de la imagen sin extension
1016#@return  nombre del programa usado para generar la imagen
1017#@exception OG_ERR_FORMAT    formato incorrecto.
1018#@exception OG_ERR_NOTFOUND   fichero no encontrado.
1019#@note     ogGetImageProgram REPO imagenA -> partclone
1020#@version 1.0 - Primeras pruebas
1021#@author  Antonio J. Doblas Viso. Universidad de Málaga
1022#@date    2010/02/08
1023#*/ ##
[ef5025f]1024
[914d834]1025function ogGetImageProgram ()
1026{
1027local IMGFILE
[ef5025f]1028# Si se solicita, mostrar ayuda.
1029if [ "$*" == "help" ]; then
1030    ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image" \
1031           "$FUNCNAME REPO prueba  ==>  PARTCLONE"
1032    return
1033fi
1034# Error si no se reciben 2 parámetros.
1035[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[305c256]1036IMGFILE=$(ogGetPath "$1" "$2.img")
[8e65e89]1037[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]1038ogGetImageInfo $IMGFILE | awk -F: '{print $1}'
1039}
1040
[9c811246]1041#/**
1042#         ogGetImageCompressor str_REPO str_imagen
1043#@brief   muestra información sobre la imagen monolitica.
1044#@see     ogGetImageInfo
1045#@param 1   REPO o CACHE       contenedor de la imagen
1046#@param 2   filename           nombre de la imagen sin extension
1047#@return    tipo de compresión usada al generar la imagen
1048#@exception OG_ERR_FORMAT    formato incorrecto.
1049#@exception OG_ERR_NOTFOUND   fichero no encontrado.
1050#@note     ogGetImageCompressor REPO imagenA -> lzop
1051#@version 1.0 - Primeras pruebas
1052#@author  Antonio J. Doblas Viso. Universidad de Málaga
1053#@date    2010/02/08
1054#*/ ##
[914d834]1055function ogGetImageCompressor ()
1056{
1057local IMGFILE
[ef5025f]1058# Si se solicita, mostrar ayuda.
1059if [ "$*" == "help" ]; then
1060    ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image" \
1061           "$FUNCNAME REPO prueba  ==>  LZOP"
1062    return
1063fi
1064# Error si no se reciben 2 parámetros.
1065[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[305c256]1066IMGFILE=$(ogGetPath "$1" "$2.img")
[8e65e89]1067[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]1068ogGetImageInfo $IMGFILE | awk -F: '{print $2}'
1069}
1070
[ef5025f]1071
[9c811246]1072#/**
1073#         ogGetImageType str_REPO str_imagen
1074#@brief   muestra información sobre el sistema de archivos de imagen monolitica.
1075#@see     ogGetImageInfo
1076#@param 1   REPO o CACHE       contenedor de la imagen
1077#@param 2   filename           nombre de la imagen sin extension
1078#@return    tipo de compresión usada al generar la imagen
1079#@exception OG_ERR_FORMAT    formato incorrecto.
1080#@exception OG_ERR_NOTFOUND   fichero no encontrado.
1081#@note     ogGetImageType REPO imagenA -> NTFS
1082#@version 1.0 - Primeras pruebas
1083#@author  Antonio J. Doblas Viso. Universidad de Málaga
1084#@date    2010/02/08
1085#*/ ##
[914d834]1086function ogGetImageType ()
1087{
1088local IMGFILE
[ef5025f]1089# Si se solicita, mostrar ayuda.
1090if [ "$*" == "help" ]; then
1091    ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image" \
1092           "$FUNCNAME REPO prueba  ==>  NTFS"
1093    return
1094fi
1095# Error si no se reciben 2 parámetros.
1096[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[305c256]1097IMGFILE=$(ogGetPath "$1" "$2.img")
[8e65e89]1098[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]1099ogGetImageInfo $IMGFILE | awk -F: '{print $3}'
1100}
1101
[ef5025f]1102
[9c811246]1103#/**
1104#         ogGetImageSize str_REPO str_imagen
1105#@brief   muestra información sobre el tamaño (KB) del sistema de archivos de imagen monolitica.
1106#@see     ogGetImageInfo
1107#@param 1   REPO o CACHE       contenedor de la imagen
1108#@param 2   filename           nombre de la imagen sin extension
1109#@return    tipo de compresión usada al generar la imagen
1110#@exception OG_ERR_FORMAT    formato incorrecto.
1111#@exception OG_ERR_NOTFOUND   fichero no encontrado.
1112#@note     ogGetImagesize REPO imagenA -> 56432234  > Kb
1113#@version 1.0 - Primeras pruebas
1114#@author  Antonio J. Doblas Viso. Universidad de Málaga
1115#@date    2010/02/08
1116#*/ ##
[914d834]1117function ogGetImageSize ()
1118{
1119# Variables locales
1120local IMGFILE
1121
1122# Si se solicita, mostrar ayuda.
1123if [ "$*" == "help" ]; then
[ef5025f]1124    ogHelp "$FUNCNAME" "$FUNCNAME str repo path_image" \
1125           "$FUNCNAME REPO prueba  ==>  5642158"
[914d834]1126    return
1127fi
[a73649d]1128# Error si no se reciben 2 parámetros.
1129[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
[914d834]1130# Error si el fichero de imagen no es accesible.
[305c256]1131IMGFILE=$(ogGetPath "$1" "$2.img")
[8e65e89]1132[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
[914d834]1133
1134# Devuelve el tamaño de la imagen en KB.
1135ogGetImageInfo $IMGFILE | awk -F: '{print $4}'
1136}
1137
[6bb748b]1138
1139#/**
1140#         ogCreateGptImage int_ndisk str_repo path_image
1141#@brief   Crea una imagen de la tabla de particiones GPT de un disco.
1142#@param   int_ndisk    nº de orden del disco
1143#@param   str_repo     repositorio de imágenes (remoto o caché local)
1144#@param   path_image   camino de la imagen (sin extensión)
1145#@return  (nada, por determinar)
1146#@note    repo = { REPO, CACHE }
1147#@exception OG_ERR_FORMAT    formato incorrecto.
1148#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
1149#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
1150#@version 1.1 - Adaptación a OpenGnSys 1.1
1151#@author  Juan Carlos Garcia. Universidad de Zaragoza
1152#@date    2017/03/29
1153#*/ ##
1154function ogCreateGptImage ()
1155{
1156# Variables locales
1157local DISK IMGDIR IMGFILE
1158# Si se solicita, mostrar ayuda.
1159if [ "$*" == "help" ]; then
1160    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk path_dir str_image" \
1161           "$FUNCNAME 1 REPO /aula1/gpt"
1162    return
1163fi
1164# Error si no se reciben 3 parámetros.
1165[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1166
1167DISK=$(ogDiskToDev "$1") || return $?
1168IMGDIR=$(ogGetParentPath "$2" "$3")
1169[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $?
1170IMGFILE="$IMGDIR/$(basename "$3").gpt"
1171
1172# Crear imagen de la tabla GPT.
1173sgdisk -b="$IMGFILE" "$DISK" || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
1174}
1175
1176#/**
1177#         ogRestoreGptImage str_repo path_image int_ndisk
1178#@brief   Restaura la imagen de la tabla de particiones GPT de un disco.
1179#@param   str_repo     repositorio de imágenes o caché local
1180#@param   path_image   camino de la imagen
1181#@param   int_ndisk    nº de orden del disco
1182#@return  (por determinar)
1183#@exception OG_ERR_FORMAT   formato incorrecto.
1184#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
1185#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
1186#@version 1.1 - Adaptación a OpenGnSys 1.1
1187#@author  Juan Carlos Garcia, Universidad de Zaragoza
1188#@date    2017/03/29
1189#*/ ##
1190function ogRestoreGptImage ()
1191{
1192# Variables locales
1193local DISK IMGFILE
1194# Si se solicita, mostrar ayuda.
1195if [ "$*" == "help" ]; then
1196    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \
1197           "$FUNCNAME REPO /aula1/gpt 1"
1198    return
1199fi
1200# Error si no se reciben 3 parámetros.
1201[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1202# Procesar parámetros.
1203DISK=$(ogDiskToDev "$3") || return $?
[305c256]1204IMGFILE=$(ogGetPath "$1" "$2.gpt")
[6bb748b]1205[ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $?
1206
1207# Restaurar tabla GPT del disco.
1208sgdisk -l="$IMGFILE" "$DISK" || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
1209}
1210
Note: See TracBrowser for help on using the repository browser.