Thursday, January 17, 2008

Automatic Backup of a USB Disk Upon Connection

Lately I started carrying with me an external USB hard disk. I find it useful for moving files around that I need to access wherever I go. When I come back home I usually connect it to my laptop.

I wanted to backup the files on the disk automatically, as soon as I connect it, without any interaction. Call me lazy.

There are two issues to solve here:
  1. how to run a script as soon as the disk is connected ?
  2. how to cause Bacula to run a backup job on demand (and not periodically) ?
The first issue is easily solved by adding the following udev rule in /etc/udev/local.rules that I already maintain for managing external disks:
KERNEL=="sd?1", ATTRS{serial}=="300000064029", ACTION=="add", SYMLINK+="aluminum", RUN+="/etc/bacula/scripts/backup-aluminum"
this runs the specified script (RUN+="/etc/bacula/scripts/backup-aluminum") upon addition (ACTION=="add") of the first partition (KERNEL=="sd?1") of a disk with the specified serial number. Along the way this rule adds a symbolic link to the newly added partition at /dev/aluminum.

The script being run has to exit or background as soon as possible, so as not to disrupt udev.

My script runs a backup job by calling bconsole:
#! /bin/bash
/usr/bin/bconsole -c /etc/bacula/bconsole.conf <<EOF
run aluminum-backup-job
yes

EOF
and here is the definition of aluminum-backup-job, in /etc/bacula/bacula-dir.conf:

Job {
Enabled = no
Name = aluminum-backup-job
Client = machine-cycle-fd
JobDefs = "DefaultJob"
FileSet = aluminum-fileset
Pool = aluminum-pool
Full Backup Pool = aluminum-full-pool
Write Bootstrap = "/mnt/elements/backup/aluminum.bsr"
ClientRunBeforeJob = "/etc/bacula/scripts/mount-aluminum"
ClientRunAfterJob = "/etc/bacula/scripts/umount-aluminum"
Priority = 10
}

The trick is to mark the job as disabled! This means that Bacula will not attempt to run it according to the schedule defined in DefaultJob, but it can still be run manually.

No comments:

Post a Comment