source: client/engine/Disk.lib @ cdbf1fc

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 cdbf1fc was d959834, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#906: Declaring new variables as local.

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