source: client/engine/Disk.lib @ 900be258

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 900be258 was 0d6e7222, checked in by ramon <ramongomez@…>, 10 years ago

#676: Integrar código desarrollado para el ticket:676 en rama de versión 1.1.

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

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