source: client/engine/Disk.lib @ 59d6670

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 59d6670 was 1f75d13, checked in by Ramón M. Gómez <ramongomez@…>, 7 years ago

Close #871: Sectors overflow comparition is moved.

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