source: client/engine/Disk.lib @ 102a50e

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacion
Last change on this file since 102a50e was d6ff164, checked in by Irina Gómez <irinagomez@…>, 6 years ago

#802 #889 ogSetPartitionActive shows message as warning

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