source: client/engine/Disk.lib @ 89cb5a5

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 89cb5a5 was 9ca55ab, checked in by ramon <ramongomez@…>, 9 years ago

#676: Activar automáticamente módulo para ZFS; detección correcta de ZPOOL y mostrar datos en tabla de configuración.

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

  • Property mode set to 100755
File size: 50.2 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 $?
686LANG=C parted -sm $DISK print 2>/dev/null | awk -F: '$7~/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 list &>/dev/null || modprobe zfs
830            zpool import -f -R /mnt -N -a 2>/dev/null
831            zfs list -Hp -o name,canmount,mountpoint -r $(blkid -s LABEL -o value $DISK) | \
832                    awk '$2=="on" && $3!="none" {c++}
833                         END {print c}'
834            ;;
835esac
836}
837
838
839#/**
840#         ogGetPartitionTableType int_ndisk
841#@brief   Devuelve el tipo de tabla de particiones del disco (GPT o MSDOS)
842#@param   int_ndisk       nº de orden del disco
843#@return  str_tabletype - Tipo de tabla de paritiones
844#@warning Salidas de errores no determinada
845#@note    tabletype = { MSDOS, GPT }
846#@note    Requisitos: parted
847#@version 1.0.4 - Primera versión para OpenGnSys
848#@author  Universidad de Huelva
849#@date    2012/03/01
850#@version 1.0.6 - Soportar LVM.
851#@author  Universidad de Huelva
852#@date    2014-09-04
853#@version 1.1.0 - Soportar ZFS.
854#@author  Ramon Gomez, ETSII Universidad Sevilla
855#@date    2014-11-14
856#*/ ##
857function ogGetPartitionTableType ()
858{
859# Variables locales.
860local DISK TYPE
861
862# Si se solicita, mostrar ayuda.
863if [ "$*" == "help" ]; then
864    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
865           "$FUNCNAME 1  =>  MSDOS"
866    return
867fi
868# Error si no se recibe 1 parámetro.
869[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
870
871# Sustituye n de disco por su dispositivo.
872DISK=$(ogDiskToDev $1) || return $?
873
874# Comprobar tabla de particiones.
875[ -b $DISK ] && TYPE=$(parted -sm $DISK print 2>/dev/null | awk -F: -v D=$DISK '{ if($1 == D) print toupper($6)}')
876# Comprobar si es volumen lógico.
877[ -d $DISK ] && vgs $DISK &>/dev/null && TYPE="LVM"
878# Comprobar si es pool de ZFS.
879[ -z "$TYPE" -o "$TYPE" == "UNKNOWN" ] && [ -n "$(blkid -s TYPE $DISK | grep zfs)" ] && TYPE="ZPOOL"
880
881# Mostrar salida.
882[ -n "$TYPE" ] && echo "$TYPE"
883}
884
885
886#/**
887#         ogGetPartitionType int_ndisk int_npartition
888#@brief   Devuelve el mnemonico con el tipo de partición.
889#@param   int_ndisk      nº de orden del disco
890#@param   int_npartition nº de orden de la partición
891#@return  Mnemonico
892#@note    Mnemonico: valor devuelto por ogIdToType.
893#@exception OG_ERR_FORMAT   Formato incorrecto.
894#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
895#@version 0.1 -  Integracion para Opengnsys  -  EAC:   TypeFS() en ATA.lib
896#@author  Antonio J. Doblas Viso. Universidad de Malaga
897#@date    2008-10-27
898#@version 0.9 - Primera adaptacion para OpenGnSys.
899#@author  Ramon Gomez, ETSII Universidad de Sevilla
900#@date    2009-07-21
901#@version 1.0.3 - Código trasladado de antigua función ogGetFsType.
902#@author  Ramon Gomez, ETSII Universidad de Sevilla
903#@date    2011-12-01
904#@version 1.0.5 - Usar función ogIdToType para hacer la conversión id. a tipo.
905#@author  Ramon Gomez, ETSII Universidad de Sevilla
906#@date    2013-09-19
907#*/ ##
908function ogGetPartitionType ()
909{
910# Variables locales.
911local ID TYPE
912
913# Si se solicita, mostrar ayuda.
914if [ "$*" == "help" ]; then
915    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
916           "$FUNCNAME 1 1  =>  NTFS"
917    return
918fi
919# Error si no se reciben 2 parámetros.
920[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
921
922# Detectar id. de tipo de partición y codificar al mnemonico.
923ID=$(ogGetPartitionId "$1" "$2") || return $?
924TYPE=$(ogIdToType "$ID")
925echo "$TYPE"
926}
927
928
929#/**
930#         ogHidePartition int_ndisk int_npartition
931#@brief   Oculta un apartición visible.
932#@param   int_ndisk      nº de orden del disco
933#@param   int_npartition nº de orden de la partición
934#@return  (nada)
935#@exception OG_ERR_FORMAT    formato incorrecto.
936#@exception OG_ERR_NOTFOUND  disco o particion no detectado (no es un dispositivo).
937#@exception OG_ERR_PARTITION tipo de partición no reconocido.
938#@version 1.0 - Versión en pruebas.
939#@author  Ramon Gomez, ETSII Universidad de Sevilla
940#@date    2010/01/12
941#*/ ##
942function ogHidePartition ()
943{
944# Variables locales.
945local PART TYPE NEWTYPE
946# Si se solicita, mostrar ayuda.
947if [ "$*" == "help" ]; then
948    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
949           "$FUNCNAME 1 1"
950    return
951fi
952# Error si no se reciben 2 parámetros.
953[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
954PART=$(ogDiskToDev "$1" "$2") || return $?
955
956# Obtener tipo de partición.
957TYPE=$(ogGetPartitionType "$1" "$2")
958case "$TYPE" in
959    NTFS)   NEWTYPE="HNTFS"  ;;
960    FAT32)  NEWTYPE="HFAT32" ;;
961    FAT16)  NEWTYPE="HFAT16" ;;
962    FAT12)  NEWTYPE="HFAT12" ;;
963    *)      ogRaiseError $OG_ERR_PARTITION "$TYPE"
964            return $? ;;
965esac
966# Cambiar tipo de partición.
967ogSetPartitionType $1 $2 $NEWTYPE
968}
969
970
971#/**
972#         ogIdToType int_idpart
973#@brief   Devuelve el identificador correspondiente a un tipo de partición.
974#@param   int_idpart    identificador de tipo de partición.
975#@return  str_parttype  mnemónico de tipo de partición.
976#@exception OG_ERR_FORMAT   Formato incorrecto.
977#@version 1.0.5 - Primera version para OpenGnSys
978#@author  Ramon Gomez, ETSII Universidad Sevilla
979#@date    2013-02-07
980#*/ ##
981function ogIdToType ()
982{
983# Variables locales
984local ID TYPE
985
986# Si se solicita, mostrar ayuda.
987if [ "$*" == "help" ]; then
988    ogHelp "$FUNCNAME" "$FUNCNAME int_idpart" \
989           "$FUNCNAME 83  =>  LINUX"
990    return
991fi
992# Error si no se recibe 1 parámetro.
993[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
994
995# Obtener valor hexadecimal de 4 caracteres rellenado con 0 por delante.
996ID=$(printf "%4s" "$1" | tr ' ' '0')
997case "${ID,,}" in
998     0000)      TYPE="EMPTY" ;;
999     0001)      TYPE="FAT12" ;;
1000     0005|000f) TYPE="EXTENDED" ;;
1001     0006|000e) TYPE="FAT16" ;;
1002     0007)      TYPE="NTFS" ;;
1003     000b|000c) TYPE="FAT32" ;;
1004     0011)      TYPE="HFAT12" ;;
1005     0012)      TYPE="COMPAQDIAG" ;;
1006     0016|001e) TYPE="HFAT16" ;;
1007     0017)      TYPE="HNTFS" ;;
1008     001b|001c) TYPE="HFAT32" ;;
1009     0042)      TYPE="WIN-DYNAMIC" ;;
1010     0082|8200) TYPE="LINUX-SWAP" ;;
1011     0083|8300) TYPE="LINUX" ;;
1012     008e|8E00) TYPE="LINUX-LVM" ;;
1013     00a5|a503) TYPE="FREEBSD" ;;
1014     00a6)      TYPE="OPENBSD" ;;
1015     00a7)      TYPE="CACHE" ;;         # (compatibilidad con Brutalix)
1016     00af|af00) TYPE="HFS" ;;
1017     00be|be00) TYPE="SOLARIS-BOOT" ;;
1018     00bf|bf0[0145]) TYPE="SOLARIS" ;;
1019     00ca|ca00) TYPE="CACHE" ;;
1020     00da)      TYPE="DATA" ;;
1021     00ee)      TYPE="GPT" ;;
1022     00ef|ef00) TYPE="EFI" ;;
1023     00fb)      TYPE="VMFS" ;;
1024     00fd|fd00) TYPE="LINUX-RAID" ;;
1025     0700)      TYPE="WINDOWS" ;;
1026     0c01)      TYPE="WIN-RESERV" ;;
1027     7f00)      TYPE="CHROMEOS-KRN" ;;
1028     7f01)      TYPE="CHROMEOS" ;;
1029     7f02)      TYPE="CHROMEOS-RESERV" ;;
1030     8301)      TYPE="LINUX-RESERV" ;;
1031     a500)      TYPE="FREEBSD-DISK" ;;
1032     a501)      TYPE="FREEBSD-BOOT" ;;
1033     a502)      TYPE="FREEBSD-SWAP" ;;
1034     ab00)      TYPE="HFS-BOOT" ;;
1035     af01)      TYPE="HFS-RAID" ;;
1036     bf02)      TYPE="SOLARIS-SWAP" ;;
1037     bf03)      TYPE="SOLARIS-DISK" ;;
1038     ef01)      TYPE="MBR" ;;
1039     ef02)      TYPE="BIOS-BOOT" ;;
1040     *)         TYPE="UNKNOWN" ;;
1041esac
1042echo "$TYPE"
1043}
1044
1045
1046#/**
1047#         ogListPartitions int_ndisk
1048#@brief   Lista las particiones definidas en un disco.
1049#@param   int_ndisk  nº de orden del disco
1050#@return  str_parttype:int_partsize ...
1051#@exception OG_ERR_FORMAT   formato incorrecto.
1052#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
1053#@note    Requisitos: \c parted \c awk
1054#@attention El nº de partición se indica por el orden de los párametros \c parttype:partsize
1055#@attention Las tuplas de valores están separadas por espacios.
1056#@version 0.9 - Primera versión para OpenGnSys
1057#@author  Ramon Gomez, ETSII Universidad de Sevilla
1058#@date    2009/07/24
1059#*/ ##
1060function ogListPartitions ()
1061{
1062# Variables locales.
1063local DISK PART NPARTS TYPE SIZE
1064
1065# Si se solicita, mostrar ayuda.
1066if [ "$*" == "help" ]; then
1067    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
1068           "$FUNCNAME 1  =>  NTFS:10000000 EXT3:5000000 LINUX-SWAP:1000000"
1069    return
1070fi
1071# Error si no se recibe 1 parámetro.
1072[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT "$FORMAT" || return $?
1073
1074# Procesar la salida de \c parted .
1075DISK="$(ogDiskToDev $1)" || return $?
1076NPARTS=$(ogGetPartitionsNumber $1)
1077for (( PART = 1; PART <= NPARTS; PART++ )); do
1078    TYPE=$(ogGetPartitionType $1 $PART 2>/dev/null)
1079    if [ $? -eq 0 ]; then
1080        SIZE=$(ogGetPartitionSize $1 $PART 2>/dev/null)
1081        echo -n "$TYPE:$SIZE "
1082    else
1083        echo -n "EMPTY:0 "
1084    fi
1085done
1086echo
1087}
1088
1089
1090#/**
1091#         ogListPrimaryPartitions int_ndisk
1092#@brief   Metafunción que lista las particiones primarias no vacías de un disco.
1093#@param   int_ndisk  nº de orden del disco
1094#@see     ogListPartitions
1095#*/ ##
1096function ogListPrimaryPartitions ()
1097{
1098# Variables locales.
1099local PTTYPE PARTS
1100
1101PTTYPE=$(ogGetPartitionTableType $1) || return $?
1102PARTS=$(ogListPartitions "$@") || return $?
1103case "$PTTYPE" in
1104    GPT)    echo $PARTS | sed 's/\( EMPTY:0\)*$//' ;;
1105    MSDOS)  echo $PARTS | cut -sf1-4 -d" " | sed 's/\( EMPTY:0\)*$//' ;;
1106esac
1107}
1108
1109
1110#/**
1111#         ogListLogicalPartitions int_ndisk
1112#@brief   Metafunción que lista las particiones lógicas de una tabla tipo MSDOS.
1113#@param   int_ndisk  nº de orden del disco
1114#@see     ogListPartitions
1115#*/ ##
1116function ogListLogicalPartitions ()
1117{
1118# Variables locales.
1119local PTTYPE PARTS
1120
1121PTTYPE=$(ogGetPartitionTableType $1) || return $?
1122[ "$PTTYPE" == "MSDOS" ] || ogRaiseError $OG_ERR_PARTITION "" || return $?
1123PARTS=$(ogListPartitions "$@") || return $?
1124echo $PARTS | cut -sf5- -d" "
1125}
1126
1127
1128#/**
1129#         ogSetPartitionActive int_ndisk int_npartition
1130#@brief   Establece cual es la partición activa de un disco.
1131#@param   int_ndisk      nº de orden del disco
1132#@param   int_npartition nº de orden de la partición
1133#@return  (nada).
1134#@exception OG_ERR_FORMAT   Formato incorrecto.
1135#@exception OG_ERR_NOTFOUND Disco o partición no corresponden con un dispositivo.
1136#@note    Requisitos: parted
1137#@version 0.1 -  Integracion para Opengnsys  -  EAC: SetPartitionActive() en ATA.lib
1138#@author  Antonio J. Doblas Viso, Universidad de Malaga
1139#@date    2008/10/27
1140#@version 0.9 - Primera version compatible con OpenGnSys.
1141#@author  Ramon Gomez, ETSII Universidad de Sevilla
1142#@date    2009/09/17
1143#*/ ##
1144function ogSetPartitionActive ()
1145{
1146# Variables locales
1147local DISK PART
1148
1149# Si se solicita, mostrar ayuda.
1150if [ "$*" == "help" ]; then
1151    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1152           "$FUNCNAME 1 1"
1153    return
1154fi
1155# Error si no se reciben 2 parámetros.
1156[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1157
1158# Comprobar que el disco existe y activar la partición indicada.
1159DISK="$(ogDiskToDev $1)" || return $?
1160PART="$(ogDiskToDev $1 $2)" || return $?
1161parted -s $DISK set $2 boot on 2>/dev/null
1162}
1163
1164
1165#/**
1166#         ogSetPartitionId int_ndisk int_npartition hex_partid
1167#@brief   Cambia el identificador de la partición.
1168#@param   int_ndisk      nº de orden del disco
1169#@param   int_npartition nº de orden de la partición
1170#@param   hex_partid     identificador de tipo de partición
1171#@return  (nada)
1172#@exception OG_ERR_FORMAT     Formato incorrecto.
1173#@exception OG_ERR_NOTFOUND   Disco o partición no corresponden con un dispositivo.
1174#@exception OG_ERR_OUTOFLIMIT Valor no válido.
1175#@exception OG_ERR_PARTITION  Error al cambiar el id. de partición.
1176#@attention Requisitos: fdisk, sgdisk
1177#@version 0.1 -  Integracion para Opengnsys  - SetPartitionType() en ATA.lib
1178#@author  Antonio J. Doblas Viso. Universidad de Malaga
1179#@date    2008/10/27
1180#@version 1.0.4 - Soporte para discos GPT.
1181#@author  Universidad de Huelva
1182#@date    2012/03/13
1183#@version 1.0.5 - Utiliza el id. de tipo de partición (no el mnemónico)
1184#@author  Universidad de Huelva
1185#@date    2012/05/14
1186#*/ ##
1187function ogSetPartitionId ()
1188{
1189# Variables locales
1190local DISK PART PTTYPE ID
1191
1192# Si se solicita, mostrar ayuda.
1193if [ "$*" == "help" ]; then
1194    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition hex_partid" \
1195           "$FUNCNAME 1 1 7"
1196    return
1197fi
1198# Error si no se reciben 3 parámetros.
1199[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1200
1201# Sustituye nº de disco y nº partición por su dispositivo.
1202DISK=$(ogDiskToDev $1) || return $?
1203PART=$(ogDiskToDev $1 $2) || return $?
1204# Error si el id. de partición no es hexadecimal.
1205ID="${3^^}"
1206[[ "$ID" =~ ^[0-9A-F]+$ ]] || ogRaiseError $OG_ERR_OUTOFLIMIT "$3" || return $?
1207
1208# Elección del tipo de partición.
1209PTTYPE=$(ogGetPartitionTableType $1)
1210case "$PTTYPE" in
1211    GPT)    sgdisk -t$2:$ID $DISK 2>/dev/null ;;
1212    MSDOS)  echo -ne "t\n$2\n${ID}\nw\n" | fdisk $DISK | grep Syncing &>/dev/null ;;
1213    *)      ogRaiseError $OG_ERR_OUTOFLIMIT "$1,$PTTYPE"
1214            return $? ;;
1215esac
1216
1217# MSDOS) Correcto si fdisk sin error o con error pero realiza Syncing
1218if [ "${PIPESTATUS[1]}" == "0" -o $? -eq 0 ]; then
1219    partprobe $DISK 2>/dev/null
1220    return 0
1221else
1222    ogRaiseError $OG_ERR_PARTITION "$1,$2,$3"
1223    return $?
1224fi
1225}
1226
1227
1228#/**
1229#         ogSetPartitionSize int_ndisk int_npartition int_size
1230#@brief   Muestra el tamano en KB de una particion determinada.
1231#@param   int_ndisk      nº de orden del disco
1232#@param   int_npartition nº de orden de la partición
1233#@param   int_size       tamaño de la partición (en KB)
1234#@return  (nada)
1235#@exception OG_ERR_FORMAT   formato incorrecto.
1236#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
1237#@note    Requisitos: sfdisk, awk
1238#@todo    Compruebar que el tamaño sea numérico positivo y evitar que pueda solaparse con la siguiente partición.
1239#@version 0.9 - Primera versión para OpenGnSys
1240#@author  Ramon Gomez, ETSII Universidad de Sevilla
1241#@date    2009/07/24
1242#*/ ##
1243function ogSetPartitionSize ()
1244{
1245# Variables locales.
1246local DISK PART SIZE
1247
1248# Si se solicita, mostrar ayuda.
1249if [ "$*" == "help" ]; then
1250    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_size" \
1251           "$FUNCNAME 1 1 10000000"
1252    return
1253fi
1254# Error si no se reciben 3 parámetros.
1255[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1256
1257# Obtener el tamaño de la partición.
1258DISK="$(ogDiskToDev $1)" || return $?
1259PART="$(ogDiskToDev $1 $2)" || return $?
1260# Convertir tamaño en KB a sectores de 512 B.
1261SIZE=$[$3*2] || ogRaiseError $OG_ERR_FORMAT || return $?
1262# Redefinir el tamaño de la partición.
1263sfdisk -f -uS -N$2 $DISK <<< ",$SIZE" &>/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
1264partprobe $DISK 2>/dev/null
1265}
1266
1267
1268#/**
1269#         ogSetPartitionType int_ndisk int_npartition str_type
1270#@brief   Cambia el identificador de la partición.
1271#@param   int_ndisk      nº de orden del disco
1272#@param   int_npartition nº de orden de la partición
1273#@param   str_type       mnemónico de tipo de partición
1274#@return  (nada)
1275#@attention Requisitos: fdisk, sgdisk
1276#@version 0.1 -  Integracion para Opengnsys  - SetPartitionType() en ATA.lib
1277#@author  Antonio J. Doblas Viso. Universidad de Malaga
1278#@date    2008/10/27
1279#@version 1.0.4 - Soporte para discos GPT.
1280#@author  Universidad de Huelva
1281#@date    2012/03/13
1282#@version 1.0.5 - Renombrada de ogSetPartitionId.
1283#@author  Ramon Gomez, ETSII Universidad de Sevilla
1284#@date    2013/03/07
1285#*/ ##
1286function ogSetPartitionType ()
1287{
1288# Variables locales
1289local DISK PART PTTYPE ID
1290
1291# Si se solicita, mostrar ayuda.
1292if [ "$*" == "help" ]; then
1293    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition str_type" \
1294           "$FUNCNAME 1 1 NTFS"
1295    return
1296fi
1297# Error si no se reciben 3 parámetros.
1298[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1299
1300# Sustituye nº de disco por su dispositivo.
1301DISK=`ogDiskToDev $1` || return $?
1302PART=`ogDiskToDev $1 $2` || return $?
1303
1304# Elección del tipo de partición.
1305PTTYPE=$(ogGetPartitionTableType $1)
1306ID=$(ogTypeToId "$3" "$PTTYPE")
1307[ -n "$ID" ] || ogRaiseError $OG_ERR_FORMAT "$3,$PTTYPE" || return $?
1308ogSetPartitionId $1 $2 $ID
1309}
1310
1311
1312#/**
1313#         ogTypeToId str_parttype [str_tabletype]
1314#@brief   Devuelve el identificador correspondiente a un tipo de partición.
1315#@param   str_parttype  mnemónico de tipo de partición.
1316#@param   str_tabletype mnemónico de tipo de tabla de particiones (MSDOS por defecto).
1317#@return  int_idpart    identificador de tipo de partición.
1318#@exception OG_ERR_FORMAT   Formato incorrecto.
1319#@note    tabletype = { MSDOS, GPT },   (MSDOS, por defecto)
1320#@version 0.1 -  Integracion para Opengnsys  -  EAC: TypeFS () en ATA.lib
1321#@author  Antonio J. Doblas Viso, Universidad de Malaga
1322#@date    2008/10/27
1323#@version 0.9 - Primera version para OpenGnSys
1324#@author  Ramon Gomez, ETSII Universidad Sevilla
1325#@date    2009-12-14
1326#@version 1.0.4 - Soportar discos GPT (sustituye a ogFsToId).
1327#@author  Universidad de Huelva
1328#@date    2012/03/30
1329#*/ ##
1330function ogTypeToId ()
1331{
1332# Variables locales
1333local PTTYPE ID
1334
1335# Si se solicita, mostrar ayuda.
1336if [ "$*" == "help" ]; then
1337    ogHelp "$FUNCNAME" "$FUNCNAME str_parttype [str_tabletype]" \
1338           "$FUNCNAME LINUX  =>  83" \
1339           "$FUNCNAME LINUX MSDOS  =>  83"
1340    return
1341fi
1342# Error si no se reciben 1 o 2 parámetros.
1343[ $# -lt 1 -o $# -gt 2 ] && (ogRaiseError $OG_ERR_FORMAT; return $?)
1344
1345# Asociar id. de partición para su mnemónico.
1346PTTYPE=${2:-"MSDOS"}
1347case "$PTTYPE" in
1348    GPT) # Se incluyen mnemónicos compatibles con tablas MSDOS.
1349        case "$1" in
1350            EMPTY)      ID=0 ;;
1351            WINDOWS|NTFS|EXFAT|FAT32|FAT16|FAT12|HNTFS|HFAT32|HFAT16|HFAT12)
1352                        ID=0700 ;;
1353            WIN-RESERV) ID=0C01 ;;
1354            CHROMEOS-KRN) ID=7F00 ;;
1355            CHROMEOS)   ID=7F01 ;;
1356            CHROMEOS-RESERV) ID=7F02 ;;
1357            LINUX-SWAP) ID=8200 ;;
1358            LINUX|EXT[234]|REISERFS|REISER4|XFS|JFS)
1359                        ID=8300 ;;
1360            LINUX-RESERV) ID=8301 ;;
1361            LINUX-LVM)  ID=8E00 ;;
1362            FREEBSD-DISK) ID=A500 ;;
1363            FREEBSD-BOOT) ID=A501 ;;
1364            FREEBSD-SWAP) ID=A502 ;;
1365            FREEBSD)    ID=A503 ;;
1366            HFS-BOOT)   ID=AB00 ;;
1367            HFS|HFS+)   ID=AF00 ;;
1368            HFSPLUS)    ID=AF00 ;;
1369            HFS-RAID)   ID=AF01 ;;
1370            SOLARIS-BOOT) ID=BE00 ;;
1371            SOLARIS)    ID=BF00 ;;
1372            SOLARIS-SWAP) ID=BF02 ;;
1373            SOLARIS-DISK) ID=BF03 ;;
1374            CACHE)      ID=CA00;;
1375            EFI)        ID=EF00 ;;
1376            LINUX-RAID) ID=FD00 ;;
1377            *)          ID="" ;;
1378        esac
1379        ;;
1380    MSDOS)
1381        case "$1" in
1382            EMPTY)      ID=0  ;;
1383            FAT12)      ID=1  ;;
1384            EXTENDED)   ID=5  ;;
1385            FAT16)      ID=6  ;;
1386            WINDOWS|NTFS|EXFAT)
1387                        ID=7  ;;
1388            FAT32)      ID=b  ;;
1389            HFAT12)     ID=11 ;;
1390            HFAT16)     ID=16 ;;
1391            HNTFS)      ID=17 ;;
1392            HFAT32)     ID=1b ;;
1393            LINUX-SWAP) ID=82 ;;
1394            LINUX|EXT[234]|REISERFS|REISER4|XFS|JFS)
1395                        ID=83 ;;
1396            LINUX-LVM)  ID=8e ;;
1397            FREEBSD)    ID=a5 ;;
1398            OPENBSD)    ID=a6 ;;
1399            HFS|HFS+)   ID=af ;;
1400            SOLARIS-BOOT) ID=be ;;
1401            SOLARIS)    ID=bf ;;
1402            CACHE)      ID=ca ;;
1403            DATA)       ID=da ;;
1404            GPT)        ID=ee ;;
1405            EFI)        ID=ef ;;
1406            VMFS)       ID=fb ;;
1407            LINUX-RAID) ID=fd ;;
1408            *)          ID="" ;;
1409        esac
1410        ;;
1411esac
1412echo $ID
1413}
1414
1415
1416#/**
1417#         ogUnhidePartition int_ndisk int_npartition
1418#@brief   Hace visible una partición oculta.
1419#@param   int_ndisk      nº de orden del disco
1420#@param   int_npartition nº de orden de la partición
1421#@return  (nada)
1422#@exception OG_ERR_FORMAT    formato incorrecto.
1423#@exception OG_ERR_NOTFOUND  disco o particion no detectado (no es un dispositivo).
1424#@exception OG_ERR_PARTITION tipo de partición no reconocido.
1425#@version 1.0 - Versión en pruebas.
1426#@author  Ramon Gomez, ETSII Universidad de Sevilla
1427#@date    2010/01/12
1428#*/ ##
1429function ogUnhidePartition ()
1430{
1431# Variables locales.
1432local PART TYPE NEWTYPE
1433# Si se solicita, mostrar ayuda.
1434if [ "$*" == "help" ]; then
1435    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1436           "$FUNCNAME 1 1"
1437    return
1438fi
1439# Error si no se reciben 2 parámetros.
1440[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1441PART=$(ogDiskToDev "$1" "$2") || return $?
1442
1443# Obtener tipo de partición.
1444TYPE=$(ogGetPartitionType "$1" "$2")
1445case "$TYPE" in
1446    HNTFS)   NEWTYPE="NTFS"  ;;
1447    HFAT32)  NEWTYPE="FAT32" ;;
1448    HFAT16)  NEWTYPE="FAT16" ;;
1449    HFAT12)  NEWTYPE="FAT12" ;;
1450    *)      ogRaiseError $OG_ERR_PARTITION "$TYPE"
1451            return $? ;;
1452esac
1453# Cambiar tipo de partición.
1454ogSetPartitionType $1 $2 $NEWTYPE
1455}
1456
1457
1458#/**
1459#         ogUpdatePartitionTable
1460#@brief   Fuerza al kernel releer la tabla de particiones de los discos duros
1461#@param   no requiere
1462#@return  informacion propia de la herramienta
1463#@note    Requisitos: \c partprobe
1464#@warning pendiente estructurar la funcion a opengnsys
1465#@version 0.1 -  Integracion para Opengnsys  -  EAC: UpdatePartitionTable() en ATA.lib
1466#@author  Antonio J. Doblas Viso. Universidad de Malaga
1467#@date    27/10/2008
1468#*/ ##
1469function ogUpdatePartitionTable ()
1470{
1471local i
1472for i in `ogDiskToDev`
1473do
1474        partprobe $i
1475done
1476}
Note: See TracBrowser for help on using the repository browser.