source: client/engine/Disk.lib @ e9601e1

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

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

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