source: client/engine/Disk.lib @ efe8ac7

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 efe8ac7 was f12cc5d, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.4, #526: Cambiar el identificador definitivo para partición de caché en discos GPT.

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

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