source: client/engine/Disk.lib @ 67388cc

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

Versión 1.0.4, #531: Retoques en ayudas y en código para Doxygen.

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

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