Byzantine Reality

Searching for Byzantine failures in the world around us

Automatically Backing Up WordPress

After my last host died (or more correctly, is in a coma-like state), I did what we all do in a similar state: begin to care more about backups. So I took this opportunity to write a Ruby script (since I’m not too familiar with Ruby) to backup my MySQL database and commit its contents to my CVS repository.

As a disclaimer is appropriate, let’s get it out of the way. Ruby isn’t my first programming language. That being said, Ruby made it really easy to solve this problem. Here’s what I ended up with (stored at/var/www/backup.rb):

filename = '/var/www/wp-config.php'
def get_db_info(file)
 username = nil
 password = nil
 db_name = nil

 file.each { |line|
  if line =~ /'DB_(USER|PASSWORD|NAME)', '([[:alnum:]]*)'/
   if $1 == "USER"
    username = $2
   elsif $1 == "PASSWORD"
    password = $2
   elsif $1 == "NAME"
    db_name = $2

 if username.nil? || password.nil? || db_name.nil?
  puts "[backup_db][bad] couldn't get all needed info"

 return username, password, db_name

 config_file = open("#{filename}")
rescue Errno::ENOENT
 puts "[backup_db][bad] File '#{filename}' didn't exist"
 puts "[backup_db][good] File '#{filename}' existed"

username, password, db_name = get_db_info(config_file)
sql_dump_info = `mysqldump --user=#{username} --password=#{password} #{db_name}`
backup_file ="/var/www/my_backup.sql", "w+")
backup_file.puts sql_dump_info

So at the end of this script I initially wasn’t sure what to do with my output, and just saved it to a flat file, analogous to my old solution. For now I have the less-than-optimal result of leaving it as a flat-file (same as wp-backup) although once I get CVS and SSH to play nicely on my Linux box all I have to do is add this to the end of my Ruby script:

`cvs commit -m 'Nightly commit' .`

You can replace this line with whatever line you use to commit changes to your version control system. Then, all you need to do is schedule your Ruby script to be run every day by running crontab -e and modifying it to:

0      0       *       *       *       ruby /var/www/backup.rb

And there you go! Now your data is automatically backed up daily at midnight and you have some exposure to a new programming language (presuming you haven’t seen Ruby before). It’s not yet optimal for me yet since it’s not version controlling it, but we’ll sort that out soon.

Update (08/08/08): 
Using CVS to solve this problem was horribly complicated, so I opted for a different solution. On my MacBook Pro I edited my crontab to:
0       1       *       *       *       /usr/local/bin/wget http://www.byzantine\
.com/my_backup.sql -O ~/cgb/my_backup.sql

Which now fetches my backup file from my site and puts it nicely in a directory that I commit to CVS nightly. Whew! What a pain in the ass.