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

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 7caf5a7c was be3b96a, checked in by adv <adv@…>, 14 years ago

version 1.0.1 #389 controlando tamaño de particion y sistema de archivos en procesos de restauracion de imagenes

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

  • Property mode set to 100755
File size: 28.3 KB
Line 
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.
7#@version 1.0
8#@warning License: GNU GPLv3+
9#*/
10
11
12
13function ogPartcloneSyntax ()
14{
15#TODO: comprobar como unico parametro particion /dev/sda1
16#COMPAR="partclone.$FS --clone --force --source $PART"
17COMPAR="-F -c -s "
18TYPE="$(ogGetFsType `ogDevToDisk $1`)"
19case "$TYPE" in
20    EXT[234])
21        echo "partclone.extfs $COMPAR $1"
22        ;;
23    REISERFS|XFS|JFS)
24        echo "partclone.dd $COMPAR $1"
25        ;;
26    NTFS|HNTFS)
27        echo "partclone.ntfs $COMPAR $1"
28        ;;
29    FAT16|FAT32|HFAT16|HFAT32)
30        echo "partclone.fat $COMPAR $1"
31        ;;
32    HFS|HFS+)
33        echo "partclone.hfsp $COMPAR $1"
34        ;;
35    *)  ogRaiseError $OG_ERR_PARTITION "$1 $TYPE"
36        return $? ;;
37esac   
38}
39
40#/**
41#         ogCreateImageSyntax partition filename [tools]  [levelcompresor]
42#@brief   Genera una cadena de texto con la instrucción para crear un fichero imagen
43#@param 1  partition             identificador linux del dispositivo particion.
44#@param 2  filename           path absoluto del fichero imagen
45#@param 3  [opcional] str_tools          herrmaienta de clonacion [partimage, partclone, ntfsclone]
46#@param 4  [opcional] str_levelcompresor nivel de compresion. [0 -none-, 1-lzop-, 2-gzip]
47#@return  cadena con el comando que se debe ejecutar.
48#@exception OG_ERR_FORMAT    formato incorrecto.
49#@warning En pruebas iniciales
50#@TODO    introducir las herramientas fsarchiver, dd
51#@TODO    introducir el nivel de compresion gzip
52#@version 1.0 - Primeras pruebas
53#@author  Antonio J. Doblas Viso. Universidad de Málaga
54#@date    2010/02/08
55#*/ ##
56
57function ogCreateImageSyntax()
58{
59local FS TOOL LEVEL PART IMGFILE BUFFER
60
61# Si se solicita, mostrar ayuda.
62if [ "$*" == "help" ]; then
63    ogHelp "$FUNCNAME" "$FUNCNAME partition filename [tool] [levelcompresor]" \
64           "$FUNCNAME /dev/sda1 /opt/opengnsys/images/prueba.img partclone lzop"
65    return
66fi
67# Error si no se reciben al menos los 2 parámetros para obtener el valor default.
68[ $# -lt 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
69
70
71PART=`echo $1`
72IMGFILE=`echo $2`
73
74case "$#" in
75   "2")
76        # Sintaxis por defecto OG PART IMGFILE
77        #echo "partimage -M -f3 -o -d -V0 -B gui=no -c -z1 save $PART $IMGFILE"
78    # Se comenta la instruccion que debería ir aqui
79    ogCreateImageSyntax $1 $2 partclone gzip
80   ;;
81   "4")
82        # Sintaxis condicionada.
83        # comprobamos parametro herramienta compresion.
84        TOOL=$(echo $3 | tr [A-Z] [a-z])       
85        #ogCheckProgram $TOOL
86        #comprobar parámetro compresor.
87        LEVEL=$(echo $4 | tr [A-Z] [a-z])
88        #ogCheckProgram $LEVEL
89
90        # herramienta
91        case "$TOOL" in
92                "ntfsclone")
93                        PARAM1="ntfsclone --force --save-image -O - $PART"
94                ;;
95                "partimage"|DEFAULT)
96                        PARAM1="partimage -M -f3 -o -d -B gui=no -c -z0 --volume=0 save $PART stdout"
97                ;;
98                "partclone")
99                        PARAM1=`ogPartcloneSyntax $PART` || ogRaiseError $OG_ERR_FORMAT || return $?
100                ;;
101        esac
102        # mbuffer
103        which mbuffer > /dev/null && PARAM2="| mbuffer -q -m 40M " || PARAM2=" "
104
105        # nivel de compresion
106        case "$LEVEL" in
107        "0"|"none")
108                PARAM3=" > "
109        ;;
110        "1"|"lzop")
111                PARAM3=" | lzop > "
112        ;;
113        "2"|"gzip")
114                PARAM3=" | gzip -c > "
115        ;;
116        "3"|"bzip")
117                PARAM3=" | bzip -c > "
118        ;;
119        esac
120        #sintaxis final.
121        echo "$PARAM1 $PARAM2 $PARAM3 $IMGFILE"
122        ;;
123esac
124}
125
126
127#/**
128#         ogRestoreImageSyntax filename partition [tools]  [levelcompresor]
129#@brief   Genera una cadena de texto con la instrucción para crear un fichero imagen
130#@param 1  filename           path absoluto del fichero imagen
131#@param 2  partition             identificador linux del dispositivo particion.
132#@param 3  [opcional] str_tools          herrmaienta de clonacion [partimage, partclone, ntfsclone]
133#@param 4  [opcional] str_levelcompresor nivel de compresion. [0 -none-, 1-lzop-, 2-gzip]
134#@return  cadena con el comando que se debe ejecutar.
135#@exception OG_ERR_FORMAT    formato incorrecto.
136#@warning En pruebas iniciales
137#@TODO    introducir las herramientas fsarchiver, dd
138#@TODO    introducir el nivel de compresion gzip
139#@version 1.0 - Primeras pruebas
140#@author  Antonio J. Doblas Viso. Universidad de Málaga
141#@date    2010/02/08
142#*/ ##
143
144ogRestoreImageSyntax ()
145{
146local TOOL COMPRESSOR LEVEL PART IMGFILE FILEHEAD INFOIMG
147
148
149# Si se solicita, mostrar ayuda.
150if [ "$*" == "help" ]; then
151    ogHelp "$FUNCNAME" "$FUNCNAME  filename partition [tool] [levelcompresor]" \
152           "$FUNCNAME  /opt/opengnsys/images/prueba.img /dev/sda1 [partclone] [lzop]"
153    return
154fi
155
156# Error si no se reciben al menos 2 parámetros.
157[ $# -lt 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
158
159# controlamos que el parametro 1 (imagen) es tipo file.
160[ -f $1 ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
161
162# Si 2 parametros (file-origen-, device-destino-) = ogGetImageFull($1)
163if [ "$#" -eq 2 ]; then
164        IMGFILE=$1
165        PART=$2
166        INFOIMG=$(ogGetImageInfo $IMGFILE) || ogRaiseError $OG_ERR_NOTFOUND "No Image $1" || return $?
167        TOOL=`echo $INFOIMG | cut -f1 -d:`
168        COMPRESSOR=`echo $INFOIMG | cut -f2 -d:`
169        ogRestoreImageSyntax $IMGFILE $PART $TOOL $COMPRESSOR
170fi
171
172
173# Si cuatro parametros genera sintaxis
174if [ "$#" -eq 4 ]; then
175        IMGFILE=$1
176        PART=$2
177        # comprobamos parametro herramienta compresion.
178        TOOL=$(echo $3 | tr [A-Z] [a-z])       
179        #ogCheckProgram $TOOL
180        #comprobar parámetro compresor.
181        LEVEL=$(echo $4 | tr [A-Z] [a-z])
182        #ogCheckProgram $LEVEL
183       
184        case "$LEVEL" in
185        "0"|"none")
186                COMPRESSOR=" "
187        ;;
188        "1"|"lzop" | "LZOP")
189                COMPRESSOR=" lzop -dc "
190        ;;
191        "2"|"gzip" | "GZIP")
192                COMPRESSOR=" gzip -dc "
193        ;;
194        "3"|"bzip" | "BZIP" )
195                COMPRESSOR=" bzip -dc "
196        ;;
197        *)
198                ogRaiseError $OG_ERR_NOTFOUND "Compressor no valid $TOOL" || return $?
199        ;;
200        esac
201    #comprobar mbuffer
202        which mbuffer > /dev/null && MBUFFER="| mbuffer -q -m 40M " || MBUFFER=" "
203
204        case "$TOOL" in
205                "ntfsclone" | "NTFSCLONE")
206                        TOOL="| ntfsclone --restore-image --overwrite $PART -"
207                ;;
208                "partimage"| "PARTIMAGE")
209                        TOOL="| partimage -f3 -B gui=no restore $PART stdin"
210                ;;
211                "partclone" | "PARTCLONE")
212                    # -C para que no compruebe tamaños
213                        TOOL="| partclone.restore -o $PART"
214                ;;
215                *)
216                ogRaiseError $OG_ERR_NOTFOUND "Tools imaging no valid $TOOL" || return $?
217        ;;
218        esac
219
220        echo "$COMPRESSOR $IMGFILE $MBUFFER $TOOL"
221fi
222
223}
224
225
226
227
228#/**
229#         ogCreateImage int_ndisk int_npartition str_repo path_image
230#@brief   Crea una imagen a partir de una partición.
231#@param   int_ndisk      nº de orden del disco
232#@param   int_npartition nº de orden de la partición
233#@param   str_repo       repositorio de imágenes (remoto o caché local)
234#@param   path_image     camino de la imagen (sin extensión)
235#@return  (nada, por determinar)
236#@note    repo = { REPO, CACHE }
237#@exception OG_ERR_FORMAT    formato incorrecto.
238#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
239#@exception OG_ERR_PARTITION partición no accesible o no soportada.
240#@exception OG_ERR_LOCKED    particion bloqueada por otra operación.
241#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
242#@warning En pruebas iniciales
243#@todo    Comprobaciones, control de errores, definir parámetros, etc.
244#@version 0.1 -  Integracion para Opengnsys  -  HIDRA:CrearImagen{EXT3, NTFS}.sh;  EAC: CreateImageFromPartition () en Deploy.lib
245#@author Ramon Gomez, ETSII Universidad de Sevilla
246#@Date    2008/05/13
247#@author  Antonio J. Doblas Viso. Universidad de Malaga
248#@date    2008/10/27
249#@version 0.9 - Versión en pruebas para OpenGnSys
250#@author  Ramon Gomez, ETSII Universidad de Sevilla
251#@date    2009/10/07
252#*/ ##
253function ogCreateImage ()
254{
255# Variables locales
256local PART PROGRAM IMGDIR IMGFILE IMGTYPE ERRCODE
257
258# Si se solicita, mostrar ayuda.
259if [ "$*" == "help" ]; then
260    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart path_dir str_image" \
261           "$FUNCNAME 1 1 REPO /aula1/winxp"
262    return
263fi
264# Error si no se reciben 4 parámetros.
265[ $# -lt 4 ] && ogRaiseError $OG_ERR_FORMAT && return $?
266
267# Comprobar que no está bloqueada ni la partición, ni la imagen.
268PART="$(ogDiskToDev $1 $2)" || return $?
269if ogIsLocked $1 $2; then
270    ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION $1, $2"
271    return $?
272fi
273IMGTYPE="img"                   # Extensión genérica de imágenes.
274IMGDIR=$(ogGetParentPath "$3" "$4")
275
276[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$3 $(dirname $4)" || return $?
277IMGFILE="$IMGDIR/$(basename "$4").$IMGTYPE"
278if ogIsImageLocked "$IMGFILE"; then
279    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $3, $4"
280    return $?
281fi
282# Desmontar partición, bloquear partición e imagen.
283ogUnmount $1 $2 2>/dev/null
284ogLock $1 $2 || return $?
285ogLockImage "$3" "$4.$IMGTYPE" || return $?
286
287# Crear Imagen.
288trap "ogUnlock $1 $2; ogUnlockImage "$3" "$4.$IMGTYPE"; rm -f $IMGFILE" 1 2 3 6 9
289#Solicitamos la generación de la instruccion a ejecutar
290PROGRAM=`ogCreateImageSyntax $PART $IMGFILE $5 $6`
291echo $PROGRAM
292eval $PROGRAM
293
294# Controlar salida de error y desbloquear partición.
295ERRCODE=$?
296if [ $ERRCODE != 0 ]; then
297    ogRaiseError $OG_ERR_IMAGE "$1 $2 $IMGFILE"
298    rm -f "$IMGFILE"
299fi
300# Desbloquear partición e imagen.
301ogUnlock $1 $2
302ogUnlockImage "$3" "$4.$IMGTYPE"
303return $ERRCODE
304}
305
306
307#/**
308#         ogCreateMbrImage int_ndisk str_repo path_image
309#@brief   Crea una imagen a partir del sector de arranque de un disco.
310#@param   int_ndisk    nº de orden del disco
311#@param   str_repo     repositorio de imágenes (remoto o caché local)
312#@param   path_image   camino de la imagen (sin extensión)
313#@return  (nada, por determinar)
314#@note    repo = { REPO, CACHE }
315#@exception OG_ERR_FORMAT    formato incorrecto.
316#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
317#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
318#@version 0.9 - Versión en pruebas para OpenGNSys
319#@author  Ramon Gomez, ETSII Universidad de Sevilla
320#@date    2010/01/12
321#@version 1.0 - Adaptación a OpenGnSys 1.0
322#@author  Ramon Gomez, ETSII Universidad de Sevilla
323#@date    2011/03/10
324#*/ ##
325function ogCreateMbrImage ()
326{
327# Variables locales
328local DISK IMGDIR IMGFILE
329# Si se solicita, mostrar ayuda.
330if [ "$*" == "help" ]; then
331    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk path_dir str_image" \
332           "$FUNCNAME 1 REPO /aula1/mbr"
333    return
334fi
335# Error si no se reciben 3 parámetros.
336[ $# -lt 3 ] && ogRaiseError $OG_ERR_FORMAT && return $?
337
338DISK=$(ogDiskToDev "$1") || return $?
339IMGDIR=$(ogGetParentPath "$2" "$3")
340[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $?
341IMGFILE="$IMGDIR/$(basename "$3").mbr"
342
343# Crear imagen del MBR.
344dd if="$DISK" of="$IMGFILE" bs=512 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
345}
346
347
348#/**
349#         ogCreateBootLoaderImage int_ndisk str_repo path_image
350#@brief   Crea una imagen del boot loader a partir del sector de arranque de un disco.
351#@param   int_ndisk    nº de orden del disco
352#@param   str_repo     repositorio de imágenes (remoto o caché local)
353#@param   path_image   camino de la imagen (sin extensión)
354#@return  (nada, por determinar)
355#@note    repo = { REPO, CACHE }
356#@exception OG_ERR_FORMAT    formato incorrecto.
357#@exception OG_ERR_NOTFOUND  fichero o dispositivo no encontrado.
358#@exception OG_ERR_IMAGE     error al crear la imagen del sistema.
359#@version 1.0 - Adaptacion de ogCreateMbrImage para guardar solo el Boot Loader
360#@author  Juan Carlos Xifre, SICUZ Universidad de Zaragoza
361#@date    2011/03/21
362#*/ ##
363function ogCreateBootLoaderImage ()
364{
365# Variables locales
366local DISK IMGDIR IMGFILE
367# Si se solicita, mostrar ayuda.
368if [ "$*" == "help" ]; then
369    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk path_dir str_image" \
370           "$FUNCNAME 1 REPO /aula1/mbr"
371    return
372fi
373# Error si no se reciben 3 parámetros.
374[ $# -lt 3 ] && ogRaiseError $OG_ERR_FORMAT && return $?
375
376DISK=$(ogDiskToDev "$1") || return $?
377IMGDIR=$(ogGetParentPath "$2" "$3")
378[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $?
379IMGFILE="$IMGDIR/$(basename "$3").mbr"
380
381# Crear imagen del Boot Loader dentro del MBR.
382dd if="$DISK" of="$IMGFILE" bs=446 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
383}
384
385#/**
386#         ogIsImageLocked [str_repo] path_image
387#@brief   Comprueba si una imagen está bloqueada para uso exclusivo.
388#@param   str_repo     repositorio de imágenes (opcional)
389#@param   path_image   camino de la imagen (sin extensión)
390#@return  Código de salida: 0 - sin bloquear, 1 - bloqueada.
391#@note    repo = { REPO, CACHE }
392#@exception OG_ERR_FORMAT    formato incorrecto.
393#@version 1.0 - Adaptación a OpenGnSys 1.0
394#@author  Ramon Gomez, ETSII Universidad de Sevilla
395#@date    2011/03/10
396#*/ ##
397function ogIsImageLocked ()
398{
399# Si se solicita, mostrar ayuda.
400if [ "$*" == "help" ]; then
401    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
402           "if $FUNCNAME /opt/opengnsys/images/aula1/winxp.img; then ...; fi" \
403           "if $FUNCNAME REPO /aula1/winxp.img; then ...; fi"
404    return
405fi
406# Error si no se reciben 1 o 2 parámetros.
407[ $# -lt 1 -o $# -gt 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
408
409# Comprobar si existe el fichero de bloqueo.
410test -n "$(ogGetPath $@.lock)"
411}
412
413
414#/**
415#         ogLockImage [str_repo] path_image
416#@brief   Bloquea una imagen para uso exclusivo.
417#@param   str_repo     repositorio de imágenes (opcional)
418#@param   path_image   camino de la imagen (sin extensión)
419#@return  Nada.
420#@note    Se genera un fichero con extensión .lock
421#@note    repo = { REPO, CACHE }
422#@exception OG_ERR_FORMAT    formato incorrecto.
423#@version 1.0 - Adaptación a OpenGnSys 1.0
424#@author  Ramon Gomez, ETSII Universidad de Sevilla
425#@date    2011/03/10
426#*/ ##
427function ogLockImage ()
428{
429# Variables locales
430local IMGDIR
431
432# Si se solicita, mostrar ayuda.
433if [ "$*" == "help" ]; then
434    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
435           "$FUNCNAME /opt/opengnsys/images/aula1/winxp.img" \
436           "$FUNCNAME REPO /aula1/winxp.img"
437    return
438fi
439# Error si no se reciben 1 o 2 parámetros.
440[ $# -lt 1 -o $# -gt 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
441# Comprobar que existe directorio de imagen
442IMGDIR=$(ogGetParentPath $@) || return $?
443# Crear fichero de bloqueo.
444touch $IMGDIR/$(basename "${!#}").lock
445}
446
447
448#/**
449#         ogRestoreImage str_repo path_image int_ndisk int_npartition
450#@brief   Restaura una imagen de sistema de archivos en una partición.
451#@param   str_repo       repositorio de imágenes o caché local
452#@param   path_image     camino de la imagen
453#@param   int_ndisk      nº de orden del disco
454#@param   int_npartition nº de orden de la partición
455#@return  (por determinar)
456#@exception OG_ERR_FORMAT   formato incorrecto.
457#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
458#@exception OG_ERR_LOCKED   partición bloqueada por otra operación.
459#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
460#@exception OG_ERR_IMGSIZEPARTITION  Tamaño de la particion es menor al tamaño de la imagen.
461#@todo    Comprobar incongruencias partición-imagen, control de errores, definir parámetros, caché/repositorio, etc.
462#@version 0.1 -  Integracion para Opengnsys  - HIDRA:RestaurarImagen{EXT3, NTFS}.sh;  EAC: RestorePartitionFromImage() en Deploy.lib
463#@author Ramon Gomez, ETSII Universidad de Sevilla
464#@Date    2008/05/13
465#@author  Antonio J. Doblas Viso. Universidad de Malaga
466#@date    2008/10/27
467#@version 0.9 - Primera version muy en pruebas para OpenGnSys
468#@author  Ramon Gomez, ETSII Universidad de Sevilla
469#@date    2009/09/10
470#*/ ##
471function ogRestoreImage ()
472{
473# Variables locales
474local PART PARTSIZE IMGFILE IMGTYPE IMGSIZE FSTYPE
475
476# Si se solicita, mostrar ayuda.
477if [ "$*" == "help" ]; then
478    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk int_npart" \
479           "$FUNCNAME REPO /aula1/winxp 1 1"
480    return
481fi
482# Error si no se reciben 4 parámetros.
483[ $# -lt 4 ] && ogRaiseError $OG_ERR_FORMAT && return $?
484# Procesar parámetros.
485PART="$(ogDiskToDev "$3" "$4")" || return $?
486#IMGTYPE=$(ogGetImageType "$1" "$2")
487IMGTYPE=img
488IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE")
489[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
490# Error si la imagen no cabe en la particion.
491IMGSIZE=$(ogGetImageSize "$1" "$2")
492#TODO:
493#PARTSIZE=$(ogGetPartitionSize $3 $4)
494PARTSIZE=$(parted `ogDiskToDev $3 $4` unit kB print | awk '{y=x; x=$4};END{print y}' | tr -d kB)
495if [ $IMGSIZE -gt $PARTSIZE ]; then
496    ogRaiseError $OG_ERR_IMGSIZEPARTITION "$IMGSIZE > $PARTSIZE"
497    return $?
498fi
499
500# Comprobar el bloqueo de la imagen y de la partición.
501if ogIsImageLocked "$IMGFILE"; then
502    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $1, $2.$IMGTYPE"
503    return $?
504fi
505if ogIsLocked $3 $4; then
506    ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION $3, $4"
507    return $?
508fi
509# Desmontar y bloquear partición.
510ogUnmount $3 $4 2>/dev/null || return $?
511ogLock $3 $4 || return $?
512trap "ogUnlock $3 $4" 1 2 3 6 9
513
514# Restaurar según el tipo de imagen.
515# Atención: no se comprueba el tipo de sistema de archivos.
516# Atención: no se comprueba incongruencia entre partición e imagen.
517#Solicitamos la generación de la instruccion a ejecutar
518PROGRAM=`ogRestoreImageSyntax  $IMGFILE $PART`
519echo $PROGRAM
520eval $PROGRAM
521
522ERRCODE=$?
523if [ $ERRCODE != 0 ]; then
524    ogRaiseError $OG_ERR_IMAGE "$IMGFILE, $3, $4"
525fi
526ogUnlock $3 $4
527return $ERRCODE
528}
529
530
531#/**
532#         ogRestoreMbrImage str_repo path_image int_ndisk
533#@brief   Restaura la imagen del sector de arranque de un disco.
534#@param   str_repo     repositorio de imágenes o caché local
535#@param   path_image   camino de la imagen
536#@param   int_ndisk    nº de orden del disco
537#@return  (por determinar)
538#@exception OG_ERR_FORMAT   formato incorrecto.
539#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
540#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
541#@version 0.9 - Primera versión en pruebas.
542#@author  Ramon Gomez, ETSII Universidad de Sevilla
543#@date    2010/01/12
544#@version 1.0 - Adaptación a OpenGnSys 1.0
545#@author  Ramon Gomez, ETSII Universidad de Sevilla
546#@date    2011/03/10
547#*/ ##
548function ogRestoreMbrImage ()
549{
550# Variables locales
551local DISK IMGFILE
552# Si se solicita, mostrar ayuda.
553if [ "$*" == "help" ]; then
554    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \
555           "$FUNCNAME REPO /aula1/mbr 1"
556    return
557fi
558# Error si no se reciben 3 parámetros.
559[ $# -lt 3 ] && ogRaiseError $OG_ERR_FORMAT && return $?
560# Procesar parámetros.
561DISK=$(ogDiskToDev "$3") || return $?
562IMGFILE=$(ogGetPath "$1" "$2.mbr") || return $?
563[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
564
565# Restaurar imagen del MBR.
566dd if="$IMGFILE" of="$DISK" bs=512 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
567}
568
569
570#/**
571#         ogRestoreBootLoaderImage str_repo path_image int_ndisk
572#@brief   Restaura la imagen del boot loader del sector de arranque de un disco.
573#@param   str_repo     repositorio de imágenes o caché local
574#@param   path_image   camino de la imagen
575#@param   int_ndisk    nº de orden del disco
576#@return  (por determinar)
577#@exception OG_ERR_FORMAT   formato incorrecto.
578#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
579#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
580#@version 1.0 - Adaptacion de ogRestoreMbrImage para restaurar solo el Boot Loader
581#@author  Juan Carlos Xifre, SICUZ Universidad de Zaragoza
582#@date    2011/03/21
583#*/ ##
584function ogRestoreBootLoaderImage ()
585{
586# Variables locales
587local DISK IMGFILE
588# Si se solicita, mostrar ayuda.
589if [ "$*" == "help" ]; then
590    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \
591           "$FUNCNAME REPO /aula1/mbr 1"
592    return
593fi
594# Error si no se reciben 3 parámetros.
595[ $# -lt 3 ] && ogRaiseError $OG_ERR_FORMAT && return $?
596# Procesar parámetros.
597DISK=$(ogDiskToDev "$3") || return $?
598IMGFILE=$(ogGetPath "$1" "$2.mbr") || return $?
599[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
600
601# Restaurar imagen del MBR.
602dd if="$IMGFILE" of="$DISK" bs=446 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
603}
604
605#/**
606#         ogUnlockImage [str_repo] path_image
607#@brief   Desbloquea una imagen con uso exclusivo.
608#@param   str_repo     repositorio de imágenes (opcional)
609#@param   path_image   camino de la imagen (sin extensión)
610#@return  Nada.
611#@note    repo = { REPO, CACHE }
612#@note    Se elimina el fichero de bloqueo con extensión .lock
613#@exception OG_ERR_FORMAT    formato incorrecto.
614#@version 1.0 - Adaptación a OpenGnSys 1.0
615#@author  Ramon Gomez, ETSII Universidad de Sevilla
616#@date    2011/03/10
617#*/ ##
618function ogUnlockImage ()
619{
620# Si se solicita, mostrar ayuda.
621if [ "$*" == "help" ]; then
622    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
623           "$FUNCNAME /opt/opengnsys/images/aula1/winxp.img" \
624           "$FUNCNAME REPO /aula1/winxp.img"
625    return
626fi
627# Error si no se reciben 1 o 2 parámetros.
628[ $# -lt 1 -o $# -gt 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
629
630# Borrar fichero de bloqueo para la imagen.
631rm -f $(ogGetPath $@.lock)
632}
633
634
635#/**
636#         ogGetImageInfo filename
637#@brief   muestra información sobre la imagen monolitica.
638#@param 1   filename           path absoluto del fichero imagen
639#@return  cadena compuesta por clonacion:compresor:sistemaarchivos:tamañoKB
640#@exception OG_ERR_FORMAT    formato incorrecto.
641#@exception OG_ERR_NOTFOUND   fichero no encontrado.
642#@exception OG_ERR_IMAGE        "Image format is not valid $IMGFILE"
643#@warning En pruebas iniciales
644#@TODO    Definir sintaxis de salida (herramienta y compresor en minuscula)
645#@TODO    Arreglar loop para ntfsclone
646#@TODO    insertar parametros entrada tipo OG
647#@version 1.0 - Primeras pruebas
648#@author  Antonio J. Doblas Viso. Universidad de Málaga
649#@date    2010/02/08
650#*/ ##
651
652function ogGetImageInfo () {
653# Si se solicita, mostrar ayuda.
654if [ "$*" == "help" ]; then
655    ogHelp "$FUNCNAME" "$FUNCNAME  filename " \
656           "$FUNCNAME  /opt/opengnsys/images/prueba.img "
657    return
658fi
659
660# Error si no se reciben 1 parámetros.
661[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
662
663#comprobando que el parametro uno es un file.
664[ -f $1 ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
665
666local TOOLS COMPRESSOR IMGFILE FILEHEAD FS SIZE SIZEFACTOR PARTIMAGEINFO PARTCLONEINFO NTFSCLONEINFO IMGDETECT
667IMGDETECT="FALSE"
668
669IMGFILE=$1
670FILEHEAD=/tmp/`basename $IMGFILE`.infohead
671COMPRESSOR=`file $IMGFILE | awk '{print $2}'`
672ogCheckStringInGroup "$COMPRESSOR" "gzip lzop" || ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
673$($COMPRESSOR -dc $IMGFILE 2>/dev/null | head > $FILEHEAD) || ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
674
675## buscando Primera opción.
676if [ "$IMGDETECT" == "FALSE" ]
677then
678        PARTCLONEINFO=$(partclone.info $FILEHEAD 2>&1)
679        if `echo $PARTCLONEINFO | grep size > /dev/null`
680        then
681                TOOLS=PARTCLONE
682                FS=$(echo $PARTCLONEINFO | awk '{gsub(/\: /,"\n"); print toupper($8);}')
683                echo $PARTCLONEINFO | grep GB > /dev/null && SIZEFACTOR=1000000 || SIZEFACTOR=1024
684                SIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{gsub(/\: /,"\n"); printf "%d\n", $11*FACTOR;}')
685                IMGDETECT="TRUE"
686        fi
687fi
688#buscando segunda opcion.
689if [ "$IMGDETECT" == "FALSE" -a ! -f /dev/loop2  ]
690then
691        cat $FILEHEAD | grep -w ntfsclone-image > /dev/null && NTFSCLONEINFO=$(cat $FILEHEAD | ntfsclone --restore --overwrite /dev/loop2 - 2>&1)
692        if `echo $NTFSCLONEINFO | grep ntfsclone > /dev/null` 
693        then
694                TOOLS=NTFSCLONE
695                SIZE=$(echo $NTFSCLONEINFO | awk '{gsub(/\(|\)|\./,""); printf "%d\n",$17/1000;}')
696                FS=NTFS
697                IMGDETECT="TRUE"
698        fi
699fi
700## buscando Tercer opción.
701if [ "$IMGDETECT" == "FALSE" ]
702then
703        PARTIMAGEINFO=$(partimage -B gui=no imginfo "$FILEHEAD" 2>&1)
704        if `echo $PARTIMAGEINFO | grep Partition > /dev/null`
705        then   
706                TOOLS=PARTIMAGE
707                FS=$(echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $17;}' | awk '{sub(/\.\.+/," "); print toupper($2)}')
708                SIZE=$( echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $36;}' | awk '{sub(/\.\.+/," "); printf "%d\n",$2*1024*1024;}')
709                IMGDETECT="TRUE"
710        fi     
711fi
712#comprobamos valores #Chequeamos los valores devueltos.
713if [ -z "$TOOLS" -o -z "$COMPRESSOR" -o "$IMGDETECT" == "FALSE" ]
714then
715        ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
716else
717        COMPRESSOR=$(echo $COMPRESSOR | tr [a-z] [A-Z])
718        echo $TOOLS:$COMPRESSOR:$FS:$SIZE
719fi
720}
721
722function ogGetImageProgram ()
723{
724local IMGFILE
725IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
726[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
727ogGetImageInfo $IMGFILE | awk -F: '{print $1}'
728
729}
730
731function ogGetImageCompressor ()
732{
733local IMGFILE
734IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
735[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
736ogGetImageInfo $IMGFILE | awk -F: '{print $2}'
737}
738
739function ogGetImageType ()
740{
741local IMGFILE
742IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
743[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
744#partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
745#        awk '/^Filesystem/ {sub(/\.\.+/," "); sub(/fs$/,""); print toupper($2);}'
746ogGetImageInfo $IMGFILE | awk -F: '{print $3}'
747
748}
749
750function ogGetImageSize ()
751{
752# Variables locales
753local IMGFILE
754
755# Si se solicita, mostrar ayuda.
756if [ "$*" == "help" ]; then
757    ogHelp "$FUNCNAME" "$FUNCNAME testing path_dir str_image int_ndisk int_npart" \
758           "$FUNCNAME 1 1 REPO /aula1/winxp  ==>  5642158"
759    return
760fi
761# Error si no se reciben menos de 2 parámetros.
762[ $# -lt 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
763# Error si el fichero de imagen no es accesible.
764IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
765[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
766
767# Devuelve el tamaño de la imagen en KB.
768#partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
769#        awk '/Partition size/ {sub(/\.\.+/," "); printf "%d\n",$3*1024*1024;}'
770ogGetImageInfo $IMGFILE | awk -F: '{print $4}'
771}
772
773
774#/**
775#         ogGetImageFs str_repo path_image
776#@brief   Devuelve el tipo de sistema de archivos almacenado en un fichero de imagen.
777#@param   str_repo    repositorio de imágenes o caché local
778#@param   path_image  camino de la imagen
779#@return  str_imgtype - mnemónico del tipo de sistema de archivos
780#@exception OG_ERR_FORMAT   formato incorrecto.
781#@exception OG_ERR_NOTFOUND fichero de imagen no encontrado.
782#@todo    Comprobar salidas para todos los tipos de sistemas de archivos.
783#/**
784function ogGetImageFsUS ()
785{
786local IMGFILE IMGTYPE
787IMGTYPE=$(ogGetImageType "$1" "$2")
788IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE") || return $?
789[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
790case "$IMGTYPE" in
791    img) # Partimage.
792         partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
793                awk '/^Filesystem/ {sub(/\.\.+/," "); if ($2=="ntfs") print NTFS;
794                                                      else { sub(/fs$/,""); print toupper($2);} }'
795         ;;
796    pgz) # Partclone / GZip
797         gzip -dc "$IMGFILE" | partclone.chkimg -C -s - 2>&1 | \
798                awk '/^File system/ {if ($2=="EXTFS") print "EXT3"; else print $3;}'
799         ;;
800    *)   # Error si el fichero de imagen no es accesible.
801         ogRaiseError OG_ERR_NOTFOUND "$IMGFILE"
802         return $?  ;;
803esac
804}
805
806
807#         ogGetImageSize str_repo path_image
808#@brief   Devuelve el tamaño del sistema de archivos almacenado en un fichero de imagen.
809#@param   str_repo    repositorio de imágenes o caché local
810#@param   path_image  camino de la imagen
811#@return  int_size  - tamaño (en KB)
812#@exception OG_ERR_FORMAT   formato incorrecto.
813#@exception OG_ERR_NOTFOUND fichero de imagen no encontrado.
814#*/
815#@warning En pruebas iniciales
816#@todo    Definición de parámetros y salidas.
817#@version 0.1 - Primera versión muy en pruebas para OpenGNSys
818#@author  Ramon Gomez, ETSII Universidad de Sevilla
819#@date    2009/09/11
820#*/ ##
821function ogGetImageSizeUS ()
822{
823# Variables locales
824local IMGFILE IMGTYPE
825
826# Si se solicita, mostrar ayuda.
827if [ "$*" == "help" ]; then
828    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk int_npart" \
829           "$FUNCNAME 1 1 REPO /aula1/winxp  ==>  5642158"
830    return
831fi
832# Error si no se reciben menos de 2 parámetros.
833[ $# -ne 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
834# Devuelve el tamaño de la imagen en KB.
835IMGTYPE=$(ogGetImageType "$1" "$2")
836IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE")
837case "$IMGTYPE" in
838    img) # Partimage.
839         partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
840                awk '/Partition size/ {sub(/\.\.+/," "); ps=$3} END {print ps*1024*1024;}'
841         ;;
842    pgz) # Partclone / GZip
843         gzip -dc "$IMGFILE" | partclone.chkimg -C -s - 2>&1 | \
844                awk -F: '/Block size/ {bs=$2} /Used block/ {ub=$2} END {print bs*ub/1024}'
845         ;;
846    *)   # Error si el fichero de imagen no es accesible.
847         ogRaiseError OG_ERR_NOTFOUND "$IMGFILE"
848         return $?  ;;
849esac
850}
851
Note: See TracBrowser for help on using the repository browser.