source: client/engine/Disk.lib @ f2c8049

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

Versión 1.0.4, #526: Corregir erratas en librería Disk.

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

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