source: client/engine/Disk.lib @ b1f562f

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 b1f562f was 5804229, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.3: Detección correcta de sistemas de archivos en configuración inicial de cliente (modifica #397).

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

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