source: client/engine/Disk.lib @ a37e5fc4

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 a37e5fc4 was e38039e, checked in by ramon <ramongomez@…>, 7 years ago

#830: Ayuda y control de errores en función ogGetDiskType.

git-svn-id: https://opengnsys.es/svn/branches/version1.1@5621 a21b9725-9963-47de-94b9-378ad31fedc9

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