source: client/engine/Disk.lib @ 426ca26

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 426ca26 was 472a4fb, checked in by ramon <ramongomez@…>, 8 years ago

#748: Función ogDevToDisk usa fichero de configuración de discos detectados.

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

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