source: client/engine/Disk.lib @ e4546f2

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 e4546f2 was 6bb748b, checked in by ramon <ramongomez@…>, 7 years ago

#802: Integrar nuevas funciones en pruebas para gestión de equipos UEFI.

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

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