source: client/engine/Disk.lib @ 4e19f13

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 4e19f13 was 1f2f1e2, checked in by irina <irinagomez@…>, 11 years ago

ogSetPartitionId: Se elimina falso error cuando las particiones están montadas o existe swap.

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