source: client/engine/Disk.lib @ d01525b

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 d01525b was 4850d65, checked in by ramon <ramongomez@…>, 7 years ago

#802: Corregir errata en revisión r5748.

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

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