source: client/engine/Disk.lib @ e47e131

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 e47e131 was 9d89103, checked in by irina <irinagomez@…>, 8 years ago

#730 Se corrige errata en ogSetPartitionId

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

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