source: client/engine/File.lib @ 71d382b

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 71d382b was 95e48e1, checked in by ramon <ramongomez@…>, 15 years ago

Funciones para calcular y tratar checksum de ficheros.

git-svn-id: https://opengnsys.es/svn/trunk@1062 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100755
File size: 13.1 KB
Line 
1#!/bin/bash
2#/**
3#@file    File.lib
4#@brief   Librería o clase File
5#@class   File
6#@brief   Funciones para gestión de archivos y directorios.
7#@version 0.9.2
8#@warning License: GNU GPLv3+
9#*/
10
11
12#/**
13#         ogCalculateChecksum [ str_repo | int_ndisk int_npart ] path_filepath
14#@brief   Devuelve la suma de comprobación (checksum) de un fichero.
15#@param   path_filepath     camino del fichero (independiente de mayúsculas)
16#@param   str_repo          repositorio de ficheros
17#@param   int_ndisk         nº de orden del disco
18#@param   int_npartition    nº de orden de la partición
19#@return  hex_checksum      Checksum del fichero
20#@version 0.9.2 - Primera versión para OpenGnSys.
21#@author  Ramon Gomez, ETSII Universidad de Sevilla
22#@date    2010-07-24
23#*/ ##
24function ogCalculateChecksum ()
25{
26# Variables locales.
27local FILE
28if [ "$*" == "help" ]; then
29    ogHelp "$FUNCNAME" "$FUNCNAME [ str_repo | int_ndisk int_npartition ] path_filepath" \
30           "$FUNCNAME REPO ubuntu.img   ==>   ef899299caf8b517ce36f1157a93d8bf"
31    return
32fi
33
34# Comprobar que existe el fichero y devolver sus datos.
35FILE=$(ogGetPath "$@")
36[ -n "$FILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$*" || return $?
37md5sum "$FILE" 2>&1 | cut -f1-2 -d" "
38}
39
40
41#/**
42#         ogCompareChecksumFiles [ str_repo | int_ndisk int_npart ] path_source [ str_repo | int_ndisk int_npart ] path_target
43#@brief   Metafunción que compara las sumas de comprobación almacenadas de 2 ficheros.
44#@return  bool_compare   Valor de comparación.
45#@warning No es necesario especificar la extensión ".sum".
46#@version 0.9.2 - Primera versión para OpenGnSys.
47#@author  Ramon Gomez, ETSII Universidad de Sevilla
48#@date    2010-07-24
49#*/ ##
50function ogCompareChecksumFiles ()
51{
52# Variables locales.
53local ARGS SOURCE TARGET
54if [ "$*" == "help" ]; then
55    ogHelp "$FUNCNAME" "$FUNCNAME [ str_repo | int_ndisk int_npartition ] path_filepath" \
56           "if $FUNCNAME REPO ubuntu.img CACHE ubuntu.img; then ... fi"
57    return
58fi
59
60ARGS="$@"
61case "$1" in
62    /*)     # Camino completo.          */ (Comentrio Doxygen)
63        SOURCE=$(ogGetPath "$1")
64        shift ;;
65    [1-9]*) # ndisco npartición.
66        SOURCE=$(ogGetPath "$1" "$2" "$3")
67        shift 3 ;;
68    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
69        SOURCE=$(ogGetPath "$1" "$2")
70        shift 2 ;;
71esac
72TARGET=$(ogGetPath "$@")
73
74# Comparar los ficheros de checksum.
75test "$(cat "$SOURCE.sum" 2>/dev/null)" == "$(cat "$TARGET.sum" 2>/dev/null)"
76}
77
78
79#/**
80#         ogCopyFile [ str_repo | int_ndisk int_npart ] path_source [ str_repo | int_ndisk int_npart ] path_target
81#@brief   Metafunción para copiar un fichero de sistema OpenGnSys a un directorio.
82#@see     ogGetPath
83#@warning Deben existir tanto el fichero origen como el directorio destino.
84#@version 0.9 - Pruebas con OpenGnSys.
85#@author  Ramon Gomez, ETSII Universidad de Sevilla
86#@date    2009-10-20
87#*/ ##
88function ogCopyFile ()
89{
90# Variables locales.
91local ARGS SOURCE TARGET
92
93ARGS="$@"
94case "$1" in
95    /*)     # Camino completo.          */ (Comentrio Doxygen)
96        SOURCE=$(ogGetPath "$1")
97        shift ;;
98    [1-9]*) # ndisco npartición.
99        SOURCE=$(ogGetPath "$1" "$2" "$3")
100        shift 3 ;;
101    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
102        SOURCE=$(ogGetPath "$1" "$2")
103        shift 2 ;;
104esac
105# Comprobar fichero origen y directorio destino.
106[ -n "$SOURCE" ] || ogRaiseError $OG_ERR_NOTFOUND "${ARGS% $*}" || return $?
107TARGET=$(ogGetPath "$@")
108[ -n "$TARGET" ] || ogRaiseError $OG_ERR_NOTFOUND "$@" || return $?
109# Copiar fichero.
110cp -p "$SOURCE" "$TARGET"                    # (definir posible error)
111}
112
113
114#/**
115#         ogDeleteFile [ str_repo | int_ndisk int_npartition ] path_filepath
116#@brief   Metafunción que borra un fichero de un dispositivo.
117#@see     ogGetPath
118#@version 0.9 - Pruebas con OpenGnSys.
119#@author  Ramon Gomez, ETSII Universidad de Sevilla
120#@date    2009-09-29
121#*/ ##
122function ogDeleteFile ()
123{
124# Variables locales.
125local FILE
126# Comprobar que existe el fichero y borrarlo.
127FILE=$(ogGetPath "$@")
128[ -n "$FILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$*" || return $?
129rm -f "$FILE" || ogRaiseError $OG_ERR_NOTFOUND "$*" || return $?
130}
131
132
133#/**
134#         ogDeleteTree [ str_repo | int_ndisk int_npartition ] path_dirpath
135#@brief   Metafunción que borra todo un subárbol de directorios de un dispositivo.
136#@see     ogGetPath
137#@version 0.9 - Pruebas con OpenGnSys.
138#@author  Ramon Gomez, ETSII Universidad de Sevilla
139#@date    2009-09-29
140#*/ ##
141function ogDeleteTree ()
142{
143# Variables locales.
144local DIR
145# Comprobar que existe el directorio y borrarlo con su contenido.
146DIR=$(ogGetPath "$@")
147[ -n "$DIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$*" || return $?
148rm -fr "$DIR" || ogRaiseError $OG_ERR_NOTFOUND "$*" || return $?
149}
150
151
152#/**
153#         ogGetPath [ str_repo | int_ndisk int_npartition ] path_filepath
154#@brief   Inicia el proceso de arranque de un sistema de archivos.
155#@param   path_filepath   camino del fichero (independiente de mayúsculas)
156#@param   str_repo        repositorio de ficheros
157#@param   int_ndisk       nº de orden del disco
158#@param   int_npartition  nº de orden de la partición
159#@return  path_file - camino completo real del fichero.
160#@note    repo = { REPO, CACHE, CDROM }
161#@note    Requisitos: \c grep \c sed
162#@exception OG_ERR_FORMAT    Formato incorrecto.
163#@exception OG_ERR_NOTFOUND  Fichero o dispositivo no encontrado.
164#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
165#@warning En caso de error, sólo devuelve el código y no da mensajes.
166#@todo    Terminar de definir parámetros para acceso a repositorios.
167#@version 0.9 - Pruebas con OpenGnSys.
168#@author  Ramon Gomez, ETSII Universidad de Sevilla
169#@date    2009-09-15
170#*/ ##
171function ogGetPath ()
172{
173# Variables locales.
174local MNTDIR FILE PREVFILE FILEPATH CURRENTDIR
175
176# Si se solicita, mostrar ayuda.
177if [ "$*" == "help" ]; then
178    ogHelp "$FUNCNAME" "$FUNCNAME [ str_repo | int_ndisk int_npartition ] path_filepath" \
179           "$FUNCNAME \"/mnt/sda1/windows/system32\"  ==>  /mnt/sda1/WINDOWS/System32" \
180           "$FUNCNAME REPO /etc/fstab  ==>  /opt/opengnsys/images/etc/fstab" \
181           "$FUNCNAME 1 1 \"/windows/system32\"  ==>  /mnt/sda1/WINDOWS/System32"
182    return
183fi
184
185# Procesar camino según el número de parámetros.
186case $# in
187    1)  FILE="$1" ;;
188    2)  case "$1" in
189            REPO|repo)
190                FILE="$OGIMG/$2" ;;
191            CACHE|cache)
192                FILE="$(ogMountCache)/$OGIMG/$2" ;;
193            CDROM|cdrom)
194                FILE="$(ogMountCdrom)/$2" ;;
195            *)  ogRaiseError $OG_ERR_FORMAT
196                return $? ;;
197        esac ;;
198    3)  FILE="$(ogMount $1 $2)/$3" ;;
199    *)  ogRaiseError $OG_ERR_FORMAT
200        return $? ;;
201esac
202
203# Eliminar caracteres \c / iniciales, finales y duplicados.
204CURRENTDIR="$PWD"
205        # /* (comentario Doxygen)
206FILE="$(echo $FILE|sed -e 's/\(\/\)*\1/\//g' -e 's/^\///' -e 's/\/$//')"
207PREVFILE=""
208FILEPATH="/"
209while [ "$FILE" != "$PREVFILE" ]; do
210    # Busca el nombre correcto en el directorio actual.
211    cd "$FILEPATH"
212    FILEPATH="${FILEPATH}/$(ls -A | grep -i -m1 "^${FILE%%/*}$")" || return $?
213    PREVFILE="$FILE"
214    FILE="${FILE#*/}"
215done
216        # (comentario Doxygen) */
217# Muestra el camino Linux, quitando el / inicial duplicado.
218[ "$FILEPATH" != "/" ] && echo ${FILEPATH#/}
219cd $CURRENTDIR
220}
221
222
223#/**
224#         ogGetParentPath [ str_repo | int_ndisk int_npartition ] path_filepath
225#@brief   Metafunción que devuelve el camino del directorio padre.
226#@see     ogGetPath
227#@version 0.9 - Pruebas con OpenGnSys.
228#@author  Ramon Gomez, ETSII Universidad de Sevilla
229#@date    2009-09-29
230#*/ ##
231function ogGetParentPath ()
232{
233local PARENT
234if [ "$*" == "help" ]; then
235    ogHelp "$FUNCNAME" "$FUNCNAME [ str_repo | int_ndisk int_npartition ] path_filepath" \
236           "$FUNCNAME \"/mnt/sda1/windows/system32\"  ==>  /mnt/sda1/WINDOWS" \
237           "$FUNCNAME REPO /etc/fstab  ==>  /opt/opengnsys/images/etc" \
238           "$FUNCNAME 1 1 \"/windows/system32\"  ==>  /mnt/sda1/WINDOWS"
239    return
240fi
241
242case $# in
243    1)  PARENT=$(dirname "$1") ;;
244    2)  PARENT="$1 $(dirname "/$2")" ;;
245    3)  PARENT="$1 $2 $(dirname "/$3")" ;;
246    *)  ogRaiseError $OG_ERR_FORMAT
247        return $? ;;
248esac
249ogGetPath $PARENT
250}
251
252
253#/**
254#         ogIsNewerFile [ str_repo | int_ndisk int_npart ] path_source [ str_repo | int_ndisk int_npart ] path_target
255#@brief   Metafunción que indica se un fichero es más nuevo que otro.
256#@see     ogGetPath
257#@return  int_code      Código de salida
258#@warning Deben existir tanto el fichero origen como el destino.
259#@version 0.9.2 - Primera versión para OpenGnSys.
260#@author  Ramon Gomez, ETSII Universidad de Sevilla
261#@date    2010-07-24
262#*/ ##
263function ogIsNewerFile ()
264{
265# Variables locales.
266local ARGS SOURCE TARGET
267# Si se solicita, mostrar ayuda.
268if [ "$*" == "help" ]; then
269    ogHelp "$FUNCNAME" "$FUNCNAME [ str_repo | int_ndisk int_npartition ] path_source [ str_repo | int_ndisk int_npartition ] path_target" \
270           "if $FUNCNAME REPO ubuntu.img CACHE ubuntu.img; then ...  fi"
271    return
272fi
273
274ARGS="$@"
275case "$1" in
276    /*)     # Camino completo.          */ (Comentrio Doxygen)
277        SOURCE=$(ogGetPath "$1")
278        shift ;;
279    [1-9]*) # ndisco npartición.
280        SOURCE=$(ogGetPath "$1" "$2" "$3")
281        shift 3 ;;
282    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
283        SOURCE=$(ogGetPath "$1" "$2")
284        shift 2 ;;
285esac
286# Comprobar que existen los ficheros origen y destino.
287[ -n "$SOURCE" ] || ogRaiseError $OG_ERR_NOTFOUND "${ARGS% $*}" || return $?
288TARGET=$(ogGetPath "$@")
289[ -n "$TARGET" ] || ogRaiseError $OG_ERR_NOTFOUND "$@" || return $?
290# Devolver si el primer fichero se ha modificado después que el segundo.
291test "$SOURCE" -nt "$TARGET"
292}
293
294
295#/**
296#         ogMakeChecksumFile [ str_repo | int_ndisk int_npart ] path_filepath
297#@brief   Metafunción que guarda el valor de comprobación de un fichero.
298#@see     ogCalculateChecksum
299#@warning Genera un fichero con extensión ".sum".
300#@version 0.9.2 - Primera versión para OpenGnSys.
301#@author  Ramon Gomez, ETSII Universidad de Sevilla
302#@date    2010-07-24
303#*/ ##
304function ogMakeChecksumFile ()
305{
306# Variables locales.
307local FILE DATA
308if [ "$*" == "help" ]; then
309    ogHelp "$FUNCNAME" "$FUNCNAME [ str_repo | int_ndisk int_npartition ] path_filepath" \
310           "$FUNCNAME REPO ubuntu.img"
311    return
312fi
313
314# Comprobar que existe el fichero y guardar su checksum.
315FILE=$(ogGetPath "$@")
316[ -n "$FILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$*" || return $?
317ogCalculateChecksum "$FILE" > "$FILE.sum"
318}
319
320
321#/**
322#         ogMakeDir [ str_repo | int_ndisk int_npartition ] path_dirpath
323#@brief   Metafunción que crea un subdirectorio vacío en un dispositivo.
324#@see     ogGetParentPath
325#@version 0.9 - Pruebas con OpenGnSys.
326#@author  Ramon Gomez, ETSII Universidad de Sevilla
327#@date    2009-09-29
328#*/ ##
329function ogMakeDir ()
330{
331local PARENT DIR
332PARENT=$(ogGetParentPath "$@") || return $?
333DIR="$(basename "${!#}")"
334mkdir -p "$PARENT/$DIR" || ogRaiseError $OG_ERR_NOTFOUND "$*" || return $?
335}
336 
337
338#/**
339#         ogNewPath [ str_repo | int_ndisk int_npartition ] path_filepath
340#@brief   Crea el directorio especificado
341#@param   path_filepath   camino del fichero (independiente de mayúsculas)
342#@param   str_repo        repositorio de ficheros
343#@param   int_ndisk       nº de orden del disco
344#@param   int_npartition  nº de orden de la partición
345#@return  file - camino completo real del directorio creado
346#@note    repo = { REPO, CACHE }
347#@note    Requisitos: \c grep \c sed
348#@exception OG_ERR_FORMAT    Formato incorrecto.
349#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
350#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
351#@warning Primeras pruebas.
352#@todo    Terminar de definir parámetros para acceso a repositorios.
353#@version 0.1 - Primera adaptaci³n para OpenGNSys.
354#@author  obtenido de ogGetPath de Ramon Gomez, ETSII Universidad de Sevilla
355#@date    2009-09-15
356#*/
357function ogNewPath ()
358{
359# Variables locales.
360local MNTDIR FILE PREVFILE FILEPATH CURRENTDIR
361
362#/// Si se solicita, mostrar ayuda.
363if [ "$*" == "help" ]; then
364    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
365           "$FUNCNAME \"/mnt/sda1/windows/system32\"  ==>  /mnt/sda1/WINDOWS/System32" \
366           "$FUNCNAME REPO /etc/fstab  ==>  /opt/opengnsys/images/etc/fstab" \
367           "$FUNCNAME 1 1 \"/windows/system32\"  ==>  /mnt/sda1/WINDOWS/System32"
368    return
369fi
370
371#/// Procesar camino según el número de parámetros.
372case $# in
373     # si 1 parametro directorio-fichero completo.
374    1)  FILE="$1" ;;
375    # Si 2 parametros es REPOSITORIO  DIRECTORIO-FICHERO
376    2)  case "$1" in
377            # consultando servidor repositorio base
378            REPO | $IPREPOMAN )  FILE="$OGIMG/$2" || return $OG_ERR_NOTFOUND ;;
379            # consultando particion auxiliar cache local
380            CACHE | $IP )
381                ogMountCache >> /dev/null &&    FILE="$OGCAC/$OGIMG/$2" || return $OG_ERR_NOTFOUND ;;
382            # conectando con Servidor Axuliar.
383            *)     ogRaiseError $OG_ERR_FORMAT
384                   return $? ;;
385        esac ;;
386    # Si 3 parametros DISK PARTITION DIRECTORIO-FICHERO
387    3)  FILE="$(ogMount $1 $2)/$3" || return $OG_ERR_NOTFOUND ;;
388    *)  return $OG_ERR_FORMAT ;;
389esac
390
391mkdir -p ${FILE}
392echo $FILE
393}
394
Note: See TracBrowser for help on using the repository browser.