source: client/engine/Disk.lib @ e9601e1

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-instalacion
Last change on this file since e9601e1 was e9601e1, checked in by Irina Gómez <irinagomez@…>, 6 years ago

#802 #889 #890 ogGrubInstallPartitions, ogGrubInstallMbr y ogRestoreEfiBootLoader: Format EFI partition if it is not. ogGetEsp: Detecting the EFI partition does not require VFAT filesystem.

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