source: client/engine/Image.lib @ 5e1020c

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 5e1020c was eb9424f, checked in by ramon <ramongomez@…>, 14 years ago

branches/version1.0: aplicar cambios de la rama trunk para desarrollar version 1.0.1

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

  • Property mode set to 100755
File size: 28.2 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")
492PARTSIZE=$(ogGetPartitionSize $3 $4)
493if [ $IMGSIZE -gt $PARTSIZE ]; then
494    ogRaiseError $OG_ERR_IMGSIZEPARTITION "$IMGSIZE > $PARTSIZE"
495    return $?
496fi
497
498# Comprobar el bloqueo de la imagen y de la partición.
499if ogIsImageLocked "$IMGFILE"; then
500    ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $1, $2.$IMGTYPE"
501    return $?
502fi
503if ogIsLocked $3 $4; then
504    ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION $3, $4"
505    return $?
506fi
507# Desmontar y bloquear partición.
508ogUnmount $3 $4 2>/dev/null || return $?
509ogLock $3 $4 || return $?
510trap "ogUnlock $3 $4" 1 2 3 6 9
511
512# Restaurar según el tipo de imagen.
513# Atención: no se comprueba el tipo de sistema de archivos.
514# Atención: no se comprueba incongruencia entre partición e imagen.
515#Solicitamos la generación de la instruccion a ejecutar
516PROGRAM=`ogRestoreImageSyntax  $IMGFILE $PART`
517echo $PROGRAM
518eval $PROGRAM
519
520ERRCODE=$?
521if [ $ERRCODE != 0 ]; then
522    ogRaiseError $OG_ERR_IMAGE "$IMGFILE, $3, $4"
523fi
524ogUnlock $3 $4
525return $ERRCODE
526}
527
528
529#/**
530#         ogRestoreMbrImage str_repo path_image int_ndisk
531#@brief   Restaura la imagen del sector de arranque de un disco.
532#@param   str_repo     repositorio de imágenes o caché local
533#@param   path_image   camino de la imagen
534#@param   int_ndisk    nº de orden del disco
535#@return  (por determinar)
536#@exception OG_ERR_FORMAT   formato incorrecto.
537#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
538#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
539#@version 0.9 - Primera versión en pruebas.
540#@author  Ramon Gomez, ETSII Universidad de Sevilla
541#@date    2010/01/12
542#@version 1.0 - Adaptación a OpenGnSys 1.0
543#@author  Ramon Gomez, ETSII Universidad de Sevilla
544#@date    2011/03/10
545#*/ ##
546function ogRestoreMbrImage ()
547{
548# Variables locales
549local DISK IMGFILE
550# Si se solicita, mostrar ayuda.
551if [ "$*" == "help" ]; then
552    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \
553           "$FUNCNAME REPO /aula1/mbr 1"
554    return
555fi
556# Error si no se reciben 3 parámetros.
557[ $# -lt 3 ] && ogRaiseError $OG_ERR_FORMAT && return $?
558# Procesar parámetros.
559DISK=$(ogDiskToDev "$3") || return $?
560IMGFILE=$(ogGetPath "$1" "$2.mbr") || return $?
561[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
562
563# Restaurar imagen del MBR.
564dd if="$IMGFILE" of="$DISK" bs=512 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
565}
566
567
568#/**
569#         ogRestoreBootLoaderImage str_repo path_image int_ndisk
570#@brief   Restaura la imagen del boot loader del sector de arranque de un disco.
571#@param   str_repo     repositorio de imágenes o caché local
572#@param   path_image   camino de la imagen
573#@param   int_ndisk    nº de orden del disco
574#@return  (por determinar)
575#@exception OG_ERR_FORMAT   formato incorrecto.
576#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados.
577#@exception OG_ERR_IMAGE    error al restaurar la imagen del sistema.
578#@version 1.0 - Adaptacion de ogRestoreMbrImage para restaurar solo el Boot Loader
579#@author  Juan Carlos Xifre, SICUZ Universidad de Zaragoza
580#@date    2011/03/21
581#*/ ##
582function ogRestoreBootLoaderImage ()
583{
584# Variables locales
585local DISK IMGFILE
586# Si se solicita, mostrar ayuda.
587if [ "$*" == "help" ]; then
588    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \
589           "$FUNCNAME REPO /aula1/mbr 1"
590    return
591fi
592# Error si no se reciben 3 parámetros.
593[ $# -lt 3 ] && ogRaiseError $OG_ERR_FORMAT && return $?
594# Procesar parámetros.
595DISK=$(ogDiskToDev "$3") || return $?
596IMGFILE=$(ogGetPath "$1" "$2.mbr") || return $?
597[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
598
599# Restaurar imagen del MBR.
600dd if="$IMGFILE" of="$DISK" bs=446 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IMGFILE" || return $?
601}
602
603#/**
604#         ogUnlockImage [str_repo] path_image
605#@brief   Desbloquea una imagen con uso exclusivo.
606#@param   str_repo     repositorio de imágenes (opcional)
607#@param   path_image   camino de la imagen (sin extensión)
608#@return  Nada.
609#@note    repo = { REPO, CACHE }
610#@note    Se elimina el fichero de bloqueo con extensión .lock
611#@exception OG_ERR_FORMAT    formato incorrecto.
612#@version 1.0 - Adaptación a OpenGnSys 1.0
613#@author  Ramon Gomez, ETSII Universidad de Sevilla
614#@date    2011/03/10
615#*/ ##
616function ogUnlockImage ()
617{
618# Si se solicita, mostrar ayuda.
619if [ "$*" == "help" ]; then
620    ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \
621           "$FUNCNAME /opt/opengnsys/images/aula1/winxp.img" \
622           "$FUNCNAME REPO /aula1/winxp.img"
623    return
624fi
625# Error si no se reciben 1 o 2 parámetros.
626[ $# -lt 1 -o $# -gt 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
627
628# Borrar fichero de bloqueo para la imagen.
629rm -f $(ogGetPath $@.lock)
630}
631
632
633#/**
634#         ogGetImageInfo filename
635#@brief   muestra información sobre la imagen monolitica.
636#@param 1   filename           path absoluto del fichero imagen
637#@return  cadena compuesta por clonacion:compresor:sistemaarchivos:tamañoKB
638#@exception OG_ERR_FORMAT    formato incorrecto.
639#@exception OG_ERR_NOTFOUND   fichero no encontrado.
640#@exception OG_ERR_IMAGE        "Image format is not valid $IMGFILE"
641#@warning En pruebas iniciales
642#@TODO    Definir sintaxis de salida (herramienta y compresor en minuscula)
643#@TODO    Arreglar loop para ntfsclone
644#@TODO    insertar parametros entrada tipo OG
645#@version 1.0 - Primeras pruebas
646#@author  Antonio J. Doblas Viso. Universidad de Málaga
647#@date    2010/02/08
648#*/ ##
649
650function ogGetImageInfo () {
651# Si se solicita, mostrar ayuda.
652if [ "$*" == "help" ]; then
653    ogHelp "$FUNCNAME" "$FUNCNAME  filename " \
654           "$FUNCNAME  /opt/opengnsys/images/prueba.img "
655    return
656fi
657
658# Error si no se reciben 1 parámetros.
659[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
660
661#comprobando que el parametro uno es un file.
662[ -f $1 ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
663
664local TOOLS COMPRESSOR IMGFILE FILEHEAD FS SIZE SIZEFACTOR PARTIMAGEINFO PARTCLONEINFO NTFSCLONEINFO IMGDETECT
665IMGDETECT="FALSE"
666
667IMGFILE=$1
668FILEHEAD=/tmp/`basename $IMGFILE`.infohead
669COMPRESSOR=`file $IMGFILE | awk '{print $2}'`
670ogCheckStringInGroup "$COMPRESSOR" "gzip lzop" || ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
671$($COMPRESSOR -dc $IMGFILE 2>/dev/null | head > $FILEHEAD) || ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
672
673## buscando Primera opción.
674if [ "$IMGDETECT" == "FALSE" ]
675then
676        PARTCLONEINFO=$(partclone.info $FILEHEAD 2>&1)
677        if `echo $PARTCLONEINFO | grep size > /dev/null`
678        then
679                TOOLS=PARTCLONE
680                FS=$(echo $PARTCLONEINFO | awk '{gsub(/\: /,"\n"); print toupper($8);}')
681                echo $PARTCLONEINFO | grep GB > /dev/null && SIZEFACTOR=1048576 || SIZEFACTOR=1024
682                SIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{gsub(/\: /,"\n"); printf "%d\n", $11*FACTOR;}')
683                IMGDETECT="TRUE"
684        fi
685fi
686#buscando segunda opcion.
687if [ "$IMGDETECT" == "FALSE" -a ! -f /dev/loop2  ]
688then
689        cat $FILEHEAD | grep -w ntfsclone-image > /dev/null && NTFSCLONEINFO=$(cat $FILEHEAD | ntfsclone --restore --overwrite /dev/loop2 - 2>&1)
690        if `echo $NTFSCLONEINFO | grep ntfsclone > /dev/null` 
691        then
692                TOOLS=NTFSCLONE
693                SIZE=$(echo $NTFSCLONEINFO | awk '{gsub(/\(|\)|\./,""); printf "%d\n",$17/1000;}')
694                FS=NTFS
695                IMGDETECT="TRUE"
696        fi
697fi
698## buscando Tercer opción.
699if [ "$IMGDETECT" == "FALSE" ]
700then
701        PARTIMAGEINFO=$(partimage -B gui=no imginfo "$FILEHEAD" 2>&1)
702        if `echo $PARTIMAGEINFO | grep Partition > /dev/null`
703        then   
704                TOOLS=PARTIMAGE
705                FS=$(echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $17;}' | awk '{sub(/\.\.+/," "); print toupper($2)}')
706                SIZE=$( echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $36;}' | awk '{sub(/\.\.+/," "); printf "%d\n",$2*1024*1024;}')
707                IMGDETECT="TRUE"
708        fi     
709fi
710#comprobamos valores #Chequeamos los valores devueltos.
711if [ -z "$TOOLS" -o -z "$COMPRESSOR" -o "$IMGDETECT" == "FALSE" ]
712then
713        ogRaiseError $OG_ERR_IMAGE "Image format is not valid $IMGFILE" || return $?
714else
715        COMPRESSOR=$(echo $COMPRESSOR | tr [a-z] [A-Z])
716        echo $TOOLS:$COMPRESSOR:$FS:$SIZE
717fi
718}
719
720function ogGetImageProgram ()
721{
722local IMGFILE
723IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
724[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
725ogGetImageInfo $IMGFILE | awk -F: '{print $1}'
726
727}
728
729function ogGetImageCompressor ()
730{
731local IMGFILE
732IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
733[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
734ogGetImageInfo $IMGFILE | awk -F: '{print $2}'
735}
736
737function ogGetImageType ()
738{
739local IMGFILE
740IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
741[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
742#partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
743#        awk '/^Filesystem/ {sub(/\.\.+/," "); sub(/fs$/,""); print toupper($2);}'
744ogGetImageInfo $IMGFILE | awk -F: '{print $3}'
745
746}
747
748function ogGetImageSize ()
749{
750# Variables locales
751local IMGFILE
752
753# Si se solicita, mostrar ayuda.
754if [ "$*" == "help" ]; then
755    ogHelp "$FUNCNAME" "$FUNCNAME testing path_dir str_image int_ndisk int_npart" \
756           "$FUNCNAME 1 1 REPO /aula1/winxp  ==>  5642158"
757    return
758fi
759# Error si no se reciben menos de 2 parámetros.
760[ $# -lt 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
761# Error si el fichero de imagen no es accesible.
762IMGFILE=$(ogGetPath "$1" "$2.img") || return $?
763[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
764
765# Devuelve el tamaño de la imagen en KB.
766#partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
767#        awk '/Partition size/ {sub(/\.\.+/," "); printf "%d\n",$3*1024*1024;}'
768ogGetImageInfo $IMGFILE | awk -F: '{print $4}'
769}
770
771
772#/**
773#         ogGetImageFs str_repo path_image
774#@brief   Devuelve el tipo de sistema de archivos almacenado en un fichero de imagen.
775#@param   str_repo    repositorio de imágenes o caché local
776#@param   path_image  camino de la imagen
777#@return  str_imgtype - mnemónico del tipo de sistema de archivos
778#@exception OG_ERR_FORMAT   formato incorrecto.
779#@exception OG_ERR_NOTFOUND fichero de imagen no encontrado.
780#@todo    Comprobar salidas para todos los tipos de sistemas de archivos.
781#/**
782function ogGetImageFsUS ()
783{
784local IMGFILE IMGTYPE
785IMGTYPE=$(ogGetImageType "$1" "$2")
786IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE") || return $?
787[ -r "$IMGFILE" ] || ogRaiseError OG_ERR_NOTFOUND "$IMGFILE" || return $?
788case "$IMGTYPE" in
789    img) # Partimage.
790         partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
791                awk '/^Filesystem/ {sub(/\.\.+/," "); if ($2=="ntfs") print NTFS;
792                                                      else { sub(/fs$/,""); print toupper($2);} }'
793         ;;
794    pgz) # Partclone / GZip
795         gzip -dc "$IMGFILE" | partclone.chkimg -C -s - 2>&1 | \
796                awk '/^File system/ {if ($2=="EXTFS") print "EXT3"; else print $3;}'
797         ;;
798    *)   # Error si el fichero de imagen no es accesible.
799         ogRaiseError OG_ERR_NOTFOUND "$IMGFILE"
800         return $?  ;;
801esac
802}
803
804
805#         ogGetImageSize str_repo path_image
806#@brief   Devuelve el tamaño del sistema de archivos almacenado en un fichero de imagen.
807#@param   str_repo    repositorio de imágenes o caché local
808#@param   path_image  camino de la imagen
809#@return  int_size  - tamaño (en KB)
810#@exception OG_ERR_FORMAT   formato incorrecto.
811#@exception OG_ERR_NOTFOUND fichero de imagen no encontrado.
812#*/
813#@warning En pruebas iniciales
814#@todo    Definición de parámetros y salidas.
815#@version 0.1 - Primera versión muy en pruebas para OpenGNSys
816#@author  Ramon Gomez, ETSII Universidad de Sevilla
817#@date    2009/09/11
818#*/ ##
819function ogGetImageSizeUS ()
820{
821# Variables locales
822local IMGFILE IMGTYPE
823
824# Si se solicita, mostrar ayuda.
825if [ "$*" == "help" ]; then
826    ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk int_npart" \
827           "$FUNCNAME 1 1 REPO /aula1/winxp  ==>  5642158"
828    return
829fi
830# Error si no se reciben menos de 2 parámetros.
831[ $# -ne 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
832# Devuelve el tamaño de la imagen en KB.
833IMGTYPE=$(ogGetImageType "$1" "$2")
834IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE")
835case "$IMGTYPE" in
836    img) # Partimage.
837         partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \
838                awk '/Partition size/ {sub(/\.\.+/," "); ps=$3} END {print ps*1024*1024;}'
839         ;;
840    pgz) # Partclone / GZip
841         gzip -dc "$IMGFILE" | partclone.chkimg -C -s - 2>&1 | \
842                awk -F: '/Block size/ {bs=$2} /Used block/ {ub=$2} END {print bs*ub/1024}'
843         ;;
844    *)   # Error si el fichero de imagen no es accesible.
845         ogRaiseError OG_ERR_NOTFOUND "$IMGFILE"
846         return $?  ;;
847esac
848}
849
Note: See TracBrowser for help on using the repository browser.