source: client/engine/Disk.lib @ 7dc06be9

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-instalacion
Last change on this file since 7dc06be9 was a31f7a9, checked in by Irina Gómez <irinagomez@…>, 6 years ago

#802 #889 ogHidePartition and ogUnhidePartition: Add Windows and Windows Reserved Partitions. ogSaveImageInfo and ogRestoreUuidPartitions: Only save/restore GUID Partition Table.

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