source: client/engine/Disk.lib @ 4d2cdae

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 4d2cdae was b663655, checked in by ramon <ramongomez@…>, 12 years ago

Función ogGetPartitionType llama a ogIdToType para obtener el tipo; corrección de código en tipos de particiones FREEBSD y HFS-BOOT.

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

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