source: client/engine/Disk.lib @ e09311f

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 e09311f was 72a7666, checked in by ramon <ramongomez@…>, 15 years ago

Función ogDeleteCache; simplificar ogCreateCache.

git-svn-id: https://opengnsys.es/svn/trunk@807 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100755
File size: 27.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 0.9
8#@warning License: GNU GPLv3+
9#*/
10
11
12#/**
13#         ogCreateCache int_partsize
14#@brief   Define la caché local en la partición 4 del disco 1
15#@param   int_partsize   tamaño de la partición (en KB)
16#@return  (nada, por determinar)
17#@exception OG_ERR_FORMAT   formato incorrecto.
18#@note    Requisitos: sfdisk, parted, awk, sed
19#@version 0.91 - Definición de caché local.
20#@author  Ramon Gomez, ETSII Universidad de Sevilla
21#@date    2010/03/09
22#*/ ##
23function ogCreateCache ()
24{
25# Variables locales.
26local DISK PART SECTORS CYLS START END SIZE ENDPART3
27# Si se solicita, mostrar ayuda.
28if [ "$*" == "help" ]; then
29    ogHelp "$FUNCNAME" "$FUNCNAME 10000000"
30    return
31fi
32# Error si no se recibe 1 parámetro.
33[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
34
35DISK=$(ogDiskToDev 1) || return $?
36PART="4"
37SECTORS=$(awk -v D=${DISK#/dev/} '{if ($4==D) {print $3*2}}' /proc/partitions)
38CYLS=$(sfdisk -g $DISK | cut -f2 -d" ")
39END=$[SECTORS/CYLS*CYLS-1]
40SIZE=$(echo $1|awk '{print $0*2}')      # En sectores de 512 B.
41START=$[END-SIZE+1]
42ENDPART3=$(sfdisk -uS -l $DISK | awk -v P="${DISK}3" '{if ($1==P) print $3}')
43# Error si tamaño 0 o si mayor que la mitad del disco o si pisa la partición 3.
44if [ $SIZE -eq 0 -o $SIZE -ge $[END/2] -o $START -le $ENDPART3 ]; then
45    ogRaiseError $OG_ERR_FORMAT "$1" || return $?
46fi
47
48# Desmontar todos los sistemas de archivos del disco.
49ogUnmountAll 1 2>/dev/null
50# Si la tabla de particiones no es valida, volver a generarla.
51[ $(parted -s $DISK print >/dev/null) ] || fdisk $DISK <<< "w"
52# Definir particiones y notificar al kernel.
53sfdisk -f $DISK -uS -N$PART <<<"$START,$SIZE,ca" 2>/dev/null && sfdisk -R $DISK
54}
55
56
57#/**
58#         ogCreatePartitions int_ndisk str_parttype:int_partsize ...
59#@brief   Define el conjunto de particiones de un disco.
60#@param   int_ndisk      nº de orden del disco
61#@param   str_parttype   mnemónico del tipo de partición
62#@param   int_partsize   tamaño de la partición (en KB)
63#@return  (nada, por determinar)
64#@exception OG_ERR_FORMAT   formato incorrecto.
65#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
66#@attention El nº de partición se indica por el orden de los párametros \c parttype:partsize
67#@attention Pueden definirse particiones vacías de tipo \c EMPTY
68#@attention No puede definirse partición de cache y no se modifica si existe.
69#@note    Requisitos: sfdisk, parted, partprobe, awk
70#@todo    Definir atributos (arranque, oculta) y tamaños en MB, GB, etc.
71#@version 0.9 - Primera versión para OpenGNSys
72#@author  Ramon Gomez, ETSII Universidad de Sevilla
73#@date    2009/09/09
74#@version 0.91 - Corrección del redondeo del tamaño del disco.
75#@author  Ramon Gomez, ETSII Universidad de Sevilla
76#@date    2010/03/09
77#*/ ##
78function ogCreatePartitions ()
79{
80# Variables locales.
81local DISK PART SECTORS CYLS START SIZE TYPE CACHESIZE EXTSTART EXTSIZE tmpsfdisk
82# Si se solicita, mostrar ayuda.
83if [ "$*" == "help" ]; then
84    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk str_parttype:int_partsize ..." \
85           "$FUNCNAME 1 NTFS:10000000 EXT3:5000000 LINUX-SWAP:1000000"
86    return
87fi
88# Error si no se reciben menos de 2 parámetros.
89[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
90
91# Desmontar todos los sistemas de archivos del disco.
92DISK=$(ogDiskToDev "$1") || return $?
93ogUnmountAll $1
94# Nº total de sectores, para evitar desbordamiento (evitar redondeo).
95SECTORS=$(awk -v D=${DISK#/dev/} '{if ($4==D) {print $3*2}}' /proc/partitions)
96CYLS=$(sfdisk -g $DISK | cut -f2 -d" ")
97SECTORS=$[SECTORS/CYLS*CYLS-1]
98# Se recalcula el nº de sectores del disco 1, si existe partición de caché.
99CACHESIZE=$(ogGetCacheSize 2>/dev/null)
100[ $1 == 1 -a -n "$CACHESIZE" ] && SECTORS=$[SECTORS-$CACHESIZE*2]
101ENDPART3=$(sfdisk -uS -l $DISK | awk -v P="${DISK}3" '{if ($1==P) print $3}')
102# Sector de inicio (la partición 1 empieza en el sector 63).
103START=63
104PART=1
105
106# Fichero temporal de entrada para "sfdisk"
107tmpsfdisk=/tmp/sfdisk$$
108trap "rm -f $tmpsfdisk" 1 2 3 9 15
109
110echo "unit: sectors" >$tmpsfdisk
111echo                >>$tmpsfdisk
112
113# Generar fichero de entrada para "sfdisk" con las particiones.
114shift
115while [ $# -gt 0 ]; do
116    # Conservar los datos de la partición de caché.
117    if [ -n "$CACHESIZE" -a $PART == 4 ]; then
118        echo "$DISK$PART : start=$[SECTORS+1], size=$CACHESIZE, Id=ca" >>$tmpsfdisk
119        PART=$[PART+1]
120    fi
121    # Leer formato de cada parámetro - Tipo:Tamaño
122    TYPE="${1%%:*}"
123    [ "$TYPE" != "CACHE" ] || ogRaiseError $OG_ERR_FORMAT "$TYPE" || return $?
124    SIZE="${1#*:}"
125    # Convertir en sectores de 512 B.
126    SIZE=$(echo $SIZE|awk '{print $0*2}')      # (solución error de sintaxis)
127    [ $SIZE -ne 0 ] || ogRaiseError $OG_ERR_FORMAT "$SIZE" || return $?
128    # Obtener identificador de tipo de partición.
129    ID=$(ogFsToId "$TYPE")
130    [ -n "$ID" ] || ogRaiseError $OG_ERR_PARTITION "$TYPE" || return $?
131    # Comprobar si la partición es extendida.
132    if [ $ID = 5 ]; then
133        [ $PART -gt 4 ] && ogRaiseError $OG_ERR_FORMAT && return $?
134        EXTSTART=$START
135        EXTSIZE=$SIZE
136    fi
137    # Incluir particiones lógicas dentro de la partición extendida.
138    if [ $PART = 5 ]; then
139        [ -z "$EXTSTART" ] && ogRaiseError $OG_ERR_FORMAT && return $?
140        START=$EXTSTART
141        SECTORS=$[EXTSTART+EXTSIZE]
142    fi
143    # Generar datos para la partición.
144    echo "$DISK$PART : start=$START, size=$SIZE, Id=$ID" >>$tmpsfdisk
145    # Error si se supera el nº total de sectores.
146    START=$[START+SIZE]
147    [ $START -le $SECTORS ] || ogRaiseError $OG_ERR_FORMAT "$[START/2] > $[SECTORS/2]" || return $?
148    PART=$[PART+1]
149    shift
150done
151# Si no se indican las 4 particiones primarias, definirlas como vacías, conservando la partición de caché.
152while [ $PART -le 4 ]; do
153    if [ -n "$CACHESIZE" -a $PART == 4 ]; then
154        echo "$DISK$PART : start=$[SECTORS+1], size=$CACHESIZE, Id=ca" >>$tmpsfdisk
155    else
156        echo "$DISK$PART : start=0, size=0, Id=0" >>$tmpsfdisk
157    fi
158    PART=$[PART+1]
159done
160# Si se define partición extendida sin lógicas, crear particion 5 vacía.
161if [ $PART = 5 -a -n "$EXTSTART" ]; then
162    echo "${DISK}5 : start=$EXTSTART, size=$EXTSIZE, Id=0" >>$tmpsfdisk
163fi
164
165# Si la tabla de particiones no es valida, volver a generarla.
166[ $(parted -s $DISK print >/dev/null) ] || fdisk $DISK <<< "w"
167# Definir particiones y notificar al kernel.
168sfdisk -f $DISK < $tmpsfdisk 2>/dev/null && sfdisk -R $DISK
169rm -f $tmpsfdisk
170}
171
172
173#/**
174#         ogDeleteCache
175#@brief   Elimina la partición de caché local.
176#@return  (nada, por determinar)
177#@exception OG_ERR_FORMAT   formato incorrecto.
178#@note    Requisitos: sfdisk, parted, awk, sed
179#@version 0.91 - Definición de caché local.
180#@author  Ramon Gomez, ETSII Universidad de Sevilla
181#@date    2010/03/11
182#*/ ##
183function ogDeleteCache ()
184{
185# Variables locales.
186local DISK PART
187# Si se solicita, mostrar ayuda.
188if [ "$*" == "help" ]; then
189    ogHelp "$FUNCNAME" "$FUNCNAME"
190    return
191fi
192# Error si no se encuentra partición de caché.
193read DISK PART <<<"$(ogDevToDisk $(ogFindCache) 2>/dev/null)"
194[ -n "$DISK" -a -n "$PART" ] || ogRaiseError $OG_ERR_PARTITION "CACHE" || return $OG_ERR_PARTITION
195DISK=$(ogDiskToDev $DISK)
196
197# Desmontar todos los sistemas de archivos del disco.
198ogUnmountAll 1 2>/dev/null
199# Si la tabla de particiones no es valida, volver a generarla.
200[ $(parted -s $DISK print >/dev/null) ] || fdisk $DISK <<< "w"
201# Eliminar (poner a 0) la partición de caché.
202sfdisk -f $DISK -N$PART <<<"0,0,0" 2>/dev/null && sfdisk -R $DISK
203}
204
205
206#/**
207#         ogDevToDisk path_device
208#@brief   Devuelve el nº de orden de dicso (y partición) correspondiente al nombre de fichero de dispositivo.
209#@param   path_device Camino del fichero de dispositivo.
210#@return  int_ndisk (para dispositivo de disco)
211#@return  int_ndisk int_npartition (para dispositivo de partición).
212#@exception OG_ERR_FORMAT   Formato incorrecto.
213#@exception OG_ERR_NOTFOUND Dispositivo no detectado.
214#@note    Requisitos: awk
215#@version 0.9 - Primera versión para OpenGNSys
216#@author  Ramon Gomez, ETSII Universidad Sevilla
217#@date    2009-07-20
218#*/ ##
219function ogDevToDisk ()
220{
221# Variables locales.
222local d n
223# Si se solicita, mostrar ayuda.
224if [ "$*" == "help" ]; then
225    ogHelp "$FUNCNAME" "$FUNCNAME path_device" \
226           "$FUNCNAME /dev/sda  =>  1 1"
227    return
228fi
229
230# Error si no se recibe 1 parámetro.
231[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
232# Error si no es fichero de bloques.
233[ -b "$1" ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
234
235# Procesa todos los discos para devolver su nº de orden y de partición.
236n=1
237for d in $(ogDiskToDev); do
238    [ -n "$(echo $1 | grep $d)" ] && echo "$n ${1#$d}" && return
239    n=$[n+1]
240done
241ogRaiseError $OG_ERR_NOTFOUND "$1"
242return $OG_ERR_NOTFOUND
243}
244
245
246#/**
247#         ogDiskToDev [int_ndisk [int_npartition]]
248#@brief   Devuelve la equivalencia entre el nº de orden del dispositivo (dicso o partición) y el nombre de fichero de dispositivo correspondiente.
249#@param   int_ndisk      nº de orden del disco
250#@param   int_npartition nº de orden de la partición
251#@return  Para 0 parametros: Devuelve los nombres de ficheros  de los dispositivos sata/ata/usb linux encontrados.
252#@return  Para 1 parametros: Devuelve la ruta del disco duro indicado.
253#@return  Para 2 parametros: Devuelve la ruta de la particion indicada.
254#@exception OG_ERR_FORMAT   Formato incorrecto.
255#@exception OG_ERR_NOTFOUND Dispositivo no detectado.
256#@note    Requisitos: awk, lvm
257#@version 0.9 - Primera versión para OpenGNSys
258#@author  Ramon Gomez, ETSII Universidad Sevilla
259#@date    2009-07-20
260#*/ ##
261function ogDiskToDev ()
262{
263# Variables locales
264local ALLDISKS VOLGROUPS DISK PART
265
266# Si se solicita, mostrar ayuda.
267if [ "$*" == "help" ]; then
268    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk [int_npartition]" \
269           "$FUNCNAME      =>  /dev/sda /dev/sdb" \
270           "$FUNCNAME 1    =>  /dev/sda" \
271           "$FUNCNAME 1 1  =>  /dev/sda1"
272    return
273fi
274
275# Listar dispositivo para los discos duros (tipos: 3=hd, 8=sd).
276ALLDISKS=$(awk '($1==3 || $1==8) && $4!~/[0-9]/ {printf "/dev/%s ",$4}' /proc/partitions)
277VOLGROUPS=$(vgs -a --noheadings 2>/dev/null | awk '{printf "/dev/%s ",$1}')
278ALLDISKS="$ALLDISKS $VOLGROUPS"
279
280# Mostrar salidas segun el número de parametros.
281case $# in
282    0)  # Muestra todos los discos, separados por espacios.
283        echo $ALLDISKS
284        ;;
285    1)  # Error si el parámetro no es un digito.
286        [ -z "${1/[1-9]/}" ] || ogRaiseError $OG_ERR_FORMAT || return $?
287        DISK=$(echo "$ALLDISKS" | awk -v n=$1 '{print $n}')
288        # Error si el fichero no existe.
289        [ -e "$DISK" ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
290        echo "$DISK"
291        ;;
292    2)  # Error si los 2 parámetros no son digitos.
293        [ -z "${1/[1-9]/}" -a -z "${2/[1-9]/}" ] || ogRaiseError $OG_ERR_FORMAT|| return $?
294        DISK=$(echo "$ALLDISKS" | awk -v n=$1 '{print $n}')
295        [ -e "$DISK" ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $?
296        PART="$DISK$2"
297        # Comprobar si es partición.
298        if [ -b "$PART" ]; then
299            echo "$PART"
300        elif [ -n "$VOLGROUPS" ]; then
301            # Comprobar si volumen lógico.      /* (comentario Doxygen)
302            PART=$(lvscan -a 2>/dev/null | grep "'$DISK/" | awk -v n=$2 -F\' '{if (NR==n) print $2}')
303            [ -e "$PART" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2" || return $?
304            #                                   (comentario Doxygen) */
305            echo "$PART"
306        else
307            ogRaiseError $OG_ERR_NOTFOUND "$1 $2" || return $?
308        fi
309        ;;
310    *)  # Formato erroneo.
311        ogRaiseError $OG_ERR_FORMAT
312        return $OG_ERR_FORMAT
313        ;;
314esac
315}
316
317
318#/**
319#         ogFsToId str_fstype
320#@brief   Devuelve el identificador de partición correspondiente a un tipo de sistema de archivos.
321#@param   str_fstype  mnemónico de tipo de sistema de archivos
322#@return  int_idpart  nº identificador de tipo de partición.
323#@exception OG_ERR_FORMAT   Formato incorrecto.
324#@version 0.9 - Primera versión para OpenGNSys
325#@author  Ramon Gomez, ETSII Universidad Sevilla
326#@date    2009-12-14
327#*/ ##
328function ogFsToId ()
329{
330# Variables locales
331local ID
332
333# Si se solicita, mostrar ayuda.
334if [ "$*" == "help" ]; then
335    ogHelp "$FUNCNAME" "$FUNCNAME str_fstype" "$FUNCNAME EXT3  =>  83"
336    return
337fi
338# Error si no se recibe 1 parámetro.
339[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
340
341# Asociar id. de partición para su mnemónico de sistema de archivos.
342case "$1" in
343    EMPTY)      ID=0  ;;
344    FAT12)      ID=1  ;;
345    EXTENDED)   ID=5  ;;
346    FAT16)      ID=6  ;;
347    NTFS|EXFAT) ID=7  ;;
348    FAT32)      ID=b  ;;
349    HFAT12)     ID=11 ;;
350    HFAT16)     ID=16 ;;
351    HNTFS)      ID=17 ;;
352    HFAT32)     ID=1b ;;
353    LINUX-SWAP) ID=82 ;;
354    EXT[234]|REISERFS|REISER4|XFS|JFS)
355                ID=83 ;;
356    LINUX-LVM)  ID=8e ;;
357    SOLARIS)    ID=bf ;;
358    CACHE)      ID=ca ;;
359    LINUX-RAID) ID=fd ;;
360    *)          ID="" ;;
361esac
362echo $ID
363}
364
365
366#/**
367#         ogGetCacheSize
368#@brief   Devuelve el tamaño definido para la partición de caché.
369#@return  int_partsize   tamaño de la partición (en KB)
370#@exception OG_ERR_PARTITION  No existe partición de caché.
371#@version 0.91 - Definición de caché local.
372#@author  Ramon Gomez, ETSII Universidad de Sevilla
373#@date    2010/03/09
374#*/ ##
375function ogGetCacheSize ()
376{
377# Variables locales
378local PART
379
380# Si se solicita, mostrar ayuda.
381if [ "$*" == "help" ]; then
382    ogHelp "$FUNCNAME" "$FUNCNAME  =>  10000000"
383    return
384fi
385# Error si no se encuentra partición de caché.
386PART=$(ogDevToDisk $(ogFindCache) 2>/dev/null) || ogRaiseError $OG_ERR_PARTITION "CACHE" || return $OG_ERR_PARTITION
387
388# Devuelve tamaño de la partición de caché.
389ogGetPartitionSize $PART
390}
391
392
393#/**
394#         ogGetCacheSpace
395#@brief   Devuelve el espacio de disco disponible para la partición de caché.
396#@return  int_size   tamaño disponible (en KB)
397#@note    El espacio disponible es el que hay entre el límite superior de la partición 3 del disco 1 y el final de dicho disco, y no puede ser superior a la mitad de dicho disco.
398#@version 0.91 - Definición de caché local.
399#@author  Ramon Gomez, ETSII Universidad de Sevilla
400#@date    2010/03/09
401#*/ ##
402function ogGetCacheSpace ()
403{
404
405# Variables locales.
406local DISK SECTORS CYLS ENDPART3
407# Si se solicita, mostrar ayuda.
408if [ "$*" == "help" ]; then
409    ogHelp "$FUNCNAME" "$FUNCNAME  =>  23165386"
410    return
411fi
412
413DISK=$(ogDiskToDev 1) || return $?
414SECTORS=$(awk -v D=${DISK#/dev/} '{if ($4==D) {print $3*2}}' /proc/partitions)
415CYLS=$(sfdisk -g $DISK | cut -f2 -d" ")
416SECTORS=$[SECTORS/CYLS*CYLS-1]
417ENDPART3=$(sfdisk -uS -l $DISK | awk -v P="${DISK}3" '{if ($1==P) print $3}')
418# Mostrar espacio libre en KB (1 KB = 2 sectores)
419if [ $ENDPART3 -gt $[SECTORS/2] ]; then
420    echo $[(SECTORS-ENDPART3)/2]
421else
422    echo $[SECTORS/4]
423fi
424}
425
426
427#         ogGetPartitionActive int_ndisk
428#@brief   Muestra que particion de un disco esta marcada como de activa.
429#@param   int_ndisk   nº de orden del disco
430#@return  int_npart   Nº de partición activa
431#@exception OG_ERR_FORMAT Formato incorrecto.
432#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
433#@note    Requisitos: parted
434#@todo    Queda definir formato para atributos (arranque, oculta, ...).
435#@version 0.9 - Primera versión compatible con OpenGNSys.
436#@author  Ramon Gomez, ETSII Universidad de Sevilla
437#@date    2009/07/24
438#*/ ##
439function ogGetPartitionActive ()
440{
441# Variables locales
442local DISK
443
444# Si se solicita, mostrar ayuda.
445if [ "$*" == "help" ]; then
446    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" "$FUNCNAME 1  =>  1"
447    return
448fi
449# Error si no se recibe 1 parámetro.
450[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
451
452# Comprobar que el disco existe y listar su partición activa.
453DISK="$(ogDiskToDev $1)" || return $?
454parted $DISK print 2>/dev/null | awk '/boot/ {print $1}'
455}
456
457
458#/**
459#         ogGetPartitionId int_ndisk int_npartition
460#@brief   Devuelve el mnemonico con el tipo de sistema de archivos.
461#@param   int_ndisk      nº de orden del disco
462#@param   int_npartition nº de orden de la partición
463#@return  Identificador de tipo de partición.
464#@exception OG_ERR_FORMAT   Formato incorrecto.
465#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo.
466#@note    Requisitos: sfdisk
467#@version 0.9 - Primera versión compatible con OpenGNSys.
468#@author  Ramon Gomez, ETSII Universidad de Sevilla
469#@date    25/03/2009
470#*/ ##
471function ogGetPartitionId ()
472{
473# Variables locales.
474local DISK PART
475
476# Si se solicita, mostrar ayuda.
477if [ "$*" == "help" ]; then
478    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
479           "$FUNCNAME 1 1  =>  7"
480    return
481fi
482# Error si no se reciben 2 parámetros.
483[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
484
485# Detectar id. de tipo de particion y codificar al mnemonico.
486DISK=$(ogDiskToDev $1) || return $?
487PART=$(ogDiskToDev $1 $2) || return $?
488echo $(sfdisk --id $DISK $2 2>/dev/null)
489}
490
491
492#/**
493#         ogGetPartitionSize int_ndisk int_npartition
494#@brief   Muestra el tamano en KB de una particion determinada.
495#@param   int_ndisk      nº de orden del disco
496#@param   int_npartition nº de orden de la partición
497#@return  int_partsize - Tamaño en KB de la partición.
498#@exception OG_ERR_FORMAT   formato incorrecto.
499#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
500#@note    Requisitos: sfdisk, awk
501#@version 0.9 - Primera versión para OpenGNSys
502#@author  Ramon Gomez, ETSII Universidad de Sevilla
503#@date    2009/07/24
504#*/ ##
505function ogGetPartitionSize ()
506{
507# Variables locales.
508local PART
509
510# Si se solicita, mostrar ayuda.
511if [ "$*" == "help" ]; then
512    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
513           "$FUNCNAME 1 1  =>  10000000"
514    return
515fi
516# Error si no se reciben 2 parámetros.
517[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
518
519# Obtener el tamaño de la partición.
520DISK="$(ogDiskToDev $1)" || return $?
521PART="$(ogDiskToDev $1 $2)" || return $?
522case "$(ogGetPartitionId $1 $2)" in
523    5|f)  # Procesar detección de tamaño de partición Extendida.
524          sfdisk -l $DISK 2>/dev/null | \
525                    awk -v p=$PART '{if ($1==p) {sub (/\*/,""); print $5} }'
526          ;;
527    *)    sfdisk -s $PART
528          ;;
529esac
530}
531
532
533#/**
534#         ogListPartitions int_ndisk
535#@brief   Lista las particiones definidas en un disco.
536#@param   int_ndisk  nº de orden del disco
537#@return  str_parttype:int_partsize ...
538#@exception OG_ERR_FORMAT   formato incorrecto.
539#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
540#@note    Requisitos: \c parted \c awk
541#@attention El nº de partición se indica por el orden de los párametros \c parttype:partsize
542#@attention Las tuplas de valores están separadas por espacios.
543#@version 0.9 - Primera versión para OpenGNSys
544#@author  Ramon Gomez, ETSII Universidad de Sevilla
545#@date    2009/07/24
546#*/ ##
547function ogListPartitions ()
548{
549# Variables locales.
550local DISK PART NPARTS TYPE SIZE
551
552# Si se solicita, mostrar ayuda.
553if [ "$*" == "help" ]; then
554    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \
555           "$FUNCNAME 1  =>  NTFS:10000000 EXT3:5000000 LINUX-SWAP:1000000"
556    return
557fi
558# Error si no se recibe 1 parámetro.
559[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT "$FORMAT" || return $?
560
561# Procesar la salida de \c parted .
562DISK="$(ogDiskToDev $1)" || return $?
563NPARTS=$(ogGetPartitionsNumber $1)
564for (( PART = 1; PART <= NPARTS; PART++ )); do
565    TYPE=$(ogGetFsType $1 $PART 2>/dev/null)
566    if [ $? -eq 0 ]; then
567        SIZE=$(ogGetPartitionSize $1 $PART 2>/dev/null)
568        echo -n "$TYPE:$SIZE "
569    else
570        echo -n "EMPTY:0 "
571    fi
572done
573echo
574}
575
576
577#/**
578#         ogListPrimaryPartitions int_ndisk
579#@brief   Metafunción que lista las particiones primarias no vacías definidas en un disco.
580#@param   int_ndisk  nº de orden del disco
581#@see     ogListPartitions
582#*/ ##
583function ogListPrimaryPartitions ()
584{
585# Variables locales.
586local PARTS
587
588PARTS=$(ogListPartitions "$@") || return $?
589echo $PARTS | cut -sf1-4 -d" " | sed 's/\( EMPTY:0\)*$//'
590}
591
592
593#/**
594#         ogListLogicalPartitions int_ndisk
595#@brief   Metafunción que lista las particiones lógicas definidas en un disco.
596#@param   int_ndisk  nº de orden del disco
597#@see     ogListPartitions
598#*/ ##
599function ogListLogicalPartitions ()
600{
601# Variables locales.
602local PARTS
603
604PARTS=$(ogListPartitions "$@") || return $?
605echo $PARTS | cut -sf5- -d" "
606}
607
608
609#/**
610#         ogSetPartitionActive int_ndisk int_npartition
611#@brief   Establece cual es la partición activa de un disco.
612#@param   int_ndisk      nº de orden del disco
613#@param   int_npartition nº de orden de la partición
614#@return  (nada).
615#@exception OG_ERR_FORMAT   Formato incorrecto.
616#@exception OG_ERR_NOTFOUND Disco o partición no corresponden con un dispositivo.
617#@note    Requisitos: parted
618#@version 0.9 - Primera versión compatible con OpenGNSys.
619#@author  Ramon Gomez, ETSII Universidad de Sevilla
620#@date    2009/09/17
621#*/ ##
622function ogSetPartitionActive ()
623{
624# Variables locales
625local DISK PART
626
627# Si se solicita, mostrar ayuda.
628if [ "$*" == "help" ]; then
629    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
630           "$FUNCNAME 1 1"
631    return
632fi
633# Error si no se reciben 2 parámetros.
634[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
635
636# Comprobar que el disco existe y activar la partición indicada.
637DISK="$(ogDiskToDev $1)" || return $?
638PART="$(ogDiskToDev $1 $2)" || return $?
639parted -s $DISK set $2 boot on 2>/dev/null
640}
641
642
643#/**
644#         ogSetPartitionSize int_ndisk int_npartition int_size
645#@brief   Muestra el tamano en KB de una particion determinada.
646#@param  int_ndisk      nº de orden del disco
647#@param   int_npartition nº de orden de la partición
648#@param   int_size       tamaño de la partición (en KB)
649#@return  (nada)
650#@exception OG_ERR_FORMAT   formato incorrecto.
651#@exception OG_ERR_NOTFOUND disco o particion no detectado (no es un dispositivo).
652#@note    Requisitos: sfdisk, awk
653#@todo    Compruebar que el tamaño sea numérico positivo y evitar que pueda solaparse con la siguiente partición.
654#@version 0.9 - Primera versión para OpenGNSys
655#@author  Ramon Gomez, ETSII Universidad de Sevilla
656#@date    2009/07/24
657#*/ ##
658function ogSetPartitionSize ()
659{
660# Variables locales.
661local DISK PART SIZE
662
663# Si se solicita, mostrar ayuda.
664if [ "$*" == "help" ]; then
665    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
666           "$FUNCNAME 1 1 10000000"
667    return
668fi
669# Error si no se reciben 3 parámetros.
670[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
671
672# Obtener el tamaño de la partición.
673DISK="$(ogDiskToDev $1)" || return $?
674PART="$(ogDiskToDev $1 $2)" || return $?
675# Convertir tamaño en KB a sectores de 512 B.
676SIZE=$[$3*2] || ogRaiseError $OG_ERR_FORMAT || return $?
677# Usar \c sfdisk para redefinir el tamaño.
678sfdisk -f -uS -N$2 $DISK <<< ",$SIZE" &>/dev/null || ogRaiseError $OG_ERR_PARTITION "$1,$2" || return $?
679}
680
681
682#/**
683#         ogUpdatePartitionTable
684#@brief   Fuerza al kernel releer la tabla de particiones de los discos duros
685#@param   no requiere
686#@return  informacion propia de la herramienta
687#@note    Requisitos: \c partprobe
688#@warning pendiente estructurar la funcion a opengnsys
689#@version 0.1       Date: 27/10/2008                 Author Antonio J. Doblas Viso. Universidad de Malaga
690#@note   funcion importada de EAC
691#*/
692
693function ogUpdatePartitionTable ()
694{
695echo "Forzando al kernel la lectura de la tabla de particiones"
696list=`partprobe -s | cut -f1 -d: ` 2>/dev/null
697echo $list > /tmp/disk
698}
699
700
701
702
703function ogGetPartitionsNumber () {
704#/**  @function ogGetPartitionsNumber: @brief detecta el numero de particiones del disco duro indicado.
705#@param   int_numdisk   (indentificado EAC del disco)
706#@return  devuelve el numero paritiones del disco duro indicado
707#@warning  Salidas de errores no determinada
708#@attention Requisitos: parted
709#@note    Notas sin especificar
710#@version 0.1       Date: 27/10/2008                 Author Antonio J. Doblas Viso. Universidad de Malaga
711#*/
712           #local disco totalpart
713           #disco=`ogDiskToDev $1`
714           #totalpart=`parted $disco print | egrep ^" [0123456789] " -c`
715           #echo $totalpart
716local DISK
717#/// Contar el nº de veces que aparece el disco en su lista de particiones.
718DISK=$(ogDiskToDev $1) 2>/dev/null
719sfdisk -l $DISK 2>/dev/null | grep -c "^$DISK"
720}
721
722
723function ogDiskToRelativeDev () {
724#/**  @function ogDiskToRelativeDev: @brief Traduce los ID de discos o particiones EAC a ID Linux relativos, es decir 1 1 => sda1
725#@param  Admite 1 parametro:   $1  int_numdisk
726#@param  Admite 2 parametro:   $1   int_numdisk                    $2  int_partition
727#@return  Para 1 parametros traduce Discos Duros: Devuelve la ruta relativa linux del disco duro indicado con nomenclatura EAC.........ejemplo: IdPartition 1 => sda
728#@return  Para 2 parametros traduce Particiones: Devuelve la ruta relativa linux de la particion indicado con nomenclatura EAC...........  ejemplo: IdPartition  2 1 => sdb1
729#@warning  No definidas
730#@attention
731#@note    Notas sin especificar
732#@version 0.1       Date: 27/10/2008                 Author Antonio J. Doblas Viso. Universidad de Malaga
733#*/
734
735if [ $# = 0 ]
736then
737        Msg "Info: Traduce el identificador del dispositivo EAC a dispositivo linux \n" info
738        Msg "Sintaxis1: IdPartition int_disk -----------------Ejemplo1: IdPartition 1 -> sda " example
739        Msg "Sintaxis2: IdPartition int_disk int_partition  --Ejemplo2: IdPartition 1 2 -> sda2 " example
740
741return
742fi
743#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.
744PART=$(ogDiskToDev|cut -f$1 -d' ')$2
745echo $PART | cut -f3 -d \/
746}
747
748
749function ogDeletePartitionTable () {
750#/**  @function ogDeletePartitionTable: @brief Borra la tabla de particiones del disco.
751#@param $1 opcion A (identificador LINUX)       str_ID_linux (/dev/sda)
752#@param $1 opcion B (Identifiador EAC)                  int_numdiskEAC(1)
753#@return   la informacion propia del fdisk
754#@warning    no definidos
755#@attention
756#@note
757#@version 0.1       Date: 27/10/2008                 Author Antonio J. Doblas Viso. Universidad de Malaga
758#*/
759if [ $# = 0 ]
760then
761        Msg "sintaxis1: ogDeletePartitionTable int_disk" red
762        Msg "sintaxis2: ogDeletePartitionTable str_/dev/sdX" red
763        return
764fi
765if [ -n "${1%/dev/*}" ]
766        then
767        dev=`DiskToDev $1`
768        else
769        dev=$1
770fi
771echo -ne "o\nw" | fdisk $dev
772}
773
774
775
776function ogSetPartitionId() {
777#/**  @function ogSetPartitionId: @brief Cambia el identificador de la particion, pero no su sistema de archivos.
778#@param  $1 int_numdiskEAC
779#@param  $2 int_numpartitionEAC
780#@param  $3 str_tipoPartition admite EXT2 EXT3 NTFS FAT32 SWAP CACHE
781#@return   la propia del fdisk
782#@warning    no controla los parametros, si se introducen mal o simplemente no se introducen no muestra mensaje
783#@warning    Identifica por nombre del sistema de archivos no por número
784#@attention Requisitos:  fdisk
785#@note
786#@version 0.1       Date: 27/10/2008                 Author Antonio J. Doblas Viso. Universidad de Malaga
787#*/
788
789# Variables locales
790local DISK PART ID
791
792# Si se solicita, mostrar ayuda.
793if [ "$*" == "help" ]; then
794    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
795           "$FUNCNAME 1 1 10000000"
796    return
797fi
798# Error si no se reciben 3 parámetros.
799[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
800
801# Sustituye nº de disco por su dispositivo.
802DISK=`ogDiskToDev $1` || return $?
803PART=`ogDiskToDev $1 $2` || return $?
804
805# Elección del tipo de partición.
806ID=$(ogFsToId "$3")
807[ -n "$ID" ] || ogRaiseError $OG_ERR_PARTITION "$TYPE" || return $?
808
809echo -ne "t\n$2\n${ID}\nw\n" | fdisk $DISK 1>/dev/null 2>&1
810}
811
812
813function ogDeletePartitionsLabels () {
814#/**  @function ogDeletePartitionsLabels: @brief Elimina la informacion que tiene el kernel del cliente og sobre los labels de los sistemas de archivos
815#@param  No requiere
816#@return   Nada
817#@warning
818#@attention Requisitos:  comando interno linux rm
819#@note
820#@version 0.1       Date: 27/10/2008                 Author Antonio J. Doblas Viso. Universidad de Malaga
821#*/
822rm /dev/disk/by-label/*    # */ COMENTARIO OBLIGATORIO PARA DOXYGEN
823}
824
Note: See TracBrowser for help on using the repository browser.