close Warning: Failed to sync with repository "ogBrowser-Git": (1366, "Incorrect string value: '\\xF0\\x9F\\x93\\xA6 I...' for column 'message' at row 1"); repository information may be out of date. Look in the Trac log for more information including mitigation strategies.

source: client/engine/Disk.lib @ beed37b

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 beed37b was 4850d65, checked in by ramon <ramongomez@…>, 9 years ago

#802: Corregir errata en revisión r5748.

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

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