source: client/engine/Disk.lib @ 831830f

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 831830f was 8ca8f5e, checked in by ramon <ramongomez@…>, 12 years ago

Versión 1.0.5, #397: Ayudas correctas en funciones ogSetPartitionId y ogSetPartitionType.

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

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