source: client/engine/Disk.lib @ 1d2bb00

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 1d2bb00 was 6bb748b, checked in by ramon <ramongomez@…>, 7 years ago

#802: Integrar nuevas funciones en pruebas para gestión de equipos UEFI.

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

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