source: client/engine/Disk.lib @ a37e5fc4

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

#830: Ayuda y control de errores en función ogGetDiskType.

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

  • Property mode set to 100755
File size: 56.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#@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, USB, etc.).
622#@param   path_device  Dispositivo
623#@exception OG_ERR_FORMAT   formato incorrecto.
624#@exception OG_ERR_NOTFOUND disco no detectado o no es un dispositivo de bloques.
625#@note    Requisitos: udevadm
626#@version 1.1.1 - Primera version para OpenGnsys
627#@author  Ramon Gomez, ETSII Universidad de Sevilla
628#@date    2018-02-27
629#*/ ##
630function ogGetDiskType ()
631{
632# Variables locales
633local DEV MAJOR TYPE
634
635# Si se solicita, mostrar ayuda.
636if [ "$*" == "help" ]; then
637    ogHelp "$FUNCNAME" "$FUNCNAME path_device" \
638           "$FUNCNAME /dev/sdb  =>  USB"
639    return
640fi
641# Error si no se recibe 1 parámetro.
642[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
643
644# Obtener el driver del dispositivo de bloques.
645[ -b "$1" ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
646DEV=${1#/dev/}
647MAJOR=$(awk -v D="$DEV" '{if ($4==D) print $1;}' /proc/partitions)
648TYPE=$(awk -v D=$MAJOR '/Block/ {bl=1} {if ($1==D&&bl) print toupper($2)}' /proc/devices)
649# Devolver mnemónico del driver de dispositivo.
650case "$TYPE" in
651    SD)
652        TYPE="DISK"
653        udevadm info -q property $1 2>/dev/null | grep -q "^ID_BUS=usb" && TYPE="USB"
654        ;;
655    SR|IDE*)
656        TYPE="CDROM"        # FIXME Comprobar discos IDE.
657        ;;
658    MD|CCISS*)
659        TYPE="RAID"
660        ;;
661    DEVICE-MAPPER)
662        TYPE="MAPPER"       # FIXME Comprobar LVM y RAID.
663        ;;
664esac
665echo $TYPE
666}
667
668
669#/**
670#         ogGetLastSector int_ndisk [int_npart]
671#@brief   Devuelve el último sector usable del disco o de una partición.
672#@param   int_ndisk      nº de orden del disco
673#@param   int_npart      nº de orden de la partición (opcional)
674#@return  Último sector usable.
675#@exception OG_ERR_FORMAT   Formato incorrecto.
676#@exception OG_ERR_NOTFOUND Disco o partición no corresponde con un dispositivo.
677#@note    Requisitos: sfdisk, sgdisk
678#@version 1.0.4 - Primera versión compatible con OpenGnSys.
679#@author  Universidad de Huelva
680#@date    2012-06-03
681#@version 1.0.6b - uso de sgdisk para todo tipo de particiones. Incidencia #762
682#@author  Universidad de Málaga
683#@date    2016-11-10
684#*/ ##
685function ogGetLastSector ()
686{
687# Variables locales
688local DISK PART LASTSECTOR
689
690# Si se solicita, mostrar ayuda.
691if [ "$*" == "help" ]; then
692    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk [int_npart]" \
693           "$FUNCNAME 1  =>  488392064" \
694           "$FUNCNAME 1 1  =>  102400062"
695    return
696fi
697
698# Obtener último sector.
699case $# in
700    1)  # Para un disco.
701        DISK=$(ogDiskToDev $1) || return $?
702        LASTSECTOR=$(LANG=C sgdisk -p $DISK | awk '/last usable sector/ {print($(NF))}')
703        ;;
704    2)  # Para una partición.
705        DISK=$(ogDiskToDev $1) || return $?
706        PART=$(ogDiskToDev $1 $2) || return $?
707        LASTSECTOR=$(LANG=C sgdisk -p $DISK | awk -v P="$2" '{if ($1==P) print $3}')
708        ;;
709    *)  # Error si se reciben más parámetros.
710        ogRaiseError $OG_ERR_FORMAT
711        return $? ;;
712esac
713echo $LASTSECTOR
714}
715
716
717#/**
718#         ogGetPartitionActive int_ndisk
719#@brief   Muestra que particion de un disco esta marcada como de activa.
720#@param   int_ndisk   nº de orden del disco
721#@return  int_npart   Nº de partición activa
722#@exception OG_ERR_FORMAT Formato incorrecto.
723#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
724#@note    Requisitos: parted
725#@todo    Queda definir formato para atributos (arranque, oculta, ...).
726#@version 0.9 - Primera version compatible con OpenGnSys.
727#@author  Ramon Gomez, ETSII Universidad de Sevilla
728#@date    2009/09/17
729#*/ ##
730function ogGetPartitionActive ()
731{
732# Variables locales
733local DISK
734
735# Si se solicita, mostrar ayuda.
736if [ "$*" == "help" ]; then
737    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" "$FUNCNAME 1  =>  1"
738    return
739fi
740# Error si no se recibe 1 parámetro.
741[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
742
743# Comprobar que el disco existe y listar su partición activa.
744DISK="$(ogDiskToDev $1)" || return $?
745LANG=C parted -sm $DISK print 2>/dev/null | awk -F: '$7~/boot/ {print $1}'
746}
747
748
749#/**
750#         ogGetPartitionId int_ndisk int_npartition
751#@brief   Devuelve el mnemónico con el tipo de partición.
752#@param   int_ndisk      nº de orden del disco
753#@param   int_npartition nº de orden de la partición
754#@return  Identificador de tipo de partición.
755#@exception OG_ERR_FORMAT   Formato incorrecto.
756#@exception OG_ERR_NOTFOUND Disco o partición no corresponde con un dispositivo.
757#@note    Requisitos: sfdisk
758#@version 0.9 - Primera versión compatible con OpenGnSys.
759#@author  Ramon Gomez, ETSII Universidad de Sevilla
760#@date    2009-03-25
761#@version 1.0.2 - Detectar partición vacía.
762#@author  Ramon Gomez, ETSII Universidad de Sevilla
763#@date    2011-12-23
764#@version 1.0.6 - Soportar LVM.
765#@author  Universidad de Huelva
766#@date    2014-09-04
767#@version 1.1.0 - Soportar pool de volúmenes ZFS.
768#@author  Ramon Gomez, ETSII Universidad Sevilla
769#@date    2014-11-14
770#*/ ##
771function ogGetPartitionId ()
772{
773# Variables locales.
774local DISK ID
775
776# Si se solicita, mostrar ayuda.
777if [ "$*" == "help" ]; then
778    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
779           "$FUNCNAME 1 1  =>  7"
780    return
781fi
782# Error si no se reciben 2 parámetros.
783[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
784
785# Detectar y mostrar el id. de tipo de partición.
786DISK=$(ogDiskToDev $1) || return $?
787case "$(ogGetPartitionTableType $1)" in
788    GPT)    ID=$(sgdisk -p $DISK 2>/dev/null | awk -v p="$2" '{if ($1==p) print $6;}') || ogRaiseError $OG_ERR_NOTFOUND "$1,$2" || return $?
789            [ "$ID" == "8300" -a "$1 $2" == "$(ogFindCache)" ] && ID=CA00
790            ;;
791    MSDOS)  ID=$(sfdisk --id $DISK $2 2>/dev/null) || ogRaiseError $OG_ERR_NOTFOUND "$1,$2" || return $? ;;
792    LVM)    ID=10000 ;;
793    ZPOOL)  ID=10010 ;;
794esac
795echo $ID
796}
797
798
799#/**
800#         ogGetPartitionSize int_ndisk int_npartition
801#@brief   Muestra el tamano en KB de una particion determinada.
802#@param   int_ndisk      nº de orden del disco
803#@param   int_npartition nº de orden de la partición
804#@return  int_partsize - Tamaño en KB de la partición.
805#@exception OG_ERR_FORMAT   formato incorrecto.
806#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
807#@note    Requisitos: sfdisk, awk
808#@version 0.1 -  Integracion para Opengnsys  -  EAC: SizePartition () en ATA.lib
809#@author  Antonio J. Doblas Viso, Universidad de Malaga
810#@date    2008/10/27
811#@version 0.9 - Primera version para OpenGnSys
812#@author  Ramon Gomez, ETSII Universidad de Sevilla
813#@date    2009/07/24
814#@version 1.1.0 - Sustituir "sfdisk" por "partx".
815#@author  Ramon Gomez, ETSII Universidad de Sevilla
816#@date    2016/05/04
817#*/ ##
818function ogGetPartitionSize ()
819{
820# Variables locales.
821local PART SIZE
822
823# Si se solicita, mostrar ayuda.
824if [ "$*" == "help" ]; then
825    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
826           "$FUNCNAME 1 1  =>  10000000"
827    return
828fi
829# Error si no se reciben 2 parámetros.
830[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
831
832# Devolver tamaño de partición, del volumen lógico o del sistema de archivos (para ZFS).
833PART="$(ogDiskToDev $1 $2)" || return $?
834SIZE=$(partx -gbo SIZE $PART 2>/dev/null | awk '{print int($1/1024)}')
835[ -z "$SIZE" ] && SIZE=$(lvs --noheadings -o lv_size --units k $PART | awk '{printf "%d",$0}')
836[ -z "$SIZE" ] && SIZE=$(ogGetFsSize $1 $2)
837echo ${SIZE:-0}
838}
839
840
841#/**
842#         ogGetPartitionsNumber int_ndisk
843#@brief   Detecta el numero de particiones del disco duro indicado.
844#@param   int_ndisk      nº de orden del disco
845#@return  Devuelve el numero paritiones del disco duro indicado
846#@warning Salidas de errores no determinada
847#@attention Requisitos: parted
848#@note    Notas sin especificar
849#@version 0.1 -  Integracion para Opengnsys  -  EAC:  DetectNumberPartition () en ATA.lib
850#@author  Antonio J. Doblas Viso. Universidad de Malaga
851#@date    Date: 27/10/2008
852#@version 1.0 - Uso de sfdisk Primera version para OpenGnSys
853#@author  Ramon Gomez, ETSII Universidad de Sevilla
854#@date    2009-07-24
855#@version 1.0.4 - Uso de /proc/partitions para detectar el numero de particiones
856#@author  Universidad de Huelva
857#@date    2012-03-28
858#@version 1.0.6 - Soportar LVM.
859#@author  Universidad de Huelva
860#@date    2014-09-04
861#@version 1.1.0 - Soportar ZFS y sustituir "sfdisk" por "partx".
862#@author  Ramon Gomez, ETSII Universidad Sevilla
863#@date    2016-04-28
864#*/ ##
865function ogGetPartitionsNumber ()
866{
867# Variables locales.
868local DISK
869# Si se solicita, mostrar ayuda.
870if [ "$*" == "help" ]; then
871    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
872           "$FUNCNAME 1  =>  3"
873    return
874fi
875# Error si no se recibe 1 parámetro.
876[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
877
878# Contar el nº de veces que aparece el disco en su lista de particiones.
879DISK=$(ogDiskToDev $1) 2>/dev/null
880case "$(ogGetPartitionTableType $1)" in
881    GPT|MSDOS)
882            partx -gso NR $DISK 2>/dev/null | awk -v p=0 '{p=$1} END {print p}' ;;
883    LVM)    lvs --noheadings $DISK 2>/dev/null | wc -l ;;
884    ZPOOL)  zpool list &>/dev/null || modprobe zfs
885            zpool import -f -R /mnt -N -a 2>/dev/null
886            zfs list -Hp -o name,canmount,mountpoint -r $(blkid -s LABEL -o value $DISK) | \
887                    awk '$2=="on" && $3!="none" {c++}
888                         END {print c}'
889            ;;
890esac
891}
892
893
894#/**
895#         ogGetPartitionTableType int_ndisk
896#@brief   Devuelve el tipo de tabla de particiones del disco (GPT o MSDOS)
897#@param   int_ndisk       nº de orden del disco
898#@return  str_tabletype - Tipo de tabla de paritiones
899#@warning Salidas de errores no determinada
900#@note    tabletype = { MSDOS, GPT }
901#@note    Requisitos: blkid, parted, vgs
902#@version 1.0.4 - Primera versión para OpenGnSys
903#@author  Universidad de Huelva
904#@date    2012/03/01
905#@version 1.0.6 - Soportar LVM.
906#@author  Universidad de Huelva
907#@date    2014-09-04
908#@version 1.1.0 - Mejorar rendimiento y soportar ZFS.
909#@author  Ramon Gomez, ETSII Universidad Sevilla
910#@date    2014-11-14
911#*/ ##
912function ogGetPartitionTableType ()
913{
914# Variables locales.
915local DISK TYPE
916
917# Si se solicita, mostrar ayuda.
918if [ "$*" == "help" ]; then
919    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
920           "$FUNCNAME 1  =>  MSDOS"
921    return
922fi
923# Error si no se recibe 1 parámetro.
924[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
925
926# Sustituye n de disco por su dispositivo.
927DISK=$(ogDiskToDev $1) || return $?
928
929# Comprobar tabla de particiones.
930if [ -b $DISK ]; then
931    TYPE=$(parted -sm $DISK print 2>/dev/null | awk -F: -v D=$DISK '{ if($1 == D) print toupper($6)}')
932    [ -z "$TYPE" ] && TYPE=$(parted -sm $DISK print 2>/dev/null | awk -F: -v D=$DISK '{ if($1 == D) print toupper($6)}')
933fi
934# Comprobar si es volumen lógico.
935[ -d $DISK ] && vgs $DISK &>/dev/null && TYPE="LVM"
936# Comprobar si es pool de ZFS.
937[ -z "$TYPE" -o "$TYPE" == "UNKNOWN" ] && [ -n "$(blkid -s TYPE $DISK | grep zfs)" ] && TYPE="ZPOOL"
938
939# Mostrar salida.
940[ -n "$TYPE" ] && echo "$TYPE"
941}
942
943
944#/**
945#         ogGetPartitionType int_ndisk int_npartition
946#@brief   Devuelve el mnemonico con el tipo de partición.
947#@param   int_ndisk      nº de orden del disco
948#@param   int_npartition nº de orden de la partición
949#@return  Mnemonico
950#@note    Mnemonico: valor devuelto por ogIdToType.
951#@exception OG_ERR_FORMAT   Formato incorrecto.
952#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
953#@version 0.1 -  Integracion para Opengnsys  -  EAC:   TypeFS() en ATA.lib
954#@author  Antonio J. Doblas Viso. Universidad de Malaga
955#@date    2008-10-27
956#@version 0.9 - Primera adaptacion para OpenGnSys.
957#@author  Ramon Gomez, ETSII Universidad de Sevilla
958#@date    2009-07-21
959#@version 1.0.3 - Código trasladado de antigua función ogGetFsType.
960#@author  Ramon Gomez, ETSII Universidad de Sevilla
961#@date    2011-12-01
962#@version 1.0.5 - Usar función ogIdToType para hacer la conversión id. a tipo.
963#@author  Ramon Gomez, ETSII Universidad de Sevilla
964#@date    2013-09-19
965#*/ ##
966function ogGetPartitionType ()
967{
968# Variables locales.
969local ID TYPE
970
971# Si se solicita, mostrar ayuda.
972if [ "$*" == "help" ]; then
973    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
974           "$FUNCNAME 1 1  =>  NTFS"
975    return
976fi
977# Error si no se reciben 2 parámetros.
978[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
979
980# Detectar id. de tipo de partición y codificar al mnemonico.
981ID=$(ogGetPartitionId "$1" "$2") || return $?
982TYPE=$(ogIdToType "$ID")
983echo "$TYPE"
984}
985
986
987#/**
988#         ogHidePartition int_ndisk int_npartition
989#@brief   Oculta un apartición visible.
990#@param   int_ndisk      nº de orden del disco
991#@param   int_npartition nº de orden de la partición
992#@return  (nada)
993#@exception OG_ERR_FORMAT    formato incorrecto.
994#@exception OG_ERR_NOTFOUND  disco o particion no detectado (no es un dispositivo).
995#@exception OG_ERR_PARTITION tipo de partición no reconocido.
996#@version 1.0 - Versión en pruebas.
997#@author  Ramon Gomez, ETSII Universidad de Sevilla
998#@date    2010/01/12
999#*/ ##
1000function ogHidePartition ()
1001{
1002# Variables locales.
1003local PART TYPE NEWTYPE
1004# Si se solicita, mostrar ayuda.
1005if [ "$*" == "help" ]; then
1006    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1007           "$FUNCNAME 1 1"
1008    return
1009fi
1010# Error si no se reciben 2 parámetros.
1011[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1012PART=$(ogDiskToDev "$1" "$2") || return $?
1013
1014# Obtener tipo de partición.
1015TYPE=$(ogGetPartitionType "$1" "$2")
1016case "$TYPE" in
1017    NTFS)   NEWTYPE="HNTFS"  ;;
1018    FAT32)  NEWTYPE="HFAT32" ;;
1019    FAT16)  NEWTYPE="HFAT16" ;;
1020    FAT12)  NEWTYPE="HFAT12" ;;
1021    *)      ogRaiseError $OG_ERR_PARTITION "$TYPE"
1022            return $? ;;
1023esac
1024# Cambiar tipo de partición.
1025ogSetPartitionType $1 $2 $NEWTYPE
1026}
1027
1028
1029#/**
1030#         ogIdToType int_idpart
1031#@brief   Devuelve el identificador correspondiente a un tipo de partición.
1032#@param   int_idpart    identificador de tipo de partición.
1033#@return  str_parttype  mnemónico de tipo de partición.
1034#@exception OG_ERR_FORMAT   Formato incorrecto.
1035#@version 1.0.5 - Primera version para OpenGnSys
1036#@author  Ramon Gomez, ETSII Universidad Sevilla
1037#@date    2013-02-07
1038#*/ ##
1039function ogIdToType ()
1040{
1041# Variables locales
1042local ID TYPE
1043
1044# Si se solicita, mostrar ayuda.
1045if [ "$*" == "help" ]; then
1046    ogHelp "$FUNCNAME" "$FUNCNAME int_idpart" \
1047           "$FUNCNAME 83  =>  LINUX"
1048    return
1049fi
1050# Error si no se recibe 1 parámetro.
1051[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1052
1053# Obtener valor hexadecimal de 4 caracteres rellenado con 0 por delante.
1054ID=$(printf "%4s" "$1" | tr ' ' '0')
1055case "${ID,,}" in
1056     0000)      TYPE="EMPTY" ;;
1057     0001)      TYPE="FAT12" ;;
1058     0005|000f) TYPE="EXTENDED" ;;
1059     0006|000e) TYPE="FAT16" ;;
1060     0007)      TYPE="NTFS" ;;
1061     000b|000c) TYPE="FAT32" ;;
1062     0011)      TYPE="HFAT12" ;;
1063     0012)      TYPE="COMPAQDIAG" ;;
1064     0016|001e) TYPE="HFAT16" ;;
1065     0017)      TYPE="HNTFS" ;;
1066     001b|001c) TYPE="HFAT32" ;;
1067     0042)      TYPE="WIN-DYNAMIC" ;;
1068     0082|8200) TYPE="LINUX-SWAP" ;;
1069     0083|8300) TYPE="LINUX" ;;
1070     008e|8E00) TYPE="LINUX-LVM" ;;
1071     00a5|a503) TYPE="FREEBSD" ;;
1072     00a6)      TYPE="OPENBSD" ;;
1073     00a7)      TYPE="CACHE" ;;         # (compatibilidad con Brutalix)
1074     00af|af00) TYPE="HFS" ;;
1075     00be|be00) TYPE="SOLARIS-BOOT" ;;
1076     00bf|bf0[0145]) TYPE="SOLARIS" ;;
1077     00ca|ca00) TYPE="CACHE" ;;
1078     00da)      TYPE="DATA" ;;
1079     00ee)      TYPE="GPT" ;;
1080     00ef|ef00) TYPE="EFI" ;;
1081     00fb)      TYPE="VMFS" ;;
1082     00fd|fd00) TYPE="LINUX-RAID" ;;
1083     0700)      TYPE="WINDOWS" ;;
1084     0c01)      TYPE="WIN-RESERV" ;;
1085     7f00)      TYPE="CHROMEOS-KRN" ;;
1086     7f01)      TYPE="CHROMEOS" ;;
1087     7f02)      TYPE="CHROMEOS-RESERV" ;;
1088     8301)      TYPE="LINUX-RESERV" ;;
1089     a500)      TYPE="FREEBSD-DISK" ;;
1090     a501)      TYPE="FREEBSD-BOOT" ;;
1091     a502)      TYPE="FREEBSD-SWAP" ;;
1092     ab00)      TYPE="HFS-BOOT" ;;
1093     af01)      TYPE="HFS-RAID" ;;
1094     bf02)      TYPE="SOLARIS-SWAP" ;;
1095     bf03)      TYPE="SOLARIS-DISK" ;;
1096     ef01)      TYPE="MBR" ;;
1097     ef02)      TYPE="BIOS-BOOT" ;;
1098     10000)     TYPE="LVM-LV" ;;
1099     10010)     TYPE="ZFS-VOL" ;;
1100     *)         TYPE="UNKNOWN" ;;
1101esac
1102echo "$TYPE"
1103}
1104
1105
1106#         ogIsDiskLocked int_ndisk
1107#@brief   Comprueba si un disco está bloqueado por una operación de uso exclusivo.
1108#@param   int_ndisk      nº de orden del disco
1109#@return  Código de salida: 0 - bloqueado, 1 - sin bloquear o error.
1110#@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 "-".
1111#@version 1.1.0 - Primera versión para OpenGnsys.
1112#@author  Ramon Gomez, ETSII Universidad de Sevilla
1113#@date    2016-04-08
1114#*/ ##
1115function ogIsDiskLocked ()
1116{
1117# Variables locales
1118local DISK LOCKFILE
1119
1120# Si se solicita, mostrar ayuda.
1121if [ "$*" == "help" ]; then
1122    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
1123           "if $FUNCNAME 1; then ... ; fi"
1124    return
1125fi
1126# Falso, en caso de error.
1127[ $# == 1 ] || return 1
1128DISK="$(ogDiskToDev $1 2>/dev/null)" || return 1
1129
1130# Comprobar existencia de fichero de bloqueo para el disco.
1131LOCKFILE="/var/lock/lock${DISK//\//-}"
1132test -f $LOCKFILE
1133}
1134
1135
1136#/**
1137#         ogListPartitions int_ndisk
1138#@brief   Lista las particiones definidas en un disco.
1139#@param   int_ndisk  nº de orden del disco
1140#@return  str_parttype:int_partsize ...
1141#@exception OG_ERR_FORMAT   formato incorrecto.
1142#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
1143#@note    Requisitos: \c parted \c awk
1144#@attention El nº de partición se indica por el orden de los párametros \c parttype:partsize
1145#@attention Las tuplas de valores están separadas por espacios.
1146#@version 0.9 - Primera versión para OpenGnSys
1147#@author  Ramon Gomez, ETSII Universidad de Sevilla
1148#@date    2009/07/24
1149#*/ ##
1150function ogListPartitions ()
1151{
1152# Variables locales.
1153local DISK PART NPARTS TYPE SIZE
1154
1155# Si se solicita, mostrar ayuda.
1156if [ "$*" == "help" ]; then
1157    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
1158           "$FUNCNAME 1  =>  NTFS:10000000 EXT3:5000000 LINUX-SWAP:1000000"
1159    return
1160fi
1161# Error si no se recibe 1 parámetro.
1162[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT "$FORMAT" || return $?
1163
1164# Procesar la salida de \c parted .
1165DISK="$(ogDiskToDev $1)" || return $?
1166NPARTS=$(ogGetPartitionsNumber $1)
1167for (( PART = 1; PART <= NPARTS; PART++ )); do
1168    TYPE=$(ogGetPartitionType $1 $PART 2>/dev/null); TYPE=${TYPE:-EMPTY}
1169    SIZE=$(ogGetPartitionSize $1 $PART 2>/dev/null); SIZE=${SIZE:-0}
1170    echo -n "$TYPE:$SIZE "
1171done
1172echo
1173}
1174
1175
1176#/**
1177#         ogListPrimaryPartitions int_ndisk
1178#@brief   Metafunción que lista las particiones primarias no vacías de un disco.
1179#@param   int_ndisk  nº de orden del disco
1180#@see     ogListPartitions
1181#*/ ##
1182function ogListPrimaryPartitions ()
1183{
1184# Variables locales.
1185local PTTYPE PARTS
1186
1187# Si se solicita, mostrar ayuda.
1188if [ "$*" == "help" ]; then
1189    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
1190           "$FUNCNAME 1  =>  NTFS:10000000 EXT3:5000000 EXTENDED:1000000"
1191    return
1192fi
1193
1194PTTYPE=$(ogGetPartitionTableType $1) || return $?
1195PARTS=$(ogListPartitions "$@") || return $?
1196case "$PTTYPE" in
1197    GPT)    echo $PARTS | sed 's/\( EMPTY:0\)*$//' ;;
1198    MSDOS)  echo $PARTS | cut -sf1-4 -d" " | sed 's/\( EMPTY:0\)*$//' ;;
1199esac
1200}
1201
1202
1203#/**
1204#         ogListLogicalPartitions int_ndisk
1205#@brief   Metafunción que lista las particiones lógicas de una tabla tipo MSDOS.
1206#@param   int_ndisk  nº de orden del disco
1207#@see     ogListPartitions
1208#*/ ##
1209function ogListLogicalPartitions ()
1210{
1211# Variables locales.
1212local PTTYPE PARTS
1213
1214# Si se solicita, mostrar ayuda.
1215if [ "$*" == "help" ]; then
1216    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
1217           "$FUNCNAME 1  =>  LINUX-SWAP:999998"
1218    return
1219fi
1220PTTYPE=$(ogGetPartitionTableType $1) || return $?
1221[ "$PTTYPE" == "MSDOS" ] || ogRaiseError $OG_ERR_PARTITION "" || return $?
1222PARTS=$(ogListPartitions "$@") || return $?
1223echo $PARTS | cut -sf5- -d" "
1224}
1225
1226
1227#/**
1228#         ogLockDisk int_ndisk
1229#@brief   Genera un fichero de bloqueo para un disco en uso exlusivo.
1230#@param   int_ndisk      nº de orden del disco
1231#@return  (nada)
1232#@exception OG_ERR_FORMAT    Formato incorrecto.
1233#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1234#@note    El fichero de bloqueo se localiza en \c /var/lock/disk, siendo \c disk el dispositivo del disco, sustituyendo el carácter "/" por "-".
1235#@version 1.1.0 - Primera versión para OpenGnsys.
1236#@author  Ramon Gomez, ETSII Universidad de Sevilla
1237#@date    2016-04-07
1238#*/ ##
1239function ogLockDisk ()
1240{
1241# Variables locales
1242local DISK LOCKFILE
1243
1244# Si se solicita, mostrar ayuda.
1245if [ "$*" == "help" ]; then
1246    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
1247           "$FUNCNAME 1"
1248    return
1249fi
1250# Error si no se recibe 1 parámetro.
1251[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1252
1253# Obtener partición.
1254DISK="$(ogDiskToDev $1)" || return $?
1255
1256# Crear archivo de bloqueo exclusivo.
1257LOCKFILE="/var/lock/lock${DISK//\//-}"
1258touch $LOCKFILE
1259}
1260
1261
1262#/**
1263#         ogSetPartitionActive int_ndisk int_npartition
1264#@brief   Establece cual es la partición activa de un disco.
1265#@param   int_ndisk      nº de orden del disco
1266#@param   int_npartition nº de orden de la partición
1267#@return  (nada).
1268#@exception OG_ERR_FORMAT   Formato incorrecto.
1269#@exception OG_ERR_NOTFOUND Disco o partición no corresponden con un dispositivo.
1270#@note    Requisitos: parted
1271#@version 0.1 -  Integracion para Opengnsys  -  EAC: SetPartitionActive() en ATA.lib
1272#@author  Antonio J. Doblas Viso, Universidad de Malaga
1273#@date    2008/10/27
1274#@version 0.9 - Primera version compatible con OpenGnSys.
1275#@author  Ramon Gomez, ETSII Universidad de Sevilla
1276#@date    2009/09/17
1277#*/ ##
1278function ogSetPartitionActive ()
1279{
1280# Variables locales
1281local DISK PART
1282
1283# Si se solicita, mostrar ayuda.
1284if [ "$*" == "help" ]; then
1285    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1286           "$FUNCNAME 1 1"
1287    return
1288fi
1289# Error si no se reciben 2 parámetros.
1290[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1291
1292# Comprobar que el disco existe y activar la partición indicada.
1293DISK="$(ogDiskToDev $1)" || return $?
1294PART="$(ogDiskToDev $1 $2)" || return $?
1295parted -s $DISK set $2 boot on 2>/dev/null
1296}
1297
1298
1299#/**
1300#         ogSetPartitionId int_ndisk int_npartition hex_partid
1301#@brief   Cambia el identificador de la partición.
1302#@param   int_ndisk      nº de orden del disco
1303#@param   int_npartition nº de orden de la partición
1304#@param   hex_partid     identificador de tipo de partición
1305#@return  (nada)
1306#@exception OG_ERR_FORMAT     Formato incorrecto.
1307#@exception OG_ERR_NOTFOUND   Disco o partición no corresponden con un dispositivo.
1308#@exception OG_ERR_OUTOFLIMIT Valor no válido.
1309#@exception OG_ERR_PARTITION  Error al cambiar el id. de partición.
1310#@attention Requisitos: fdisk, sgdisk
1311#@version 0.1 -  Integracion para Opengnsys  - SetPartitionType() en ATA.lib
1312#@author  Antonio J. Doblas Viso. Universidad de Malaga
1313#@date    2008/10/27
1314#@version 1.0.4 - Soporte para discos GPT.
1315#@author  Universidad de Huelva
1316#@date    2012/03/13
1317#@version 1.0.5 - Utiliza el id. de tipo de partición (no el mnemónico)
1318#@author  Universidad de Huelva
1319#@date    2012/05/14
1320#*/ ##
1321function ogSetPartitionId ()
1322{
1323# Variables locales
1324local DISK PART PTTYPE ID
1325
1326# Si se solicita, mostrar ayuda.
1327if [ "$*" == "help" ]; then
1328    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition hex_partid" \
1329           "$FUNCNAME 1 1 7"
1330    return
1331fi
1332# Error si no se reciben 3 parámetros.
1333[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1334
1335# Sustituye nº de disco y nº partición por su dispositivo.
1336DISK=$(ogDiskToDev $1) || return $?
1337PART=$(ogDiskToDev $1 $2) || return $?
1338# Error si el id. de partición no es hexadecimal.
1339ID="${3^^}"
1340[[ "$ID" =~ ^[0-9A-F]+$ ]] || ogRaiseError $OG_ERR_OUTOFLIMIT "$3" || return $?
1341
1342# Elección del tipo de partición.
1343PTTYPE=$(ogGetPartitionTableType $1)
1344case "$PTTYPE" in
1345    GPT)    sgdisk -t$2:$ID $DISK 2>/dev/null ;;
1346    MSDOS)  sfdisk --id $DISK $2 $ID 2>/dev/null ;;
1347    *)      ogRaiseError $OG_ERR_OUTOFLIMIT "$1,$PTTYPE"
1348            return $? ;;
1349esac
1350
1351# MSDOS) Correcto si fdisk sin error o con error pero realiza Syncing
1352if [ "${PIPESTATUS[1]}" == "0" -o $? -eq 0 ]; then
1353    partprobe $DISK 2>/dev/null
1354    return 0
1355else
1356    ogRaiseError $OG_ERR_PARTITION "$1,$2,$3"
1357    return $?
1358fi
1359}
1360
1361
1362#/**
1363#         ogSetPartitionSize int_ndisk int_npartition int_size
1364#@brief   Muestra el tamano en KB de una particion determinada.
1365#@param   int_ndisk      nº de orden del disco
1366#@param   int_npartition nº de orden de la partición
1367#@param   int_size       tamaño de la partición (en KB)
1368#@return  (nada)
1369#@exception OG_ERR_FORMAT   formato incorrecto.
1370#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
1371#@note    Requisitos: sfdisk, awk
1372#@todo    Compruebar que el tamaño sea numérico positivo y evitar que pueda solaparse con la siguiente partición.
1373#@version 0.9 - Primera versión para OpenGnSys
1374#@author  Ramon Gomez, ETSII Universidad de Sevilla
1375#@date    2009/07/24
1376#*/ ##
1377function ogSetPartitionSize ()
1378{
1379# Variables locales.
1380local DISK PART SIZE
1381
1382# Si se solicita, mostrar ayuda.
1383if [ "$*" == "help" ]; then
1384    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_size" \
1385           "$FUNCNAME 1 1 10000000"
1386    return
1387fi
1388# Error si no se reciben 3 parámetros.
1389[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1390
1391# Obtener el tamaño de la partición.
1392DISK="$(ogDiskToDev $1)" || return $?
1393PART="$(ogDiskToDev $1 $2)" || return $?
1394# Convertir tamaño en KB a sectores de 512 B.
1395SIZE=$[$3*2] || ogRaiseError $OG_ERR_FORMAT || return $?
1396# Redefinir el tamaño de la partición.
1397sfdisk -f -uS -N$2 $DISK <<< ",$SIZE" &>/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
1398partprobe $DISK 2>/dev/null
1399}
1400
1401
1402#/**
1403#         ogSetPartitionType int_ndisk int_npartition str_type
1404#@brief   Cambia el identificador de la partición.
1405#@param   int_ndisk      nº de orden del disco
1406#@param   int_npartition nº de orden de la partición
1407#@param   str_type       mnemónico de tipo de partición
1408#@return  (nada)
1409#@attention Requisitos: fdisk, sgdisk
1410#@version 0.1 -  Integracion para Opengnsys  - SetPartitionType() en ATA.lib
1411#@author  Antonio J. Doblas Viso. Universidad de Malaga
1412#@date    2008/10/27
1413#@version 1.0.4 - Soporte para discos GPT.
1414#@author  Universidad de Huelva
1415#@date    2012/03/13
1416#@version 1.0.5 - Renombrada de ogSetPartitionId.
1417#@author  Ramon Gomez, ETSII Universidad de Sevilla
1418#@date    2013/03/07
1419#*/ ##
1420function ogSetPartitionType ()
1421{
1422# Variables locales
1423local DISK PART PTTYPE ID
1424
1425# Si se solicita, mostrar ayuda.
1426if [ "$*" == "help" ]; then
1427    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition str_type" \
1428           "$FUNCNAME 1 1 NTFS"
1429    return
1430fi
1431# Error si no se reciben 3 parámetros.
1432[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1433
1434# Sustituye nº de disco por su dispositivo.
1435DISK=`ogDiskToDev $1` || return $?
1436PART=`ogDiskToDev $1 $2` || return $?
1437
1438# Elección del tipo de partición.
1439PTTYPE=$(ogGetPartitionTableType $1)
1440ID=$(ogTypeToId "$3" "$PTTYPE")
1441[ -n "$ID" ] || ogRaiseError $OG_ERR_FORMAT "$3,$PTTYPE" || return $?
1442ogSetPartitionId $1 $2 $ID
1443}
1444
1445
1446#/**
1447#         ogTypeToId str_parttype [str_tabletype]
1448#@brief   Devuelve el identificador correspondiente a un tipo de partición.
1449#@param   str_parttype  mnemónico de tipo de partición.
1450#@param   str_tabletype mnemónico de tipo de tabla de particiones (MSDOS por defecto).
1451#@return  int_idpart    identificador de tipo de partición.
1452#@exception OG_ERR_FORMAT   Formato incorrecto.
1453#@note    tabletype = { MSDOS, GPT },   (MSDOS, por defecto)
1454#@version 0.1 -  Integracion para Opengnsys  -  EAC: TypeFS () en ATA.lib
1455#@author  Antonio J. Doblas Viso, Universidad de Malaga
1456#@date    2008/10/27
1457#@version 0.9 - Primera version para OpenGnSys
1458#@author  Ramon Gomez, ETSII Universidad Sevilla
1459#@date    2009-12-14
1460#@version 1.0.4 - Soportar discos GPT (sustituye a ogFsToId).
1461#@author  Universidad de Huelva
1462#@date    2012/03/30
1463#*/ ##
1464function ogTypeToId ()
1465{
1466# Variables locales
1467local PTTYPE ID=""
1468
1469# Si se solicita, mostrar ayuda.
1470if [ "$*" == "help" ]; then
1471    ogHelp "$FUNCNAME" "$FUNCNAME str_parttype [str_tabletype]" \
1472           "$FUNCNAME LINUX  =>  83" \
1473           "$FUNCNAME LINUX MSDOS  =>  83"
1474    return
1475fi
1476# Error si no se reciben 1 o 2 parámetros.
1477[ $# -lt 1 -o $# -gt 2 ] && (ogRaiseError $OG_ERR_FORMAT; return $?)
1478
1479# Asociar id. de partición para su mnemónico.
1480PTTYPE=${2:-"MSDOS"}
1481case "$PTTYPE" in
1482    GPT) # Se incluyen mnemónicos compatibles con tablas MSDOS.
1483        case "$1" in
1484            EMPTY)      ID=0 ;;
1485            WINDOWS|NTFS|EXFAT|FAT32|FAT16|FAT12|HNTFS|HFAT32|HFAT16|HFAT12)
1486                        ID=0700 ;;
1487            WIN-RESERV) ID=0C01 ;;
1488            CHROMEOS-KRN) ID=7F00 ;;
1489            CHROMEOS)   ID=7F01 ;;
1490            CHROMEOS-RESERV) ID=7F02 ;;
1491            LINUX-SWAP) ID=8200 ;;
1492            LINUX|EXT[234]|REISERFS|REISER4|XFS|JFS)
1493                        ID=8300 ;;
1494            LINUX-RESERV) ID=8301 ;;
1495            LINUX-LVM)  ID=8E00 ;;
1496            FREEBSD-DISK) ID=A500 ;;
1497            FREEBSD-BOOT) ID=A501 ;;
1498            FREEBSD-SWAP) ID=A502 ;;
1499            FREEBSD)    ID=A503 ;;
1500            HFS-BOOT)   ID=AB00 ;;
1501            HFS|HFS+)   ID=AF00 ;;
1502            HFSPLUS)    ID=AF00 ;;
1503            HFS-RAID)   ID=AF01 ;;
1504            SOLARIS-BOOT) ID=BE00 ;;
1505            SOLARIS)    ID=BF00 ;;
1506            SOLARIS-SWAP) ID=BF02 ;;
1507            SOLARIS-DISK) ID=BF03 ;;
1508            CACHE)      ID=CA00;;
1509            EFI)        ID=EF00 ;;
1510            LINUX-RAID) ID=FD00 ;;
1511        esac
1512        ;;
1513    MSDOS)
1514        case "$1" in
1515            EMPTY)      ID=0  ;;
1516            FAT12)      ID=1  ;;
1517            EXTENDED)   ID=5  ;;
1518            FAT16)      ID=6  ;;
1519            WINDOWS|NTFS|EXFAT)
1520                        ID=7  ;;
1521            FAT32)      ID=b  ;;
1522            HFAT12)     ID=11 ;;
1523            HFAT16)     ID=16 ;;
1524            HNTFS)      ID=17 ;;
1525            HFAT32)     ID=1b ;;
1526            LINUX-SWAP) ID=82 ;;
1527            LINUX|EXT[234]|REISERFS|REISER4|XFS|JFS)
1528                        ID=83 ;;
1529            LINUX-LVM)  ID=8e ;;
1530            FREEBSD)    ID=a5 ;;
1531            OPENBSD)    ID=a6 ;;
1532            HFS|HFS+)   ID=af ;;
1533            SOLARIS-BOOT) ID=be ;;
1534            SOLARIS)    ID=bf ;;
1535            CACHE)      ID=ca ;;
1536            DATA)       ID=da ;;
1537            GPT)        ID=ee ;;
1538            EFI)        ID=ef ;;
1539            VMFS)       ID=fb ;;
1540            LINUX-RAID) ID=fd ;;
1541        esac
1542        ;;
1543    LVM)
1544        case "$1" in
1545            LVM-LV)     ID=10000 ;;
1546        esac
1547        ;;
1548    ZVOL)
1549        case "$1" in
1550            ZFS-VOL)    ID=10010 ;;
1551        esac
1552        ;;
1553esac
1554echo $ID
1555}
1556
1557
1558#/**
1559#         ogUnhidePartition int_ndisk int_npartition
1560#@brief   Hace visible una partición oculta.
1561#@param   int_ndisk      nº de orden del disco
1562#@param   int_npartition nº de orden de la partición
1563#@return  (nada)
1564#@exception OG_ERR_FORMAT    formato incorrecto.
1565#@exception OG_ERR_NOTFOUND  disco o particion no detectado (no es un dispositivo).
1566#@exception OG_ERR_PARTITION tipo de partición no reconocido.
1567#@version 1.0 - Versión en pruebas.
1568#@author  Ramon Gomez, ETSII Universidad de Sevilla
1569#@date    2010/01/12
1570#*/ ##
1571function ogUnhidePartition ()
1572{
1573# Variables locales.
1574local PART TYPE NEWTYPE
1575# Si se solicita, mostrar ayuda.
1576if [ "$*" == "help" ]; then
1577    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
1578           "$FUNCNAME 1 1"
1579    return
1580fi
1581# Error si no se reciben 2 parámetros.
1582[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1583PART=$(ogDiskToDev "$1" "$2") || return $?
1584
1585# Obtener tipo de partición.
1586TYPE=$(ogGetPartitionType "$1" "$2")
1587case "$TYPE" in
1588    HNTFS)   NEWTYPE="NTFS"  ;;
1589    HFAT32)  NEWTYPE="FAT32" ;;
1590    HFAT16)  NEWTYPE="FAT16" ;;
1591    HFAT12)  NEWTYPE="FAT12" ;;
1592    *)      ogRaiseError $OG_ERR_PARTITION "$TYPE"
1593            return $? ;;
1594esac
1595# Cambiar tipo de partición.
1596ogSetPartitionType $1 $2 $NEWTYPE
1597}
1598
1599
1600#/**
1601#         ogUnlockDisk int_ndisk
1602#@brief   Elimina el fichero de bloqueo para un disco.
1603#@param   int_ndisk      nº de orden del disco
1604#@return  (nada)
1605#@exception OG_ERR_FORMAT    Formato incorrecto.
1606#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
1607#@note    El fichero de bloqueo se localiza en \c /var/lock/disk, siendo \c disk el dispositivo del disco, sustituyendo el carácter "/" por "-".
1608#@version 1.1.0 - Primera versión para OpenGnsys.
1609#@author  Ramon Gomez, ETSII Universidad de Sevilla
1610#@date    2016-04-08
1611#*/ ##
1612function ogUnlockDisk ()
1613{
1614# Variables locales
1615local DISK LOCKFILE
1616
1617# Si se solicita, mostrar ayuda.
1618if [ "$*" == "help" ]; then
1619    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
1620           "$FUNCNAME 1"
1621    return
1622fi
1623# Error si no se recibe 1 parámetro.
1624[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
1625
1626# Obtener partición.
1627DISK="$(ogDiskToDev $1)" || return $?
1628
1629# Borrar archivo de bloqueo exclusivo.
1630LOCKFILE="/var/lock/lock${DISK//\//-}"
1631rm -f $LOCKFILE
1632}
1633
1634
1635#/**
1636#         ogUpdatePartitionTable
1637#@brief   Fuerza al kernel releer la tabla de particiones de los discos duros
1638#@param   no requiere
1639#@return  informacion propia de la herramienta
1640#@note    Requisitos: \c partprobe
1641#@warning pendiente estructurar la funcion a opengnsys
1642#@version 0.1 -  Integracion para Opengnsys  -  EAC: UpdatePartitionTable() en ATA.lib
1643#@author  Antonio J. Doblas Viso. Universidad de Malaga
1644#@date    27/10/2008
1645#*/ ##
1646function ogUpdatePartitionTable ()
1647{
1648local i
1649for i in `ogDiskToDev`
1650do
1651        partprobe $i
1652done
1653}
Note: See TracBrowser for help on using the repository browser.