source: client/engine/Disk.lib @ 72875ec

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

Versión 1.0.5, #295: Eliminar función obsoleta ogFsToId.

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

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