source: client/engine/Disk.lib @ b584da5

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 b584da5 was e3f557f, checked in by ramon <ramongomez@…>, 9 years ago

Versión 1.1: Solucionar errata en detección de caché para discos GPT en función ogCreateGptPartitions.

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

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