En este artículo voy a demostrar cómo restaurar la copia de respaldo más fresca de un cliente, previa a una fecha específica, desde la consola de Bacula.



El artículo Cómo instalar y configurar Bacula en Debian explica detalladamente los pasos de configuración del director de Bacula. Previo a restaurar una copia de seguridad es necesario definir, en la configuración del director, un trabajo de restore específico para el cliente en cuestión.

Crear un trabajo de restauración en la configuración del director:

root@debian7:~# nano /usr/local/bacula/etc/bacula-dir.conf

Especificar un nombre para el trabajo, el tipo "Restore" y el cliente (previamente registrado en el director a través de una sección "Client"):

Job {
  Name = "RestoreFBSD10"
  Type = Restore
  Client=fbsd10-fd
  Storage = File1
# The FileSet and Pool directives are not used by Restore Jobs
# but must not be removed
  FileSet="Full Set"
  Pool = File
  Messages = Standard
  Where = /usr/local/bacula/restore
}

Además es necesario indicar el medio de almacenamiento destino y un directorio ("Where"). Las directivas "FileSet" y "Pool" no son utilizadas por los trabajos de restore pero aún así deben ser especificadas.

Reiniciar el director para que reconozca el nuevo trabajo:

root@debian7:~# service bacula-dir restart
Stopping Bacula Director: bacula-dir
Starting Bacula Director: bacula-dir

A continuación, abrir la consola de Bacula:

root@debian7:~# /usr/local/bacula/sbin/bconsole 
Connecting to Director debian7:9101
1000 OK: 102 debian7-dir Version: 7.4.4 (28 September 2016)
Enter a period to cancel a command.
*

Se desea restaurar una copia de seguridad de los archivos del cliente "fbsd10-fd" previa al 31 de octubre de 2016. El primer paso consiste en listar las copias de seguridad disponibles para dicho cliente:

*list jobs client=fbsd10-fd
+-------+------------------+---------------------+------+-------+----------+----------+-----------+
| jobid | name             | starttime           | type | level | jobfiles | jobbytes | jobstatus |
+-------+------------------+---------------------+------+-------+----------+----------+-----------+
|     9 | BackupFBSD10     | 2016-10-28 09:42:53 | B    | F     |        0 |        0 | A         |
|    10 | BackupFBSD10     | 2016-10-28 10:01:12 | B    | F     |        0 |        0 | f         |
|    11 | BackupFBSD10     | 2016-10-28 10:05:55 | B    | F     |      448 |  476,254 | T         |
|    13 | BackupFBSD10     | 2016-10-28 23:05:03 | B    | I     |        0 |        0 | T         |
|    16 | BackupFBSD10     | 2016-10-29 23:05:02 | B    | I     |        0 |        0 | T         |
|    19 | BackupFBSD10     | 2016-10-30 23:05:03 | B    | D     |        0 |        0 | T         |
|    22 | BackupFBSD10     | 2016-10-31 23:05:03 | B    | I     |        3 |      283 | T         |
|    25 | BackupFBSD10     | 2016-11-01 23:05:03 | B    | I     |        0 |        0 | T         |
|    28 | BackupFBSD10     | 2016-11-02 23:05:02 | B    | I     |        0 |        0 | T         |
|    31 | BackupFBSD10     | 2016-11-03 23:05:02 | B    | I     |        0 |        0 | T         |
+-------+------------------+---------------------+------+-------+----------+----------+-----------+

Las copias de seguridad disponibles consisten en aquellos trabajos de backup que hayan finalizado correctamente (cuyo estado es igual a "T").

De acuerdo a la ayuda (comando help), el comando restore se utiliza para recuperar datos desde una copia de seguridad:

*help restore
  Command       Description
  =======       ===========
  restore       Restore files

Arguments:
        where=</path> client=<client> storage=<storage> bootstrap=<file> restorejob=<job>
        comment=<text> jobid=<jobid> copies done select all

When at a prompt, entering a period cancels the command.

Restaurar todos los archivos de una copia de seguridad

Para restaurar todos los archivos de una copia de seguridad, utilizar el comando restore all:

*restore client=fbsd10-fd all

First you select one or more JobIds that contain files
to be restored. You will be presented several methods
of specifying the JobIds. Then you will be allowed to
select which files from those JobIds are to be restored.

To select the JobIds, you have the following choices:
     1: List last 20 Jobs run
     2: List Jobs where a given File is saved
     3: Enter list of comma separated JobIds to select
     4: Enter SQL list command
     5: Select the most recent backup for a client
     6: Select backup for a client before a specified time
     7: Enter a list of files to restore
     8: Enter a list of files to restore before a specified time
     9: Find the JobIds of the most recent backup for a client
    10: Find the JobIds for a backup for a client before a specified time
    11: Enter a list of directories to restore for found JobIds
    12: Select full restore to a specified Job date
    13: Cancel
Select item: (1-13):

Seleccionar la opción "6" para restaurar la copia de backup más reciente anterior a una fecha especificada:

Select item:  (1-13): 6
The restored files will the most current backup
BEFORE the date you specify below.

Enter date as YYYY-MM-DD HH:MM:SS :

Se desea obtener la copia de respaldo más reciente previo al 31 de octubre de 2016, por lo tanto en este caso es necesario especificar la fecha "2016-10-31 00:00:00":

Enter date as YYYY-MM-DD HH:MM:SS :2016-10-31 00:00:00
Automatically selected FileSet: Full Set
+-------+-------+----------+----------+---------------------+------------+
| jobid | level | jobfiles | jobbytes | starttime           | volumename |
+-------+-------+----------+----------+---------------------+------------+
|    11 | F     |      448 |  476,254 | 2016-10-28 10:05:55 | Local-0001 |
+-------+-------+----------+----------+---------------------+------------+
You have selected the following JobId: 11

Building directory tree for JobId(s) 11 ...  ++++++++++++++++++++++++++++++++++++++++++++++
420 files inserted into the tree and marked for extraction.

You are now entering file selection mode where you add (mark) and
remove (unmark) files to be restored. No files are initially added, unless
you used the "all" keyword on the command line.
Enter "done" to leave this mode.

cwd is: /
$ 

Notar que Bacula selecciona el trabajo de backup del día 28 de octubre, ya que los días 29 y 30 no hubo cambios (contrastar con la salida previa del comando list).

A continuación es necesario especificar los archivos a extraer de la copia de seguridad seleccionada. Como se ha especificado la opción "all" en el comando restore, se van a recuperar todos los archivos en la copia. Por lo tanto ingresar "done" para finalizar:

$ done
Bootstrap records written to /opt/bacula/working/debian7-dir.restore.1.bsr
Bootstrap records written to /opt/bacula/working/debian7-dir.restore.1.bsr

The Job will require the following (*=>InChanger):
   Volume(s)                 Storage(s)                SD Device(s)
===========================================================================
   
    Local-0001                File1                     FileStorage              

Volumes marked with "*" are in the Autochanger.


448 files selected to be restored.

The defined Restore Job resources are:
     1: RestoreArchivosLocales
     2: RestoreFBSD10
Select Restore Job (1-2)

Luego, seleccionar el trabajo de backup creado previamente e ingresar "yes" para despachar el trabajo de restore:

Select Restore Job (1-2): 2
Using Catalog "MyCatalog"
Run Restore job
JobName:         RestoreFBSD10
Bootstrap:       /opt/bacula/working/debian7-dir.restore.1.bsr
Where:           /usr/local/bacula/restore
Replace:         Always
FileSet:         Full Set
Backup Client:   fbsd10-fd
Restore Client:  fbsd10-fd
Storage:         File1
When:            2016-11-04 09:31:05
Catalog:         MyCatalog
Priority:        10
Plugin Options:  
OK to run? (yes/mod/no): yes
Job queued. JobId=33

De acuerdo a la configuración del trabajo, los archivos se restauran en el mismo cliente:

Backup Client:   fbsd10-fd
Restore Client:  fbsd10-fd

El trabajo finaliza correctamente:

*list jobs client=fbsd10-fd
+-------+-------------------+---------------------+------+-------+----------+-----------+-----------+
| jobid | name              | starttime           | type | level | jobfiles | jobbytes  | jobstatus |
+-------+-------------------+---------------------+------+-------+----------+-----------+-----------+
|     9 | BackupFBSD10      | 2016-10-28 09:42:53 | B    | F     |        0 |         0 | A         |
|    10 | BackupFBSD10      | 2016-10-28 10:01:12 | B    | F     |        0 |         0 | f         |
|    11 | BackupFBSD10      | 2016-10-28 10:05:55 | B    | F     |      448 |   476,254 | T         |
|    13 | BackupFBSD10      | 2016-10-28 23:05:03 | B    | I     |        0 |         0 | T         |
|    16 | BackupFBSD10      | 2016-10-29 23:05:02 | B    | I     |        0 |         0 | T         |
|    19 | BackupFBSD10      | 2016-10-30 23:05:03 | B    | D     |        0 |         0 | T         |
|    22 | BackupFBSD10      | 2016-10-31 23:05:03 | B    | I     |        3 |       283 | T         |
|    25 | BackupFBSD10      | 2016-11-01 23:05:03 | B    | I     |        0 |         0 | T         |
|    28 | BackupFBSD10      | 2016-11-02 23:05:02 | B    | I     |        0 |         0 | T         |
|    31 | BackupFBSD10      | 2016-11-03 23:05:02 | B    | I     |        0 |         0 | T         |
|    33 | RestoreFBSD10     | 2016-11-04 09:31:34 | R    | F     |      448 | 1,925,559 | T         |
+-------+-------------------+---------------------+------+-------+----------+-----------+-----------+

Acceder al cliente en cuestión y verificar que los archivos hayan sido recuperados:

root@fbsd10:~ # ll /usr/local/bacula/restore/
total 9
drwxr-xr-x  26 root  wheel  114 Oct 28 08:57 etc/
root@fbsd10:~ # du -hs /usr/local/bacula/restore/  
3.4M    /usr/local/bacula/restore/

Sólo se ha recuperado el directorio /etc porque así está configurado el trabajo de backup para dicho cliente.

Luego de examinar el contenido del directorio restaurado y recuperar los archivos necesarios, no olvidar borrarlo:

root@fbsd10:~ # rm -fr /usr/local/bacula/restore/etc

Restaurar un archivo o directorio específico de una copia de backup

En caso de que se deseen restaurar archivos o directorios específicos desde una copia de backup (no todos los archivos), no se debe utilizar la directiva "all":

*restore client=fbsd10-fd
Using Catalog "MyCatalog"

First you select one or more JobIds that contain files
to be restored. You will be presented several methods
of specifying the JobIds. Then you will be allowed to
select which files from those JobIds are to be restored.

To select the JobIds, you have the following choices:
     1: List last 20 Jobs run
     2: List Jobs where a given File is saved
     3: Enter list of comma separated JobIds to select
     4: Enter SQL list command
     5: Select the most recent backup for a client
     6: Select backup for a client before a specified time
     7: Enter a list of files to restore
     8: Enter a list of files to restore before a specified time
     9: Find the JobIds of the most recent backup for a client
    10: Find the JobIds for a backup for a client before a specified time
    11: Enter a list of directories to restore for found JobIds
    12: Select full restore to a specified Job date
    13: Cancel
Select item:  (1-13):

Igual que antes, indicar la fecha deseada:

Select item:  (1-13): 6
The restored files will the most current backup
BEFORE the date you specify below.

Enter date as YYYY-MM-DD HH:MM:SS :2016-10-31 00:00:00
Automatically selected FileSet: Full Set
+-------+-------+----------+----------+---------------------+------------+
| jobid | level | jobfiles | jobbytes | starttime           | volumename |
+-------+-------+----------+----------+---------------------+------------+
|    11 | F     |      448 |  476,254 | 2016-10-28 10:05:55 | Local-0001 |
+-------+-------+----------+----------+---------------------+------------+
You have selected the following JobId: 11

Building directory tree for JobId(s) 11 ...  ++++++++++++++++++++++++++++++++++++++++++++++
420 files inserted into the tree.

You are now entering file selection mode where you add (mark) and
remove (unmark) files to be restored. No files are initially added, unless
you used the "all" keyword on the command line.
Enter "done" to leave this mode.

cwd is: /
$

El modo de selección de archivos posee un conjunto de comandos para examinar la copia de seguridad seleccionada y elegir (marcar) qué archivos/directorios restaurar:

$ help
  Command    Description
  =======    ===========
  add        add dir/file to be restored recursively, wildcards allowed
  cd         change current directory
  count      count marked files in and below the cd
  delete     delete dir/file to be restored recursively in dir
  dir        long list current directory, wildcards allowed
  done       leave file selection mode
  estimate   estimate restore size
  exit       same as done command
  find       find files, wildcards allowed
  help       print help
  ls         list current directory, wildcards allowed
  lsmark     list the marked files in and below the cd
  mark       mark dir/file to be restored recursively, wildcards allowed
  markdir    mark directory name to be restored (no files)
  pwd        print current working directory
  unmark     unmark dir/file to be restored recursively in dir
  unmarkdir  unmark directory name only no recursion
  quit       quit and do not do restore
  ?          print help

Es posible listar el directorio actual (ls) y cambiar con cd al igual que en Bash:

$ ls
etc/

El comando ls no lista recursivamente ni acepta parámetros, por lo que es necesario cambiar al directorio que se desea listar:

$ cd etc
cwd is: /etc/
$ ls rc*
rc
rc.bsdextended
rc.conf
rc.conf.d
rc.d/
rc.firewall
rc.initdiskless
rc.resume
rc.sendmail
rc.shutdown
rc.subr
rc.suspend

A modo de ejemplo, sólo se desea restaurar el archivo rc.conf:

$ mark rc.conf
1 file marked.

Es posible listar la selección dentro del directorio actual con el comando lsmark:

$ lsmark
*rc.conf

Terminar con done y lanzar el trabajo:

$ done
Bootstrap records written to /opt/bacula/working/debian7-dir.restore.1.bsr
Bootstrap records written to /opt/bacula/working/debian7-dir.restore.1.bsr

The Job will require the following (*=>InChanger):
   Volume(s)                 Storage(s)                SD Device(s)
===========================================================================
   
    Local-0001                File1                     FileStorage              

Volumes marked with "*" are in the Autochanger.


1 file selected to be restored.

The defined Restore Job resources are:
     1: RestoreArchivosLocales
     2: RestoreFBSD10
Select Restore Job (1-2): 2
Using Catalog "MyCatalog"
Run Restore job
JobName:         RestoreFBSD10
Bootstrap:       /opt/bacula/working/debian7-dir.restore.1.bsr
Where:           /usr/local/bacula/restore
Replace:         Always
FileSet:         Full Set
Backup Client:   fbsd10-fd
Restore Client:  fbsd10-fd
Storage:         File1
When:            2016-11-04 11:05:42
Catalog:         MyCatalog
Priority:        10
Plugin Options:  
OK to run? (yes/mod/no): yes
Job queued. JobId=35

El trabajo 35 finaliza correctamente y restaura el único archivo seleccionado:

*list jobid=35
+-------+-------------------+---------------------+------+-------+----------+----------+-----------+
| jobid | name              | starttime           | type | level | jobfiles | jobbytes | jobstatus |
+-------+-------------------+---------------------+------+-------+----------+----------+-----------+
|    35 | RestoreFBSD10     | 2016-11-04 11:06:06 | R    | F     |        1 |      845 | T         |
+-------+-------------------+---------------------+------+-------+----------+----------+-----------+

En el cliente se restaura el archivo, respetando el directorio destino (directiva Where del trabajo) y la jerarquía de directorios dentro de la copia de backup:

root@fbsd10:~ # ls -lR /usr/local/bacula/restore
total 1
drwxr--r--  2 root  wheel  3 Nov  4 11:05 etc

/usr/local/bacula/restore/etc:
total 5
-rw-r--r--  1 root  wheel  845 Oct 28 09:06 rc.conf

Restaurar una copia de backup en otro host

A veces es deseable poder recuperar una copia de backup de un cliente en otro host. Ya sea porque el cliente está apagado/offline/muerto, porque no tiene espacio disponible, o simplemente porque se desea examinar un archivo o fecha en particular como análisis forense luego de un incidente de seguridad informática.

A modo de ejemplo, recuperar sólo el archivo rc.conf de la copia de backup más fresca previa al 31 de octubre de 2016 del cliente "fbsd10-fd".

Seleccionar la copia de backup más fresca previa al 31 de octubre de 2016 para el cliente "fbsd10-fd":

*restore client=fbsd10-fd
Using Catalog "MyCatalog"

First you select one or more JobIds that contain files
to be restored. You will be presented several methods
of specifying the JobIds. Then you will be allowed to
select which files from those JobIds are to be restored.

To select the JobIds, you have the following choices:
     1: List last 20 Jobs run
     2: List Jobs where a given File is saved
     3: Enter list of comma separated JobIds to select
     4: Enter SQL list command
     5: Select the most recent backup for a client
     6: Select backup for a client before a specified time
     7: Enter a list of files to restore
     8: Enter a list of files to restore before a specified time
     9: Find the JobIds of the most recent backup for a client
    10: Find the JobIds for a backup for a client before a specified time
    11: Enter a list of directories to restore for found JobIds
    12: Select full restore to a specified Job date
    13: Cancel
Select item:  (1-13): 6
The restored files will the most current backup
BEFORE the date you specify below.

Enter date as YYYY-MM-DD HH:MM:SS :2016-10-31 00:00:00
Automatically selected FileSet: Full Set
+-------+-------+----------+----------+---------------------+------------+
| jobid | level | jobfiles | jobbytes | starttime           | volumename |
+-------+-------+----------+----------+---------------------+------------+
|    11 | F     |      448 |  476,254 | 2016-10-28 10:05:55 | Local-0001 |
+-------+-------+----------+----------+---------------------+------------+
You have selected the following JobId: 11

Building directory tree for JobId(s) 11 ...  ++++++++++++++++++++++++++++++++++++++++++++++
420 files inserted into the tree.

You are now entering file selection mode where you add (mark) and
remove (unmark) files to be restored. No files are initially added, unless
you used the "all" keyword on the command line.
Enter "done" to leave this mode.

cwd is: /
$

Seleccionar sólo el archivo /etc/rc.conf:

$ cd etc
cwd is: /etc/
$ mark rc.conf
1 file marked.
$ done
Bootstrap records written to /opt/bacula/working/debian7-dir.restore.2.bsr
Bootstrap records written to /opt/bacula/working/debian7-dir.restore.2.bsr

The Job will require the following (*=>InChanger):
   Volume(s)                 Storage(s)                SD Device(s)
===========================================================================
   
    Local-0001                File1                     FileStorage              

Volumes marked with "*" are in the Autochanger.


1 file selected to be restored.

The defined Restore Job resources are:
     1: RestoreArchivosLocales
     2: RestoreFBSD10
Select Restore Job (1-2):

Luego seleccionar el trabajo de backup. En este caso "RestoreFBSD10":

Select Restore Job (1-2): 2
Using Catalog "MyCatalog"
Run Restore job
JobName:         RestoreFBSD10
Bootstrap:       /opt/bacula/working/debian7-dir.restore.2.bsr
Where:           /usr/local/bacula/restore
Replace:         Always
FileSet:         Full Set
Backup Client:   fbsd10-fd
Restore Client:  fbsd10-fd
Storage:         File1
When:            2016-11-04 11:31:03
Catalog:         MyCatalog
Priority:        10
Plugin Options:  
OK to run? (yes/mod/no):

En este momento es posible cambiar el host (tiene que ser un cliente registrado en el director) destino de la restauración. En este punto es crucial que, en la configuración del trabajo, la restauración no sea pisando el contenido original (Where = / o sin especificar) sino que sea en un directorio temporal. De lo contrario las consecuencias pueden ser catastróficas.

Para modificar el host destino de los archivos, ingresar "mod":

OK to run? (yes/mod/no): mod
Parameters to modify:
     1: Level
     2: Storage
     3: Job
     4: FileSet
     5: Restore Client
     6: When
     7: Priority
     8: Bootstrap
     9: Where
    10: File Relocation
    11: Replace
    12: JobId
    13: Plugin Options
Select parameter to modify (1-13):

Con "5" es posible cambiar el cliente destino (Restore Client):

Select parameter to modify (1-13): 5
The defined Client resources are:
     1: debian7-fd
     2: fbsd10-fd
Select Client (File daemon) resource (1-2):

Seleccionar el cliente donde se desean recuperar los archivos:

Select Client (File daemon) resource (1-2): 1
Run Restore job
JobName:         RestoreFBSD10
Bootstrap:       /opt/bacula/working/debian7-dir.restore.2.bsr
Where:           /usr/local/bacula/restore
Replace:         Always
FileSet:         Full Set
Backup Client:   fbsd10-fd
Restore Client:  debian7-fd
Storage:         File1
When:            2016-11-04 11:31:03
Catalog:         MyCatalog
Priority:        10
Plugin Options:  
OK to run? (yes/mod/no):

Por último, lanzar el trabajo:

OK to run? (yes/mod/no): yes
Job queued. JobId=36
You have messages.
*list jobid=36
+-------+-------------------+---------------------+------+-------+----------+----------+-----------+
| jobid | name              | starttime           | type | level | jobfiles | jobbytes | jobstatus |
+-------+-------------------+---------------------+------+-------+----------+----------+-----------+
|    36 | RestoreFBSD10     | 2016-11-04 11:37:31 | R    | F     |        1 |      845 | T         |
+-------+-------------------+---------------------+------+-------+----------+----------+-----------+
*

El trabajo finaliza correctamente.

El archivo se recupera correctamente en el cliente "debian7-fd":

root@debian7:~# ls -lR /usr/local/bacula/restore
/usr/local/bacula/restore:
total 4
drwxr--r-- 2 root root 4096 nov  4 11:37 etc

/usr/local/bacula/restore/etc:
total 4
-rw-r--r-- 1 root root 845 oct 28 09:06 rc.conf

Referencias

Bacula Main Reference Guide

Console and Operators Guide


Tal vez pueda interesarte


Compartí este artículo