source: client/engine/Disk.lib @ f8a75f18

opengnsys-1.0.6b
Last change on this file since f8a75f18 was f2ac15a, checked in by ramon <ramongomez@…>, 8 years ago

#754: Congelar versión de mantenimiento en rama tags/opengnsys-1.0.6b.

git-svn-id: https://opengnsys.es/svn/tags/opengnsys-1.0.6b@5144 a21b9725-9963-47de-94b9-378ad31fedc9

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