source: client/engine/Disk.lib @ fc57da8

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since fc57da8 was 1f75d13, checked in by Ramón M. Gómez <ramongomez@…>, 7 years ago

Close #871: Sectors overflow comparition is moved.

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