source: client/engine/Disk.lib @ e79df1d

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 e79df1d was 19b1a2f, checked in by ramon <ramongomez@…>, 12 years ago

Versión 1.0.5, #526: Cambios en función ogDiskToDev para soportar que los parámetros puedan ser números positivos (en vez de un único dígito), lo que permite disponer de más de 9 discos y de más de 9 particiones (necesario en tablas GPT).

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

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