source: client/engine/Disk.lib @ 0703783

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 0703783 was 6bde19d, checked in by ramon <ramongomez@…>, 11 years ago

#637: Corregir erratas en r4188.

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

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