source: client/engine/Disk.lib @ 55fcaa6

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 55fcaa6 was 9eaa464, checked in by ramon <ramongomez@…>, 7 years ago

#830: Integrar cambios de ticket:830.

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

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