source: client/engine/Disk.lib @ c21abbc

Last change on this file since c21abbc was 4181251, checked in by ramon <ramongomez@…>, 9 years ago

Versión 1.0.6a, #730: Integrar código y liberar la versión de mantenimiento OpenGnSys 1.0.6a.

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

  • Property mode set to 100755
File size: 51.0 KB
Line 
1#!/bin/bash
2#/**
3#@file    Disk.lib
4#@brief   Librería o clase Disk
5#@class   Disk
6#@brief   Funciones para gestión de discos y particiones.
7#@version 1.0.6
8#@warning License: GNU GPLv3+
9#*/
10
11
12# Función ficticia para lanzar parted con timeout, evitando cuelgues del programa.
13function parted ()
14{
15timeout -k 5s -s KILL 3s $(which parted) "$@"
16}
17
18
19#/**
20#         ogCreatePartitions int_ndisk str_parttype:int_partsize ...
21#@brief   Define el conjunto de particiones de un disco.
22#@param   int_ndisk      nº de orden del disco
23#@param   str_parttype   mnemónico del tipo de partición
24#@param   int_partsize   tamaño de la partición (en KB)
25#@return  (nada, por determinar)
26#@exception OG_ERR_FORMAT    formato incorrecto.
27#@exception OG_ERR_NOTFOUND  disco o partición no detectado (no es un dispositivo).
28#@exception OG_ERR_PARTITION error en partición o en tabla de particiones.
29#@attention El nº de partición se indica por el orden de los párametros \c parttype:partsize
30#@attention Pueden definirse particiones vacías de tipo \c EMPTY
31#@attention No puede definirse partición de cache y no se modifica si existe.
32#@note    Requisitos: sfdisk, parted, partprobe, awk
33#@todo    Definir atributos (arranque, oculta) y tamaños en MB, GB, etc.
34#@version 0.9 - Primera versión para OpenGnSys
35#@author  Ramon Gomez, ETSII Universidad de Sevilla
36#@date    2009/09/09
37#@version 0.9.1 - Corrección del redondeo del tamaño del disco.
38#@author  Ramon Gomez, ETSII Universidad de Sevilla
39#@date    2010/03/09
40#@version 1.0.4 - Llamada a función específica para tablas GPT.
41#@author  Universidad de Huelva
42#@date    2012/03/30
43#*/ ##
44function ogCreatePartitions ()
45{
46# Variables locales.
47local ND DISK PTTYPE PART SECTORS START SIZE TYPE CACHEPART CACHESIZE IOSIZE EXTSTART EXTSIZE tmpsfdisk
48# Si se solicita, mostrar ayuda.
49if [ "$*" == "help" ]; then
50    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk str_parttype:int_partsize ..." \
51           "$FUNCNAME 1 NTFS:10000000 EXT3:5000000 LINUX-SWAP:1000000"
52    return
53fi
54# Error si no se reciben al menos 2 parámetros.
55[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
56
57# Nº total de sectores, para evitar desbordamiento (evitar redondeo).
58ND="$1"
59DISK=$(ogDiskToDev "$ND") || return $?
60PTTYPE=$(ogGetPartitionTableType $1)
61PTTYPE=${PTTYPE:-"MSDOS"}               # Por defecto para discos vacíos.
62case "$PTTYPE" in
63    GPT)   ogCreateGptPartitions "$@"
64           return $? ;;
65    MSDOS) ;;
66    *)     ogRaiseError $OG_ERR_PARTITION "$PTTYPE"
67           return $? ;;
68esac
69SECTORS=$(ogGetLastSector $1)
70# Se recalcula el nº de sectores del disco 1, si existe partición de caché.
71CACHEPART=$(ogFindCache 2>/dev/null)
72[ "$ND" = "${CACHEPART% *}" ] && CACHESIZE=$(ogGetCacheSize 2>/dev/null | awk '{print $0*2}')
73[ -n "$CACHESIZE" ] && SECTORS=$[SECTORS-CACHESIZE]
74# Sector de inicio (la partición 1 empieza en el sector 63).
75##########   agp  ###########
76iodisco=$(ogDiskToDev $1)
77IOSIZE=$(fdisk -l $iodisco | grep I/O | cut -d ":" -f2 | cut -d "/" -f1 | cut -d " " -f2)
78if [[ $IOSIZE = 4096 ]]; then
79        START=4096
80else
81        START=63
82fi
83##########   agp  ###########
84
85
86
87
88
89PART=1
90
91# Fichero temporal de entrada para "sfdisk"
92tmpsfdisk=/tmp/sfdisk$$
93trap "rm -f $tmpsfdisk" 1 2 3 9 15
94
95echo "unit: sectors" >$tmpsfdisk
96echo                >>$tmpsfdisk
97
98# Generar fichero de entrada para "sfdisk" con las particiones.
99shift
100while [ $# -gt 0 ]; do
101    # Conservar los datos de la partición de caché.
102    if [ "$ND $PART" == "$CACHEPART" -a -n "$CACHESIZE" ]; then
103        echo "$DISK$PART : start=$[SECTORS+1], size=$CACHESIZE, Id=ca" >>$tmpsfdisk
104        PART=$[PART+1]
105    fi
106    # Leer formato de cada parámetro - Tipo:Tamaño
107    TYPE="${1%%:*}"
108    SIZE="${1#*:}"
109    # Obtener identificador de tipo de partición válido.
110    ID=$(ogTypeToId "$TYPE" MSDOS)
111    [ "$TYPE" != "CACHE" -a -n "$ID" ] || ogRaiseError $OG_ERR_PARTITION "$TYPE" || return $?
112    # Comprobar tamaño numérico y convertir en sectores de 512 B.
113    [[ "$SIZE" == *([0-9]) ]] || ogRaiseError $OG_ERR_FORMAT "$SIZE" || return $?
114    SIZE=$[SIZE*2]
115    # Comprobar si la partición es extendida.
116    if [ $ID = 5 ]; then
117        [ $PART -le 4 ] || ogRaiseError $OG_ERR_FORMAT || return $?
118        EXTSTART=$START
119        EXTSIZE=$SIZE
120    fi
121    # Incluir particiones lógicas dentro de la partición extendida.
122    if [ $PART = 5 ]; then
123        [ -n "$EXTSTART" ] || ogRaiseError $OG_ERR_FORMAT || return $?
124        START=$EXTSTART
125        SECTORS=$[EXTSTART+EXTSIZE]
126    fi
127    # Generar datos para la partición.
128    echo "$DISK$PART : start=$START, size=$SIZE, Id=$ID" >>$tmpsfdisk
129    # Error si se supera el nº total de sectores.
130    START=$[START+SIZE]
131    [ $START -le $SECTORS ] || ogRaiseError $OG_ERR_FORMAT "$[START/2] > $[SECTORS/2]" || return $?
132    PART=$[PART+1]
133    shift
134done
135# Si no se indican las 4 particiones primarias, definirlas como vacías, conservando la partición de caché.
136while [ $PART -le 4 ]; do
137    if [ "$ND $PART" == "$CACHEPART" -a -n "$CACHESIZE" ]; then
138        echo "$DISK$PART : start=$[SECTORS+1], size=$CACHESIZE, Id=ca" >>$tmpsfdisk
139    else
140        echo "$DISK$PART : start=0, size=0, Id=0" >>$tmpsfdisk
141    fi
142    PART=$[PART+1]
143done
144# Si se define partición extendida sin lógicas, crear particion 5 vacía.
145if [ $PART = 5 -a -n "$EXTSTART" ]; then
146    echo "${DISK}5 : start=$EXTSTART, size=$EXTSIZE, Id=0" >>$tmpsfdisk
147fi
148
149# Desmontar los sistemas de archivos del disco antes de realizar las operaciones.
150ogUnmountAll $ND 2>/dev/null
151[ -n "$CACHESIZE" ] && ogUnmountCache 2>/dev/null
152
153# Si la tabla de particiones no es valida, volver a generarla.
154ogCreatePartitionTable $ND
155# Definir particiones y notificar al kernel.
156sfdisk -f $DISK < $tmpsfdisk 2>/dev/null && partprobe $DISK
157rm -f $tmpsfdisk
158[ -n "$CACHESIZE" ] && ogMountCache 2>/dev/null
159}
160
161
162#/**
163#         ogCreateGptPartitions int_ndisk str_parttype:int_partsize ...
164#@brief   Define el conjunto de particiones de un disco GPT
165#@param   int_ndisk      nº de orden del disco
166#@param   str_parttype   mnemónico del tipo de partición
167#@param   int_partsize   tamaño de la partición (en KB)
168#@return  (nada, por determinar)
169#@exception OG_ERR_FORMAT    formato incorrecto.
170#@exception OG_ERR_NOTFOUND  disco o partición no detectado (no es un dispositivo).
171#@exception OG_ERR_PARTITION error en partición o en tabla de particiones.
172#@attention El nº de partición se indica por el orden de los párametros \c parttype:partsize
173#@attention Pueden definirse particiones vacías de tipo \c EMPTY
174#@attention No puede definirse partición de caché y no se modifica si existe.
175#@note    Requisitos: sfdisk, parted, partprobe, awk
176#@todo    Definir atributos (arranque, oculta) y tamaños en MB, GB, etc.
177#@version 1.0.4 - Primera versión para OpenGnSys
178#@author  Universidad de Huelva
179#@date    2012/03/30
180#*/ ##
181function ogCreateGptPartitions ()
182{
183# Variables locales.
184local ND DISK PART SECTORS ALIGN START SIZE TYPE CACHEPART CACHESIZE DELOPTIONS OPTIONS
185# Si se solicita, mostrar ayuda.
186if [ "$*" == "help" ]; then
187    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk str_parttype:int_partsize ..." \
188           "$FUNCNAME 1 NTFS:10000000 EXT3:5000000 LINUX-SWAP:1000000"
189    return
190fi
191# Error si no se reciben menos de 2 parámetros.
192[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
193
194# Nº total de sectores, para evitar desbordamiento (evitar redondeo).
195ND="$1"
196DISK=$(ogDiskToDev "$ND") || return $?
197# Se calcula el ultimo sector del disco (total de sectores usables)
198SECTORS=$(ogGetLastSector $1)
199[ "$ND" = "${CACHEPART% *}" ] && CACHESIZE=$(ogGetCacheSize 2>/dev/null | awk '{print $0*2}')
200[ -n "$CACHESIZE" ] && SECTORS=$[SECTORS-CACHESIZE]
201# Si el disco es GPT empieza en el sector 2048  por defecto, pero podria cambiarse
202ALIGN=$(sgdisk -D $DISK 2>/dev/null)
203START=$ALIGN
204PART=1
205
206# Leer parámetros con definición de particionado.
207shift
208
209while [ $# -gt 0 ]; do
210    # Si PART es la cache, nos la saltamos y seguimos con el siguiente numero para conservar los datos de la partición de caché.
211    if [ "$ND $PART" == "$CACHEPART" -a -n "$CACHESIZE" ]; then
212        PART=$[PART+1]
213    fi
214    # Leer formato de cada parámetro - Tipo:Tamaño
215    TYPE="${1%%:*}"
216    SIZE="${1#*:}"
217    # Error si la partición es extendida (no válida en discos GPT).
218    if [ "$TYPE" == "EXTENDED" ]; then
219        ogRaiseError $OG_ERR_PARTITION "EXTENDED"
220        return $?
221    fi
222    # Comprobar si existe la particion actual, capturamos su tamaño para ver si cambio o no
223    PARTSIZE=$(ogGetPartitionSize $ND $PART 2>/dev/null)
224    # En sgdisk no se pueden redimensionar las particiones, es necesario borrarlas y volver a crealas
225    [ $PARTSIZE ] && DELOPTIONS="$DELOPTIONS -d$PART"
226    # Creamos la particion
227    # Obtener identificador de tipo de partición válido.
228    ID=$(ogTypeToId "$TYPE" GPT)
229    [ "$TYPE" != "CACHE" -a -n "$ID" ] || ogRaiseError $OG_ERR_PARTITION "$TYPE" || return $?
230    # Comprobar tamaño numérico y convertir en sectores de 512 B.
231    [[ "$SIZE" == *([0-9]) ]] || ogRaiseError $OG_ERR_FORMAT "$SIZE" || return $?
232    SIZE=$[SIZE*2]
233    # SIZE debe ser múltiplo de ALIGN, si no gdisk lo mueve automáticamente.
234    DIV=$[$SIZE/$ALIGN]
235    SIZE=$[$DIV*$ALIGN]
236    # En el caso de que la partición sea EMPTY no se crea nada
237    if [ "$TYPE" != "EMPTY" ]; then
238        OPTIONS="$OPTIONS -n$PART:$START:+$SIZE -t$PART:$ID "
239    fi
240    START=$[START+SIZE]
241    # Error si se supera el nº total de sectores.
242    [ $START -le $SECTORS ] || ogRaiseError $OG_ERR_FORMAT "$[START/2] > $[SECTORS/2]" || return $?
243    PART=$[PART+1]
244    shift
245done
246
247# Desmontar los sistemas de archivos del disco antes de realizar las operaciones.
248ogUnmountAll $ND 2>/dev/null
249[ -n "$CACHESIZE" ] && ogUnmountCache 2>/dev/null
250
251# Si la tabla de particiones no es valida, volver a generarla.
252ogCreatePartitionTable $ND
253# Definir particiones y notificar al kernel.
254# Borramos primero las particiones y luego creamos las nuevas
255sgdisk $DELOPTIONS $OPTIONS $DISK 2>/dev/null && partprobe $DISK
256[ -n "$CACHESIZE" ] && ogMountCache 2>/dev/null
257}
258
259
260#/**
261#         ogCreatePartitionTable int_ndisk [str_tabletype]
262#@brief   Genera una tabla de particiones en caso de que no sea valida, si es valida no hace nada.
263#@param   int_ndisk      nº de orden del disco
264#@param   str_tabletype  tipo de tabla de particiones (opcional)
265#@return  (por determinar)
266#@exception OG_ERR_FORMAT   Formato incorrecto.
267#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
268#@note    tabletype: { MSDOS, GPT }
269#@note    Requisitos: sfdisk, sgdisk
270#@version 1.0.4 - Primera versión compatible con OpenGnSys.
271#@author  Universidad de Huelva
272#@date    2012/03/06
273#@version 1.0.6a - Adaptar creación de nueva tabla MSDOS.
274#@author  Ramon Gomez, ETSII Universidad de Sevilla
275#@date    2016/01/29
276#*/ ##
277function ogCreatePartitionTable ()
278{
279# Variables locales.
280local DISK PTTYPE CREATE CREATEPTT
281
282# Si se solicita, mostrar ayuda.
283if [ "$*" == "help" ]; then
284    ogHelp "$FUNCNAME int_ndisk [str_partype]" \
285           "$FUNCNAME 1 GPT" "$FUNCNAME 1"
286    return
287fi
288# Error si no se reciben 1 o 2 parámetros.
289case $# in
290    1)  CREATEPTT="" ;;
291    2)  CREATEPTT="$2" ;;
292    *)  ogRaiseError $OG_ERR_FORMAT
293        return $? ;;
294esac
295
296# Capturamos el tipo de tabla de particiones actual
297DISK=$(ogDiskToDev $1) || return $?
298PTTYPE=$(ogGetPartitionTableType $1)
299PTTYPE=${PTTYPE:-"MSDOS"}               # Por defecto para discos vacíos.
300CREATEPTT=${CREATEPTT:-"$PTTYPE"}
301
302# Si la tabla actual y la que se indica son iguales, se comprueba si hay que regenerarla.
303if [ "$CREATEPTT" == "$PTTYPE" ]; then
304    case "$PTTYPE" in
305        GPT)   [ ! $(sgdisk -p $DISK 2>&1 >/dev/null) ] || CREATE="GPT" ;;
306        MSDOS) [ $(parted -s $DISK print >/dev/null) ] || CREATE="MSDOS" ;;
307    esac
308else
309    CREATE="$CREATEPTT"
310fi
311# Dependiendo del valor de CREATE, creamos la tabla de particiones en cada caso.
312case "$CREATE" in
313    GPT)
314        # Si es necesario crear una tabla GPT pero la actual es MSDOS
315        if [ "$PTTYPE" == "MSDOS" ]; then
316            sgdisk -g $DISK
317        else
318            echo -e "2\nw\nY\n" | gdisk $DISK
319        fi
320        partprobe $DISK 2>/dev/null
321        ;;
322    MSDOS)
323        # Si es necesario crear una tabla MSDOS pero la actual es GPT
324        if [ "$PTTYPE" == "GPT" ]; then
325            sgdisk -Z $DISK
326        fi
327        # Crear y borrar una partición para que la tabla se genere bien.
328        echo -e "o\nn\np\n\n\n\nd\n\nw" | fdisk $DISK
329        partprobe $DISK 2>/dev/null
330        ;;
331esac
332}
333
334
335#/**
336#         ogDeletePartitionTable ndisk
337#@brief   Borra la tabla de particiones del disco.
338#@param   int_ndisk      nº de orden del disco
339#@return  la informacion propia del fdisk
340#@version 0.1 -  Integracion para OpenGnSys
341#@author  Antonio J. Doblas Viso. Universidad de Malaga
342#@date    2008/10/27
343#@version 1.0.4 - Adaptado para su uso con discos GPT
344#@author  Universidad de Huelva
345#@date    2012/03/13
346#*/ ##
347function ogDeletePartitionTable ()
348{
349# Variables locales.
350local DISK
351
352# Si se solicita, mostrar ayuda.
353if [ "$*" == "help" ]; then
354    ogHelp "$FUNCNAME int_ndisk" "$FUNCNAME 1"
355    return
356fi
357# Error si no se reciben 1 parámetros.
358[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
359
360# Obteniendo Identificador linux del disco.
361DISK=$(ogDiskToDev $1) || return $?
362# Crear una tabla de particiones vacía.
363case "$(ogGetPartitionTableType $1)" in
364    GPT)    sgdisk -o $DISK ;;
365    MSDOS)  echo -ne "o\nw" | fdisk $DISK ;;
366esac
367}
368
369
370#/**
371#         ogDevToDisk path_device | LABEL="str_label" | UUID="str_uuid"
372#@brief   Devuelve el nº de orden de dicso (y partición) correspondiente al nombre de fichero de dispositivo o a la etiqueta o UUID del sistema de archivos asociado.
373#@param   path_device  Camino del fichero de dispositivo.
374#@param   str_label    etiqueta de sistema de archivos.
375#@param   str_uuid     UUID de sistema de archivos.
376#@return  int_ndisk (para dispositivo de disco)
377#@return  int_ndisk int_npartition (para dispositivo de partición).
378#@exception OG_ERR_FORMAT   Formato incorrecto.
379#@exception OG_ERR_NOTFOUND Dispositivo no detectado.
380#@note    Solo se acepta en cada llamada 1 de los 3 tipos de parámetros.
381#@version 0.1 -  Integracion para Opengnsys  -  EAC: DiskEAC() en ATA.lib
382#@author  Antonio J. Doblas Viso, Universidad de Malaga
383#@date    2008/10/27
384#@version 0.9 - Primera version para OpenGnSys
385#@author  Ramon Gomez, ETSII Universidad Sevilla
386#@date    2009/07/20
387#@version 1.0.6 - Soporta parámetro con UIID o etiqueta.
388#@author  Ramon Gomez, ETSII Universidad Sevilla
389#@date    2014/07/13
390#*/ ##
391function ogDevToDisk ()
392{
393# Variables locales.
394local DEV d n
395# Si se solicita, mostrar ayuda.
396if [ "$*" == "help" ]; then
397    ogHelp "$FUNCNAME" "$FUNCNAME path_device | LABEL=str_label | UUID=str_uuid" \
398           "$FUNCNAME /dev/sda  =>  1" \
399           "$FUNCNAME /dev/sda1  =>  1 1" \
400           "$FUNCNAME LABEL=CACHE  =>  1 4"
401    return
402fi
403
404# Error si no se recibe 1 parámetro.
405[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
406
407# Obtener dispositivo a partir de camino, etiqueta o UUID.
408DEV="$1"
409case "$DEV" in
410    LABEL=*)    DEV=$(blkid -L "${1#*=}") ;;
411    UUID=*)     DEV=$(blkid -U "${1#*=}") ;;
412esac
413
414# Error si no es fichero de bloques.
415[ -b "$DEV" ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
416
417# Procesa todos los discos para devolver su nº de orden y de partición.
418n=1
419for d in $(ogDiskToDev); do
420    [ -n "$(echo $DEV | grep $d)" ] && echo "$n ${DEV#$d}" && return
421    n=$[n+1]
422done
423ogRaiseError $OG_ERR_NOTFOUND "$1"
424return $OG_ERR_NOTFOUND
425}
426
427
428#/**
429#         ogDiskToDev [int_ndisk [int_npartition]]
430#@brief   Devuelve la equivalencia entre el nº de orden del dispositivo (dicso o partición) y el nombre de fichero de dispositivo correspondiente.
431#@param   int_ndisk      nº de orden del disco
432#@param   int_npartition nº de orden de la partición
433#@return  Para 0 parametros: Devuelve los nombres de ficheros  de los dispositivos sata/ata/usb linux encontrados.
434#@return  Para 1 parametros: Devuelve la ruta del disco duro indicado.
435#@return  Para 2 parametros: Devuelve la ruta de la particion indicada.
436#@exception OG_ERR_FORMAT   Formato incorrecto.
437#@exception OG_ERR_NOTFOUND Dispositivo no detectado.
438#@note    Requisitos: awk, lvm
439#@version 0.1 -  Integracion para Opengnsys  -  EAC: Disk() en ATA.lib;  HIDRA: DetectarDiscos.sh
440#@author Ramon Gomez, ETSII Universidad de Sevilla
441#@Date    2008/06/19
442#@author  Antonio J. Doblas Viso, Universidad de Malaga
443#@date    2008/10/27
444#@version 0.9 - Primera version para OpenGnSys
445#@author  Ramon Gomez, ETSII Universidad Sevilla
446#@date    2009-07-20
447#@version 1.0.5 - Comprobación correcta de parámetros para soportar valores > 9.
448#@author  Ramon Gomez, ETSII Universidad Sevilla
449#@date    2013-05-07
450#@version 1.0.6 - Soporta RAID hardware y Multipath.
451#@author  Ramon Gomez, ETSII Universidad Sevilla
452#@date    2014-09-23
453#*/ ##
454function ogDiskToDev ()
455{
456# Variables locales
457local ALLDISKS MPATH VOLGROUPS DISK PART i
458
459# Si se solicita, mostrar ayuda.
460if [ "$*" == "help" ]; then
461    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk [int_npartition]" \
462           "$FUNCNAME      =>  /dev/sda /dev/sdb" \
463           "$FUNCNAME 1    =>  /dev/sda" \
464           "$FUNCNAME 1 1  =>  /dev/sda1"
465    return
466fi
467
468# Listar dispositivos de discos duros.
469ALLDISKS=$(lsblk -n | awk '$6~/^disk$/ {gsub(/!/,"/"); printf "/dev/%s ",$1}')
470
471# Listar volúmenes lógicos.
472VOLGROUPS=$(vgs -a --noheadings 2>/dev/null | awk '{printf "/dev/%s ",$1}')
473ALLDISKS="$ALLDISKS $VOLGROUPS"
474
475# Detectar caminos múltiples (ignorar mensaje si no está configurado Multipath).
476if MPATH=$(multipath -l -v 1 2>/dev/null | awk '{printf "/dev/mapper/%s ",$1}'; exit ${PIPESTATUS[0]}); then
477    # Quitar de la lista los discos que forman parte de Multipath.
478    for i in $(multipath -ll | awk '$6=="ready" {printf "/dev/%s ",$3}'); do
479        ALLDISKS="${ALLDISKS//$i/}"
480    done
481    # Añadir caminos múltiples a los discos detectados.
482    ALLDISKS="$ALLDISKS $MPATH"
483fi
484
485# Mostrar salidas segun el número de parametros.
486case $# in
487    0)  # Muestra todos los discos, separados por espacios.
488        echo $ALLDISKS
489        ;;
490    1)  # Error si el parámetro no es un número positivo.
491        [[ "$1" =~ ^[1-9][0-9]*$ ]] || ogRaiseError $OG_ERR_FORMAT "$1" || return $?
492        DISK=$(echo "$ALLDISKS" | awk -v n=$1 '{print $n}')
493        # Error si el fichero no existe.
494        [ -e "$DISK" ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
495        echo "$DISK"
496        ;;
497    2)  # Error si los 2 parámetros no son números positivos.
498        [[ "$1" =~ ^[1-9][0-9]*$ ]] && [[ "$2" =~ ^[1-9][0-9]*$ ]] || ogRaiseError $OG_ERR_FORMAT "$1 $2" || return $?
499        DISK=$(echo "$ALLDISKS" | awk -v n=$1 '{print $n}')
500        [ -e "$DISK" ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
501        PART="$DISK$2"
502        # Comprobar si es partición.
503        if [ -b "$PART" ]; then
504            echo "$PART"
505        else
506            # Comprobar si RAID o Multipath (tener en cuenta enlace simbólico).
507            PART="${DISK}p$2"
508            if [ "$(stat -L -c "%A" "$PART" 2>/dev/null | cut -c1)" == "b" ]; then
509                echo "$PART"
510            elif [ -n "$VOLGROUPS" ]; then
511                # Comprobar si volumen lógico.      /* (comentario Doxygen)
512                PART=$(lvscan -a 2>/dev/null | \
513                       awk -F\' -v n=$2 "\$2~/^${DISK//\//\\/}\// {if (NR==n) print \$2}")
514                [ -e "$PART" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2" || return $?
515                #                                   (comentario Doxygen) */
516                echo "$PART"
517            else
518                ogRaiseError $OG_ERR_NOTFOUND "$1 $2" || return $?
519            fi
520        fi
521        ;;
522    *)  # Formato erroneo.
523        ogRaiseError $OG_ERR_FORMAT
524        return $OG_ERR_FORMAT
525        ;;
526esac
527}
528
529
530#/**
531#         ogGetDiskSize int_ndisk
532#@brief   Muestra el tamaño en KB de un disco.
533#@param   int_ndisk   nº de orden del disco
534#@return  int_size  - Tamaño en KB del disco.
535#@exception OG_ERR_FORMAT   formato incorrecto.
536#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
537#@note    Requisitos: sfdisk, awk
538#@version 0.9.2 - Primera version para OpenGnSys
539#@author  Ramon Gomez, ETSII Universidad de Sevilla
540#@date    2010/09/15
541#@version 1.0.6 - Soportar LVM.
542#@author  Universidad de Huelva
543#@date    2014/09/04
544#*/ ##
545function ogGetDiskSize ()
546{
547# Variables locales.
548local DISK SIZE
549
550# Si se solicita, mostrar ayuda.
551if [ "$*" == "help" ]; then
552    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" "$FUNCNAME 1  => 244198584"
553    return
554fi
555# Error si no se recibe 1 parámetro.
556[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
557
558# Obtener el tamaño del disco.
559DISK="$(ogDiskToDev $1)" || return $?
560SIZE=$(awk -v D=${DISK#/dev/} '{if ($4==D) {print $3}}' /proc/partitions)
561# Si no, obtener tamaño del grupo de volúmenes.
562[ -z "$SIZE" ] && SIZE=$(vgs --noheadings --units=B -o dev_size $DISK 2>/dev/null | \
563                         awk '{print $1/1024}')
564
565# Mostrar salida.
566[ -n "$SIZE" ] && echo "$SIZE"
567}
568
569
570#/**
571#         ogGetDiskType path_device
572#@brief   Muestra el tipo de disco (real, RAID, meta-disco, etc.).
573#@warning Función en pruebas
574#*/ ##
575function ogGetDiskType ()
576{
577local DEV MAJOR TYPE
578
579# Obtener el driver del dispositivo de bloques.
580[ -b "$1" ] || ogRaiseError $OG_ERR_FORMAT || return $?
581DEV=${1#/dev/}
582MAJOR=$(awk -v D="$DEV" '{if ($4==D) print $1;}' /proc/partitions)
583TYPE=$(awk -v D=$MAJOR '/Block/ {bl=1} {if ($1==D&&bl) print toupper($2)}' /proc/devices)
584# Devolver mnemónico del driver de dispositivo.
585case "$TYPE" in
586    SD)            TYPE="DISK" ;;
587    SR|IDE*)       TYPE="CDROM" ;;         # FIXME Comprobar discos IDE.
588    MD|CCISS*)     TYPE="RAID" ;;
589    DEVICE-MAPPER) TYPE="MAPPER" ;;        # FIXME Comprobar LVM y RAID.
590esac
591echo $TYPE
592}
593
594
595#/**
596#         ogGetLastSector int_ndisk [int_npart]
597#@brief   Devuelve el último sector usable del disco o de una partición.
598#@param   int_ndisk      nº de orden del disco
599#@param   int_npart      nº de orden de la partición (opcional)
600#@return  Último sector usable.
601#@exception OG_ERR_FORMAT   Formato incorrecto.
602#@exception OG_ERR_NOTFOUND Disco o partición no corresponde con un dispositivo.
603#@note    Requisitos: sfdisk, sgdisk
604#@version 1.0.4 - Primera versión compatible con OpenGnSys.
605#@author  Universidad de Huelva
606#@date    2012/06/03
607#*/ ##
608
609function ogGetLastSector ()
610{
611# Variables locales
612local DISK PART PTTYPE LASTSECTOR SECTORS CYLS IOSIZE
613# Si se solicita, mostrar ayuda.
614if [ "$*" == "help" ]; then
615    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk [int_npart]" \
616           "$FUNCNAME 1  =>  488392064" \
617           "$FUNCNAME 1 1  =>  102400062"
618    return
619fi
620# Error si no se reciben 1 o 2 parámetros.
621case $# in
622    1)  DISK=$(ogDiskToDev $1) || return $?
623        ;;
624    2)  DISK=$(ogDiskToDev $1) || return $?
625        PART=$(ogDiskToDev $1 $2) || return $?
626        ;;
627    *)  ogRaiseError $OG_ERR_FORMAT
628        return $? ;;
629esac
630
631# Hay que comprobar si el disco es GPT
632PTTYPE=$(ogGetPartitionTableType $1)
633PTTYPE=${PTTYPE:-"MSDOS"}               # Por defecto para discos vacíos.
634case "$PTTYPE" in
635    GPT)
636        if [ $# == 1 ]; then
637            LASTSECTOR=$(LANG=C sgdisk -p $DISK | awk '/last usable sector/ {print($(NF))}')
638        else
639            LASTSECTOR=$(LANG=C sgdisk -p $DISK | awk -v P="$2" '{if ($1==P) print $3}')
640        fi
641        ;;
642    MSDOS)
643        if [ $# == 1 ]; then
644            SECTORS=$(awk -v D=${DISK#/dev/} '{if ($4==D) {print $3*2}}' /proc/partitions)
645            CYLS=$(sfdisk -g $DISK | cut -f2 -d" ")
646            ##########   agp  ###########
647            IOSIZE=$(fdisk -l $DISK | grep I/O | cut -d ":" -f2 | cut -d "/" -f1 | cut -d " " -f2)
648            if [[ $IOSIZE = 4096 ]]; then
649                LASTSECTOR=$[SECTORS-512]
650            else
651                LASTSECTOR=$[SECTORS/CYLS*CYLS-1]
652            fi
653            ##########   agp  ###########
654        else
655            LASTSECTOR=$(sfdisk -uS -l $DISK 2>/dev/null | \
656                         awk -v P="$PART" '{if ($1==P) {if ($2=="*") print $4; else print $3} }')
657        fi
658        ;;
659esac
660echo $LASTSECTOR
661}
662
663
664#/**
665#         ogGetPartitionActive int_ndisk
666#@brief   Muestra que particion de un disco esta marcada como de activa.
667#@param   int_ndisk   nº de orden del disco
668#@return  int_npart   Nº de partición activa
669#@exception OG_ERR_FORMAT Formato incorrecto.
670#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
671#@note    Requisitos: parted
672#@todo    Queda definir formato para atributos (arranque, oculta, ...).
673#@version 0.9 - Primera version compatible con OpenGnSys.
674#@author  Ramon Gomez, ETSII Universidad de Sevilla
675#@date    2009/09/17
676#*/ ##
677function ogGetPartitionActive ()
678{
679# Variables locales
680local DISK
681
682# Si se solicita, mostrar ayuda.
683if [ "$*" == "help" ]; then
684    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" "$FUNCNAME 1  =>  1"
685    return
686fi
687# Error si no se recibe 1 parámetro.
688[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
689
690# Comprobar que el disco existe y listar su partición activa.
691DISK="$(ogDiskToDev $1)" || return $?
692parted $DISK print 2>/dev/null | awk '/boot/ {print $1}'
693}
694
695
696#/**
697#         ogGetPartitionId int_ndisk int_npartition
698#@brief   Devuelve el mnemónico con el tipo de partición.
699#@param   int_ndisk      nº de orden del disco
700#@param   int_npartition nº de orden de la partición
701#@return  Identificador de tipo de partición.
702#@exception OG_ERR_FORMAT   Formato incorrecto.
703#@exception OG_ERR_NOTFOUND Disco o partición no corresponde con un dispositivo.
704#@note    Requisitos: sfdisk
705#@version 0.9 - Primera versión compatible con OpenGnSys.
706#@author  Ramon Gomez, ETSII Universidad de Sevilla
707#@date    2009/03/25
708#@version 1.0.2 - Detectar partición vacía.
709#@author  Ramon Gomez, ETSII Universidad de Sevilla
710#@date    2011/12/23
711#*/ ##
712function ogGetPartitionId ()
713{
714# Variables locales.
715local DISK PART ID
716
717# Si se solicita, mostrar ayuda.
718if [ "$*" == "help" ]; then
719    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
720           "$FUNCNAME 1 1  =>  7"
721    return
722fi
723# Error si no se reciben 2 parámetros.
724[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
725
726# Detectar id. de tipo de partición y codificar al mnemónico.
727DISK=$(ogDiskToDev $1) || return $?
728PART=$(ogDiskToDev $1 $2) || return $?
729case "$(ogGetPartitionTableType $1)" in
730    GPT)    ID=$(sgdisk -p $DISK 2>/dev/null | awk -v p="$2" '{if ($1==p) print $6;}') || ogRaiseError $OG_ERR_NOTFOUND "$1,$2" || return $?
731            [ "$ID" == "8301" -a "$1 $2" == "$(ogFindCache)" ] && ID=CA00
732            ;;
733    MSDOS)  ID=$(sfdisk --id $DISK $2 2>/dev/null) || ogRaiseError $OG_ERR_NOTFOUND "$1,$2" || return $? ;;
734esac
735echo $ID
736}
737
738
739#/**
740#         ogGetPartitionSize int_ndisk int_npartition
741#@brief   Muestra el tamano en KB de una particion determinada.
742#@param   int_ndisk      nº de orden del disco
743#@param   int_npartition nº de orden de la partición
744#@return  int_partsize - Tamaño en KB de la partición.
745#@exception OG_ERR_FORMAT   formato incorrecto.
746#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
747#@note    Requisitos: sfdisk, awk
748#@version 0.1 -  Integracion para Opengnsys  -  EAC: SizePartition () en ATA.lib
749#@author  Antonio J. Doblas Viso, Universidad de Malaga
750#@date    2008/10/27
751#@version 0.9 - Primera version para OpenGnSys
752#@author  Ramon Gomez, ETSII Universidad de Sevilla
753#@date    2009/07/24
754#*/ ##
755function ogGetPartitionSize ()
756{
757# Variables locales.
758local DISK PART
759
760# Si se solicita, mostrar ayuda.
761if [ "$*" == "help" ]; then
762    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
763           "$FUNCNAME 1 1  =>  10000000"
764    return
765fi
766# Error si no se reciben 2 parámetros.
767[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
768
769# Obtener el tamaño de la partición.
770DISK="$(ogDiskToDev $1)" || return $?
771PART="$(ogDiskToDev $1 $2)" || return $?
772case "$(ogGetPartitionId $1 $2)" in
773    5|f)  # Procesar detección de tamaño de partición Extendida.
774          sfdisk -l $DISK 2>/dev/null | \
775                    awk -v p=$PART '{if ($1==p) {sub (/[^0-9]+/,"",$5); print $5} }'
776          ;;
777    *)    sfdisk -s $PART
778          ;;
779esac
780}
781
782
783#/**
784#         ogGetPartitionsNumber int_ndisk
785#@brief   Detecta el numero de particiones del disco duro indicado.
786#@param   int_ndisk      nº de orden del disco
787#@return  Devuelve el numero paritiones del disco duro indicado
788#@warning Salidas de errores no determinada
789#@attention Requisitos: parted
790#@note    Notas sin especificar
791#@version 0.1 -  Integracion para Opengnsys  -  EAC:  DetectNumberPartition () en ATA.lib
792#@author  Antonio J. Doblas Viso. Universidad de Malaga
793#@date    Date: 27/10/2008
794#@version 1.0 - Uso de sfdisk Primera version para OpenGnSys
795#@author  Ramon Gomez, ETSII Universidad de Sevilla
796#@date    2009/07/24
797#@version 1.0.4 - Uso de /proc/partitions para detectar el numero de particiones
798#@author  Universidad de Huelva
799#@date    2012/03/28
800#@version 1.0.6 - Soportar LVM.
801#@author  Universidad de Huelva
802#@date    2014/09/04
803#*/ ##
804function ogGetPartitionsNumber ()
805{
806# Variables locales.
807local DISK
808# Si se solicita, mostrar ayuda.
809if [ "$*" == "help" ]; then
810    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
811           "$FUNCNAME 1  =>  3"
812    return
813fi
814# Error si no se recibe 1 parámetro.
815[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
816
817# Contar el nº de veces que aparece el disco en su lista de particiones.
818DISK=$(ogDiskToDev $1) 2>/dev/null
819case "$(ogGetPartitionTableType $1)" in
820    GPT)    grep -c "${DISK#/dev/}." /proc/partitions ;;
821    MSDOS)  sfdisk -l $DISK 2>/dev/null | grep -c "^$DISK" ;;
822    LVM)    lvs --noheadings $DISK 2>/dev/null | wc -l ;;
823esac
824}
825
826
827#/**
828#         ogGetPartitionTableType int_ndisk
829#@brief   Devuelve el tipo de tabla de particiones del disco (GPT o MSDOS)
830#@param   int_ndisk       nº de orden del disco
831#@return  str_tabletype - Tipo de tabla de paritiones
832#@warning Salidas de errores no determinada
833#@note    tabletype = { MSDOS, GPT }
834#@note    Requisitos: parted
835#@version 1.0.4 - Primera versión para OpenGnSys
836#@author  Universidad de Huelva
837#@date    2012/03/01
838#@version 1.0.6 - Soportar LVM.
839#@author  Universidad de Huelva
840#@date    2014/09/04
841#*/ ##
842function ogGetPartitionTableType ()
843{
844# Variables locales.
845local DISK TYPE
846
847# Si se solicita, mostrar ayuda.
848if [ "$*" == "help" ]; then
849    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
850           "$FUNCNAME 1  =>  MSDOS"
851    return
852fi
853# Error si no se recibe 1 parámetro.
854[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
855
856# Sustituye n de disco por su dispositivo.
857DISK=$(ogDiskToDev $1) || return $?
858
859# Comprobar tabla de particiones.
860[ -b $DISK ] && TYPE=$(parted -sm $DISK print | awk -F: -v D=$DISK '{ if($1 == D) print toupper($6)}')
861[ -d $DISK ] && vgs $DISK &>/dev/null && TYPE="LVM"
862
863# Mostrar salida.
864[ -n "$TYPE" ] && echo "$TYPE"
865}
866
867
868#/**
869#         ogGetPartitionType int_ndisk int_npartition
870#@brief   Devuelve el mnemonico con el tipo de partición.
871#@param   int_ndisk      nº de orden del disco
872#@param   int_npartition nº de orden de la partición
873#@return  Mnemonico
874#@note    Mnemonico: valor devuelto por ogIdToType.
875#@exception OG_ERR_FORMAT   Formato incorrecto.
876#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
877#@version 0.1 -  Integracion para Opengnsys  -  EAC:   TypeFS() en ATA.lib
878#@author  Antonio J. Doblas Viso. Universidad de Malaga
879#@date    2008-10-27
880#@version 0.9 - Primera adaptacion para OpenGnSys.
881#@author  Ramon Gomez, ETSII Universidad de Sevilla
882#@date    2009-07-21
883#@version 1.0.3 - Código trasladado de antigua función ogGetFsType.
884#@author  Ramon Gomez, ETSII Universidad de Sevilla
885#@date    2011-12-01
886#@version 1.0.5 - Usar función ogIdToType para hacer la conversión id. a tipo.
887#@author  Ramon Gomez, ETSII Universidad de Sevilla
888#@date    2013-09-19
889#*/ ##
890function ogGetPartitionType ()
891{
892# Variables locales.
893local ID TYPE
894
895# Si se solicita, mostrar ayuda.
896if [ "$*" == "help" ]; then
897    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
898           "$FUNCNAME 1 1  =>  NTFS"
899    return
900fi
901# Error si no se reciben 2 parámetros.
902[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
903
904# Detectar id. de tipo de partición y codificar al mnemonico.
905ID=$(ogGetPartitionId "$1" "$2") || return $?
906TYPE=$(ogIdToType "$ID")
907echo "$TYPE"
908}
909
910
911#/**
912#         ogHidePartition int_ndisk int_npartition
913#@brief   Oculta un apartición visible.
914#@param   int_ndisk      nº de orden del disco
915#@param   int_npartition nº de orden de la partición
916#@return  (nada)
917#@exception OG_ERR_FORMAT    formato incorrecto.
918#@exception OG_ERR_NOTFOUND  disco o particion no detectado (no es un dispositivo).
919#@exception OG_ERR_PARTITION tipo de partición no reconocido.
920#@version 1.0 - Versión en pruebas.
921#@author  Ramon Gomez, ETSII Universidad de Sevilla
922#@date    2010/01/12
923#*/ ##
924function ogHidePartition ()
925{
926# Variables locales.
927local PART TYPE NEWTYPE
928# Si se solicita, mostrar ayuda.
929if [ "$*" == "help" ]; then
930    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
931           "$FUNCNAME 1 1"
932    return
933fi
934# Error si no se reciben 2 parámetros.
935[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
936PART=$(ogDiskToDev "$1" "$2") || return $?
937
938# Obtener tipo de partición.
939TYPE=$(ogGetPartitionType "$1" "$2")
940case "$TYPE" in
941    NTFS)   NEWTYPE="HNTFS"  ;;
942    FAT32)  NEWTYPE="HFAT32" ;;
943    FAT16)  NEWTYPE="HFAT16" ;;
944    FAT12)  NEWTYPE="HFAT12" ;;
945    *)      ogRaiseError $OG_ERR_PARTITION "$TYPE"
946            return $? ;;
947esac
948# Cambiar tipo de partición.
949ogSetPartitionType $1 $2 $NEWTYPE
950}
951
952
953#/**
954#         ogIdToType int_idpart
955#@brief   Devuelve el identificador correspondiente a un tipo de partición.
956#@param   int_idpart    identificador de tipo de partición.
957#@return  str_parttype  mnemónico de tipo de partición.
958#@exception OG_ERR_FORMAT   Formato incorrecto.
959#@version 1.0.5 - Primera version para OpenGnSys
960#@author  Ramon Gomez, ETSII Universidad Sevilla
961#@date    2013-02-07
962#*/ ##
963function ogIdToType ()
964{
965# Variables locales
966local ID TYPE
967
968# Si se solicita, mostrar ayuda.
969if [ "$*" == "help" ]; then
970    ogHelp "$FUNCNAME" "$FUNCNAME int_idpart" \
971           "$FUNCNAME 83  =>  LINUX"
972    return
973fi
974# Error si no se recibe 1 parámetro.
975[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
976
977# Obtener valor hexadecimal de 4 caracteres rellenado con 0 por delante.
978ID=$(printf "%4s" "$1" | tr ' ' '0')
979case "${ID,,}" in
980     0000)      TYPE="EMPTY" ;;
981     0001)      TYPE="FAT12" ;;
982     0005|000f) TYPE="EXTENDED" ;;
983     0006|000e) TYPE="FAT16" ;;
984     0007)      TYPE="NTFS" ;;
985     000b|000c) TYPE="FAT32" ;;
986     0011)      TYPE="HFAT12" ;;
987     0012)      TYPE="COMPAQDIAG" ;;
988     0016|001e) TYPE="HFAT16" ;;
989     0017)      TYPE="HNTFS" ;;
990     001b|001c) TYPE="HFAT32" ;;
991     0042)      TYPE="WIN-DYNAMIC" ;;
992     0082|8200) TYPE="LINUX-SWAP" ;;
993     0083|8300) TYPE="LINUX" ;;
994     008e|8E00) TYPE="LINUX-LVM" ;;
995     00a5|a503) TYPE="FREEBSD" ;;
996     00a6)      TYPE="OPENBSD" ;;
997     00a7)      TYPE="CACHE" ;;         # (compatibilidad con Brutalix)
998     00af|af00) TYPE="HFS" ;;
999     00be|be00) TYPE="SOLARIS-BOOT" ;;
1000     00bf|bf0[0145]) TYPE="SOLARIS" ;;
1001     00ca|ca00) TYPE="CACHE" ;;
1002     00da)      TYPE="DATA" ;;
1003     00ee)      TYPE="GPT" ;;
1004     00ef|ef00) TYPE="EFI" ;;
1005     00fb)      TYPE="VMFS" ;;
1006     00fd|fd00) TYPE="LINUX-RAID" ;;
1007     0700)      TYPE="WINDOWS" ;;
1008     0c01)      TYPE="WIN-RESERV" ;;
1009     7f00)      TYPE="CHROMEOS-KRN" ;;
1010     7f01)      TYPE="CHROMEOS" ;;
1011     7f02)      TYPE="CHROMEOS-RESERV" ;;
1012     8301)      TYPE="LINUX-RESERV" ;;
1013     a500)      TYPE="FREEBSD-DISK" ;;
1014     a501)      TYPE="FREEBSD-BOOT" ;;
1015     a502)      TYPE="FREEBSD-SWAP" ;;
1016     ab00)      TYPE="HFS-BOOT" ;;
1017     af01)      TYPE="HFS-RAID" ;;
1018     bf02)      TYPE="SOLARIS-SWAP" ;;
1019     bf03)      TYPE="SOLARIS-DISK" ;;
1020     ef01)      TYPE="MBR" ;;
1021     ef02)      TYPE="BIOS-BOOT" ;;
1022     *)         TYPE="UNKNOWN" ;;
1023esac
1024echo "$TYPE"
1025}
1026
1027
1028#/**
1029#         ogListPartitions int_ndisk
1030#@brief   Lista las particiones definidas en un disco.
1031#@param   int_ndisk  nº de orden del disco
1032#@return  str_parttype:int_partsize ...
1033#@exception OG_ERR_FORMAT   formato incorrecto.
1034#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
1035#@note    Requisitos: \c parted \c awk
1036#@attention El nº de partición se indica por el orden de los párametros \c parttype:partsize
1037#@attention Las tuplas de valores están separadas por espacios.
1038#@version 0.9 - Primera versión para OpenGnSys
1039#@author  Ramon Gomez, ETSII Universidad de Sevilla
1040#@date    2009/07/24
1041#*/ ##
1042function ogListPartitions ()
1043{
1044# Variables locales.
1045local DISK PART NPARTS TYPE SIZE
1046
1047# Si se solicita, mostrar ayuda.
1048if [ "$*" == "help" ]; then
1049    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
1050           "$FUNCNAME 1  =>  NTFS:10000000 EXT3:5000000 LINUX-SWAP:1000000"
1051    return
1052fi
1053# Error si no se recibe 1 parámetro.
1054[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT "$FORMAT" || return $?
1055
1056# Procesar la salida de \c parted .
1057DISK="$(ogDiskToDev $1)" || return $?
1058NPARTS=$(ogGetPartitionsNumber $1)
1059for (( PART = 1; PART <= NPARTS; PART++ )); do
1060    TYPE=$(ogGetPartitionType $1 $PART 2>/dev/null)
1061    if [ $? -eq 0 ]; then
1062        SIZE=$(ogGetPartitionSize $1 $PART 2>/dev/null)
1063        echo -n "$TYPE:$SIZE "
1064    else
1065        echo -n "EMPTY:0 "
1066    fi
1067done
1068echo
1069}
1070
1071
1072#/**
1073#         ogListPrimaryPartitions int_ndisk
1074#@brief   Metafunción que lista las particiones primarias no vacías de un disco.
1075#@param   int_ndisk  nº de orden del disco
1076#@see     ogListPartitions
1077#*/ ##
1078function ogListPrimaryPartitions ()
1079{
1080# Variables locales.
1081local PTTYPE PARTS
1082
1083PTTYPE=$(ogGetPartitionTableType $1) || return $?
1084PARTS=$(ogListPartitions "$@") || return $?
1085case "$PTTYPE" in
1086    GPT)    echo $PARTS | sed 's/\( EMPTY:0\)*$//' ;;
1087    MSDOS)  echo $PARTS | cut -sf1-4 -d" " | sed 's/\( EMPTY:0\)*$//' ;;
1088esac
1089}
1090
1091
1092#/**
1093#         ogListLogicalPartitions int_ndisk
1094#@brief   Metafunción que lista las particiones lógicas de una tabla tipo MSDOS.
1095#@param   int_ndisk  nº de orden del disco
1096#@see     ogListPartitions
1097#*/ ##
1098function ogListLogicalPartitions ()
1099{
1100# Variables locales.
1101local PTTYPE PARTS
1102
1103PTTYPE=$(ogGetPartitionTableType $1) || return $?
1104[ "$PTTYPE" == "MSDOS" ] || ogRaiseError $OG_ERR_PARTITION "" || return $?
1105PARTS=$(ogListPartitions "$@") || return $?
1106echo $PARTS | cut -sf5- -d" "
1107}
1108
1109
1110#/**
1111#         ogSetPartitionActive int_ndisk int_npartition
1112#@brief   Establece cual es la partición activa de un disco.
1113#@param   int_ndisk      nº de orden del disco
1114#@param   int_npartition nº de orden de la partición
1115#@return  (nada).
1116#@exception OG_ERR_FORMAT   Formato incorrecto.
1117#@exception OG_ERR_NOTFOUND Disco o partición no corresponden con un dispositivo.
1118#@note    Requisitos: parted
1119#@version 0.1 -  Integracion para Opengnsys  -  EAC: SetPartitionActive() en ATA.lib
1120#@author  Antonio J. Doblas Viso, Universidad de Malaga
1121#@date    2008/10/27
1122#@version 0.9 - Primera version compatible con OpenGnSys.
1123#@author  Ramon Gomez, ETSII Universidad de Sevilla
1124#@date    2009/09/17
1125#*/ ##
1126function ogSetPartitionActive ()
1127{
1128# Variables locales
1129local DISK PART
1130
1131# Si se solicita, mostrar ayuda.
1132if [ "$*" == "help" ]; then
1133    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1134           "$FUNCNAME 1 1"
1135    return
1136fi
1137# Error si no se reciben 2 parámetros.
1138[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1139
1140# Comprobar que el disco existe y activar la partición indicada.
1141DISK="$(ogDiskToDev $1)" || return $?
1142PART="$(ogDiskToDev $1 $2)" || return $?
1143parted -s $DISK set $2 boot on 2>/dev/null
1144}
1145
1146
1147#/**
1148#         ogSetPartitionId int_ndisk int_npartition hex_partid
1149#@brief   Cambia el identificador de la partición.
1150#@param   int_ndisk      nº de orden del disco
1151#@param   int_npartition nº de orden de la partición
1152#@param   hex_partid     identificador de tipo de partición
1153#@return  (nada)
1154#@exception OG_ERR_FORMAT     Formato incorrecto.
1155#@exception OG_ERR_NOTFOUND   Disco o partición no corresponden con un dispositivo.
1156#@exception OG_ERR_OUTOFLIMIT Valor no válido.
1157#@exception OG_ERR_PARTITION  Error al cambiar el id. de partición.
1158#@attention Requisitos: fdisk, sgdisk
1159#@version 0.1 -  Integracion para Opengnsys  - SetPartitionType() en ATA.lib
1160#@author  Antonio J. Doblas Viso. Universidad de Malaga
1161#@date    2008/10/27
1162#@version 1.0.4 - Soporte para discos GPT.
1163#@author  Universidad de Huelva
1164#@date    2012/03/13
1165#@version 1.0.5 - Utiliza el id. de tipo de partición (no el mnemónico)
1166#@author  Universidad de Huelva
1167#@date    2012/05/14
1168#*/ ##
1169function ogSetPartitionId ()
1170{
1171# Variables locales
1172local DISK PART PTTYPE ID
1173
1174# Si se solicita, mostrar ayuda.
1175if [ "$*" == "help" ]; then
1176    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition hex_partid" \
1177           "$FUNCNAME 1 1 7"
1178    return
1179fi
1180# Error si no se reciben 3 parámetros.
1181[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1182
1183# Sustituye nº de disco y nº partición por su dispositivo.
1184DISK=$(ogDiskToDev $1) || return $?
1185PART=$(ogDiskToDev $1 $2) || return $?
1186# Error si el id. de partición no es hexadecimal.
1187ID="${3^^}"
1188[[ "$ID" =~ ^[0-9A-F]+$ ]] || ogRaiseError $OG_ERR_OUTOFLIMIT "$3" || return $?
1189
1190# Elección del tipo de partición.
1191PTTYPE=$(ogGetPartitionTableType $1)
1192case "$PTTYPE" in
1193    GPT)    sgdisk -t$2:$ID $DISK 2>/dev/null ;;
1194    MSDOS)  echo -ne "t\n$2\n${ID}\nw\n" | fdisk $DISK | grep Syncing &>/dev/null ;;
1195    *)      ogRaiseError $OG_ERR_OUTOFLIMIT "$1,$PTTYPE"
1196            return $? ;;
1197esac
1198
1199# MSDOS) Correcto si fdisk sin error o con error pero realiza Syncing
1200if [ "${PIPESTATUS[1]}" == "0" -o $? -eq 0 ]; then
1201    partprobe $DISK 2>/dev/null
1202    return 0
1203else
1204    ogRaiseError $OG_ERR_PARTITION "$1,$2,$3"
1205    return $?
1206fi
1207}
1208
1209
1210#/**
1211#         ogSetPartitionSize int_ndisk int_npartition int_size
1212#@brief   Muestra el tamano en KB de una particion determinada.
1213#@param   int_ndisk      nº de orden del disco
1214#@param   int_npartition nº de orden de la partición
1215#@param   int_size       tamaño de la partición (en KB)
1216#@return  (nada)
1217#@exception OG_ERR_FORMAT   formato incorrecto.
1218#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
1219#@note    Requisitos: sfdisk, awk
1220#@todo    Compruebar que el tamaño sea numérico positivo y evitar que pueda solaparse con la siguiente partición.
1221#@version 0.9 - Primera versión para OpenGnSys
1222#@author  Ramon Gomez, ETSII Universidad de Sevilla
1223#@date    2009/07/24
1224#*/ ##
1225function ogSetPartitionSize ()
1226{
1227# Variables locales.
1228local DISK PART SIZE
1229
1230# Si se solicita, mostrar ayuda.
1231if [ "$*" == "help" ]; then
1232    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_size" \
1233           "$FUNCNAME 1 1 10000000"
1234    return
1235fi
1236# Error si no se reciben 3 parámetros.
1237[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1238
1239# Obtener el tamaño de la partición.
1240DISK="$(ogDiskToDev $1)" || return $?
1241PART="$(ogDiskToDev $1 $2)" || return $?
1242# Convertir tamaño en KB a sectores de 512 B.
1243SIZE=$[$3*2] || ogRaiseError $OG_ERR_FORMAT || return $?
1244# Redefinir el tamaño de la partición.
1245sfdisk -f -uS -N$2 $DISK <<< ",$SIZE" &>/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
1246partprobe $DISK 2>/dev/null
1247}
1248
1249
1250#/**
1251#         ogSetPartitionType int_ndisk int_npartition str_type
1252#@brief   Cambia el identificador de la partición.
1253#@param   int_ndisk      nº de orden del disco
1254#@param   int_npartition nº de orden de la partición
1255#@param   str_type       mnemónico de tipo de partición
1256#@return  (nada)
1257#@attention Requisitos: fdisk, sgdisk
1258#@version 0.1 -  Integracion para Opengnsys  - SetPartitionType() en ATA.lib
1259#@author  Antonio J. Doblas Viso. Universidad de Malaga
1260#@date    2008/10/27
1261#@version 1.0.4 - Soporte para discos GPT.
1262#@author  Universidad de Huelva
1263#@date    2012/03/13
1264#@version 1.0.5 - Renombrada de ogSetPartitionId.
1265#@author  Ramon Gomez, ETSII Universidad de Sevilla
1266#@date    2013/03/07
1267#*/ ##
1268function ogSetPartitionType ()
1269{
1270# Variables locales
1271local DISK PART PTTYPE ID
1272
1273# Si se solicita, mostrar ayuda.
1274if [ "$*" == "help" ]; then
1275    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition str_type" \
1276           "$FUNCNAME 1 1 NTFS"
1277    return
1278fi
1279# Error si no se reciben 3 parámetros.
1280[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1281
1282# Sustituye nº de disco por su dispositivo.
1283DISK=`ogDiskToDev $1` || return $?
1284PART=`ogDiskToDev $1 $2` || return $?
1285
1286# Elección del tipo de partición.
1287PTTYPE=$(ogGetPartitionTableType $1)
1288ID=$(ogTypeToId "$3" "$PTTYPE")
1289[ -n "$ID" ] || ogRaiseError $OG_ERR_FORMAT "$3,$PTTYPE" || return $?
1290ogSetPartitionId $1 $2 $ID
1291}
1292
1293
1294#/**
1295#         ogTypeToId str_parttype [str_tabletype]
1296#@brief   Devuelve el identificador correspondiente a un tipo de partición.
1297#@param   str_parttype  mnemónico de tipo de partición.
1298#@param   str_tabletype mnemónico de tipo de tabla de particiones (MSDOS por defecto).
1299#@return  int_idpart    identificador de tipo de partición.
1300#@exception OG_ERR_FORMAT   Formato incorrecto.
1301#@note    tabletype = { MSDOS, GPT },   (MSDOS, por defecto)
1302#@version 0.1 -  Integracion para Opengnsys  -  EAC: TypeFS () en ATA.lib
1303#@author  Antonio J. Doblas Viso, Universidad de Malaga
1304#@date    2008/10/27
1305#@version 0.9 - Primera version para OpenGnSys
1306#@author  Ramon Gomez, ETSII Universidad Sevilla
1307#@date    2009-12-14
1308#@version 1.0.4 - Soportar discos GPT (sustituye a ogFsToId).
1309#@author  Universidad de Huelva
1310#@date    2012/03/30
1311#*/ ##
1312function ogTypeToId ()
1313{
1314# Variables locales
1315local PTTYPE ID
1316
1317# Si se solicita, mostrar ayuda.
1318if [ "$*" == "help" ]; then
1319    ogHelp "$FUNCNAME" "$FUNCNAME str_parttype [str_tabletype]" \
1320           "$FUNCNAME LINUX  =>  83" \
1321           "$FUNCNAME LINUX MSDOS  =>  83"
1322    return
1323fi
1324# Error si no se reciben 1 o 2 parámetros.
1325[ $# -lt 1 -o $# -gt 2 ] && (ogRaiseError $OG_ERR_FORMAT; return $?)
1326
1327# Asociar id. de partición para su mnemónico.
1328PTTYPE=${2:-"MSDOS"}
1329case "$PTTYPE" in
1330    GPT) # Se incluyen mnemónicos compatibles con tablas MSDOS.
1331        case "$1" in
1332            EMPTY)      ID=0 ;;
1333            WINDOWS|NTFS|EXFAT|FAT32|FAT16|FAT12|HNTFS|HFAT32|HFAT16|HFAT12)
1334                        ID=0700 ;;
1335            WIN-RESERV) ID=0C01 ;;
1336            CHROMEOS-KRN) ID=7F00 ;;
1337            CHROMEOS)   ID=7F01 ;;
1338            CHROMEOS-RESERV) ID=7F02 ;;
1339            LINUX-SWAP) ID=8200 ;;
1340            LINUX|EXT[234]|REISERFS|REISER4|XFS|JFS)
1341                        ID=8300 ;;
1342            LINUX-RESERV) ID=8301 ;;
1343            LINUX-LVM)  ID=8E00 ;;
1344            FREEBSD-DISK) ID=A500 ;;
1345            FREEBSD-BOOT) ID=A501 ;;
1346            FREEBSD-SWAP) ID=A502 ;;
1347            FREEBSD)    ID=A503 ;;
1348            HFS-BOOT)   ID=AB00 ;;
1349            HFS|HFS+)   ID=AF00 ;;
1350            HFSPLUS)    ID=AF00 ;;
1351            HFS-RAID)   ID=AF01 ;;
1352            SOLARIS-BOOT) ID=BE00 ;;
1353            SOLARIS)    ID=BF00 ;;
1354            SOLARIS-SWAP) ID=BF02 ;;
1355            SOLARIS-DISK) ID=BF03 ;;
1356            CACHE)      ID=CA00;;
1357            EFI)        ID=EF00 ;;
1358            LINUX-RAID) ID=FD00 ;;
1359            *)          ID="" ;;
1360        esac
1361        ;;
1362    MSDOS)
1363        case "$1" in
1364            EMPTY)      ID=0  ;;
1365            FAT12)      ID=1  ;;
1366            EXTENDED)   ID=5  ;;
1367            FAT16)      ID=6  ;;
1368            WINDOWS|NTFS|EXFAT)
1369                        ID=7  ;;
1370            FAT32)      ID=b  ;;
1371            HFAT12)     ID=11 ;;
1372            HFAT16)     ID=16 ;;
1373            HNTFS)      ID=17 ;;
1374            HFAT32)     ID=1b ;;
1375            LINUX-SWAP) ID=82 ;;
1376            LINUX|EXT[234]|REISERFS|REISER4|XFS|JFS)
1377                        ID=83 ;;
1378            LINUX-LVM)  ID=8e ;;
1379            FREEBSD)    ID=a5 ;;
1380            OPENBSD)    ID=a6 ;;
1381            HFS|HFS+)   ID=af ;;
1382            SOLARIS-BOOT) ID=be ;;
1383            SOLARIS)    ID=bf ;;
1384            CACHE)      ID=ca ;;
1385            DATA)       ID=da ;;
1386            GPT)        ID=ee ;;
1387            EFI)        ID=ef ;;
1388            VMFS)       ID=fb ;;
1389            LINUX-RAID) ID=fd ;;
1390            *)          ID="" ;;
1391        esac
1392        ;;
1393esac
1394echo $ID
1395}
1396
1397
1398#/**
1399#         ogUnhidePartition int_ndisk int_npartition
1400#@brief   Hace visible una partición oculta.
1401#@param   int_ndisk      nº de orden del disco
1402#@param   int_npartition nº de orden de la partición
1403#@return  (nada)
1404#@exception OG_ERR_FORMAT    formato incorrecto.
1405#@exception OG_ERR_NOTFOUND  disco o particion no detectado (no es un dispositivo).
1406#@exception OG_ERR_PARTITION tipo de partición no reconocido.
1407#@version 1.0 - Versión en pruebas.
1408#@author  Ramon Gomez, ETSII Universidad de Sevilla
1409#@date    2010/01/12
1410#*/ ##
1411function ogUnhidePartition ()
1412{
1413# Variables locales.
1414local PART TYPE NEWTYPE
1415# Si se solicita, mostrar ayuda.
1416if [ "$*" == "help" ]; then
1417    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1418           "$FUNCNAME 1 1"
1419    return
1420fi
1421# Error si no se reciben 2 parámetros.
1422[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1423PART=$(ogDiskToDev "$1" "$2") || return $?
1424
1425# Obtener tipo de partición.
1426TYPE=$(ogGetPartitionType "$1" "$2")
1427case "$TYPE" in
1428    HNTFS)   NEWTYPE="NTFS"  ;;
1429    HFAT32)  NEWTYPE="FAT32" ;;
1430    HFAT16)  NEWTYPE="FAT16" ;;
1431    HFAT12)  NEWTYPE="FAT12" ;;
1432    *)      ogRaiseError $OG_ERR_PARTITION "$TYPE"
1433            return $? ;;
1434esac
1435# Cambiar tipo de partición.
1436ogSetPartitionType $1 $2 $NEWTYPE
1437}
1438
1439
1440#/**
1441#         ogUpdatePartitionTable
1442#@brief   Fuerza al kernel releer la tabla de particiones de los discos duros
1443#@param   no requiere
1444#@return  informacion propia de la herramienta
1445#@note    Requisitos: \c partprobe
1446#@warning pendiente estructurar la funcion a opengnsys
1447#@version 0.1 -  Integracion para Opengnsys  -  EAC: UpdatePartitionTable() en ATA.lib
1448#@author  Antonio J. Doblas Viso. Universidad de Malaga
1449#@date    27/10/2008
1450#*/ ##
1451function ogUpdatePartitionTable ()
1452{
1453local i
1454for i in `ogDiskToDev`
1455do
1456        partprobe $i
1457done
1458}
1459
1460
1461#/**  @function ogDiskToRelativeDev: @brief Traduce los ID de discos o particiones EAC a ID Linux relativos, es decir 1 1 => sda1
1462#@param  Admite 1 parametro:   $1  int_numdisk
1463#@param  Admite 2 parametro:   $1   int_numdisk                    $2  int_partition
1464#@return  Para 1 parametros traduce Discos Duros: Devuelve la ruta relativa linux del disco duro indicado con nomenclatura EAC.........ejemplo: IdPartition 1 => sda
1465#@return  Para 2 parametros traduce Particiones: Devuelve la ruta relativa linux de la particion indicado con nomenclatura EAC...........  ejemplo: IdPartition  2 1 => sdb1
1466#@warning  No definidas
1467#@attention
1468#@note    Notas sin especificar
1469#@version 0.1 -  Integracion para Opengnsys  -  EAC:  IdPartition en ATA.lib
1470#@author  Antonio J. Doblas Viso. Universidad de Malaga
1471#@date    27/10/2008
1472#*/
1473function ogDiskToRelativeDev () {
1474if [ $# = 0 ]
1475then
1476        Msg "Info: Traduce el identificador del dispositivo EAC a dispositivo linux \n" info
1477        Msg "Sintaxis1: IdPartition int_disk -----------------Ejemplo1: IdPartition 1 -> sda " example
1478        Msg "Sintaxis2: IdPartition int_disk int_partition  --Ejemplo2: IdPartition 1 2 -> sda2 " example
1479
1480return
1481fi
1482#PART="$(Disk|cut -f$1 -d' ')$2"    # se comenta esta linea porque doxygen no reconoce la funcion disk y no crea los enlaces y referencias correctas.
1483PART=$(ogDiskToDev|cut -f$1 -d' ')$2
1484echo $PART | cut -f3 -d \/
1485}
1486
1487
1488#/**  @function ogDeletePartitionsLabels: @brief Elimina la informacion que tiene el kernel del cliente og sobre los labels de los sistemas de archivos
1489#@param  No requiere
1490#@return   Nada
1491#@warning
1492#@attention Requisitos:  comando interno linux rm
1493#@note
1494#@version 0.1 -  Integracion para Opengnsys  -  EAC:   DeletePartitionTable()  en ATA.lib
1495#@author  Antonio J. Doblas Viso. Universidad de Malaga
1496#@date    27/10/2008
1497#*/
1498function ogDeletePartitionsLabels () {
1499# Si se solicita, mostrar ayuda.
1500if [ "$*" == "help" ]; then
1501    ogHelp "$FUNCNAME" "$FUNCNAME " \
1502           "$FUNCNAME "
1503    return
1504fi
1505
1506rm /dev/disk/by-label/*    # */ COMENTARIO OBLIGATORIO PARA DOXYGEN
1507}
1508
Note: See TracBrowser for help on using the repository browser.