source: client/engine/Disk.lib @ eeade34

v1.2.0
Last change on this file since eeade34 was 6d71b90, checked in by Juan Manuel Bardallo juanmanuel.bardallo@…>, 5 years ago

ogGetEsp has been modified to handle with nvme disks, in that case, blkid returns

/dev/loop0
/dev/nvme0n1
/dev/nvme0n1p1

When ogDevToDisk processes the line /dev/nvme0n1, $PART contains only one argument corresponding to the disk number, when occurs, ogGetPartitionId throws an error.

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