source: client/engine/File.lib @ c82725c

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 c82725c was c82725c, checked in by ramon <ramongomez@…>, 12 years ago

Corregida errata en función ogGetPath que devolvía erróneamente el directorio de caché no definida, además ahora la función soporta cualquier combinación de mayúsculas y minúsculas para indicar el tipo de repositorio.

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

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